python编程从入门到实践学习笔记

文章目录

  • 字符串
    • print(name.title())
    • print(name.upper())
    • print(name.lower())
  • 合并字符串
  • 删除空白
    • name.rstrip()
    • name.lstrip()
    • name.strip()
  • 方法str(name)
  • 数学运算
  • python之禅
  • 列表
    • 1.列表添加元素方法
      • name.append()
      • name.insert()
    • 2.列表删除元素方法
      • del name[]
      • 方法pop()
    • 3.删除列表任意位置元素
      • remove()
    • 4.排序列表
      • 方法sort()
      • 函数sorted()
    • 5.倒序列表
      • reverse()
    • 6.确定列表长度
      • 函数len()
    • 7.操作列表
    • **8.数字列表**
      • 1.函数range()
        • 1.使用range()创建数字列表
        • 2.指定区间
      • 2.对数字列表简单统计计算
        • min(),max(),sun()函数
      • 3.列表解析
      • 4.切片
        • 1.提取
        • 2.遍历
        • 3.复制
      • 5.元组
        • 1.定义元组
        • 2.遍历元组中的值
        • 3.修改元组变量
    • 6.字典
      • 嵌套
    • 用户输入和while循环
      • 函数input()的工作原理
      • 使用int()来获取数值输入
      • 求模运算符%
      • While循环
    • 函数
      • 位置实参
      • 返回值
      • 结合使用任意数量或的实参和结合位置实参
      • 将函数存储在模块中
      • 函数编写指南
      • 导入类
    • 文件和异常
      • 写入文件
      • 异常
      • 存储数据
      • 重构
    • 测试代码
      • 测试类

字符串

name.py

print(name.title())

将单词头变为大写

print(name.upper())

全部变为大写

print(name.lower())

全部变为小写

合并字符串

用+连接
\t(制表符)=tab

删除空白

name.rstrip()

删除末尾空白
只是暂时的删除。永久删除需要将name.rstrip()存入name中

name.lstrip()

删除开头空白

name.strip()

删除两端空白

方法str(name)

将非字符串转变成字符串

数学运算

进行除法会将结果转变成浮点型

python之禅

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> 

列表

例:

bicycles = ['track','cannondale','redline','specialized']
print(bicycles[0].title())
print(bicycles[-1].title())#-1可以返回最后一个元素

输出结果:

Track
Specialized

可以通过+进行字符串的连接
列表中的元素可以在后赋值进行修改

1.列表添加元素方法

name.append()

将新元素添加到列表的末尾
通常用于先创建一个空列表。然后逐渐使用append函数进行添加元素

name.insert()

在列表的任意位置添加新元素,需要指定新元素的位置和值

name = ['apple','car','kid']
name.insert(0,'dog')
print(name)
name.insert(2,'pig')
print(name)

结果

['dog', 'apple', 'car', 'kid']
['dog', 'apple', 'pig', 'car', 'kid']

2.列表删除元素方法

del name[]

方法一接上例

del name[0]
print(name)
del name[2]
print(name)

结果

['apple', 'pig', 'car', 'kid']
['apple', 'pig', 'kid']

方法pop()

删除末尾元素
接上例

new_name = name.pop()#将name的最后一个元素删除并将删除的元素存入new_name
print(name)
print(new_name)#new_是一个自定义名称

结果

['apple', 'pig']
'kid'

如果不加new_那么结果将变成被删除的那个元素

name = name.pop()
print(name)

结果

'kid'

3.删除列表任意位置元素

name = ['apple','car','kid']
new_name=name.pop(1)

结果

['apple', 'kid']

如不知道位置只知道值则使用

remove()

指定进行删除
例接上

new_name=name.remove('kid')
print(name)

结果

['apple']

remove()只删除发现的第一个值
也可将要删除的元素存入一个变量中然后在remove的括号里输入变量名进行删除。

4.排序列表

方法sort()

对列表进行永久性排序

list = ['abc','ikj','sfge','bdj']
list.sort()
print(list)
list.sort(reverse=True)
print(list)

结果

['abc', 'bdj', 'ikj', 'sfge']
['sfge', 'ikj', 'bdj', 'abc']

可利用

函数sorted()

对列表进行临时排序

list = ['abc','ikj','sfge','bdj']
print(list)#原列表
print(sorted(list))#临时排序列表
print(list)#原列表不变
print(sorted(list,reverse=True))#在临时排序列表中倒序输出

结果

['abc', 'ikj', 'sfge', 'bdj']
['abc', 'bdj', 'ikj', 'sfge']
['abc', 'ikj', 'sfge', 'bdj']
['sfge', 'ikj', 'bdj', 'abc']

5.倒序列表

reverse()

接上

list.reverse()

结果

['bdj', 'sfge', 'ikj', 'abc']

6.确定列表长度

函数len()

接上

print (len(list))

结果为

4

7.操作列表

1.遍历整个列表

magicians = ['alice','david','carolina']
for magician in magicians:#将magicians取出一个放入magician
    print(magician)
    print(magician.title()+",that was a great trick!")
    print("I can't wait to see your next trick, "+ magician.title()+".\n")
print("Thank you,everyone.That was a great magic show!")    

结果

alice
Alice,that was a great trick!
I can't wait to see your next trick, Alice.

david
David,that was a great trick!
I can't wait to see your next trick, David.

carolina
Carolina,that was a great trick!
I can't wait to see your next trick, Carolina.

Thank you,everyone.That was a great magic show!
#for循环一个个取出存入输出

2.避免缩进错误,for in后不要遗漏冒号

8.数字列表

1.函数range()

for value in range(1,5):#从第一个值开始到指定值停止所以不包括5
    print(value)
1
2
3
4
1.使用range()创建数字列表
numbers = list(range(1,6))
print(numbers)
[1, 2, 3, 4, 5]
2.指定区间

1-10的偶数

even_numbers = list(range(2,11,2))
print(even_numbers)
[2, 4, 6, 8, 10]

1-10的平方

squares = []
for value in range(1,11):
    square = value**2
    squares.append(square)
print(squares)    
缩减
squares = []
for value in range(1,11):
    squares.append(value**2)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

2.对数字列表简单统计计算

min(),max(),sun()函数
digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
0
9
45
>>> digits = [1,2,3,4,5,6,7,8,9,0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45

3.列表解析

精简代码

squares = [value**2 for value in range(1,11)]#for语句后没有:
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

4.切片

1.提取
players = ['charles','martina','michael','florence','eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[2:])
print(players[-3:])
['charles', 'martina', 'michael']
['martina', 'michael', 'florence']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
2.遍历
players = ['charles','martina','michael','florence','eli']
print("Here are the first three players on my team:")
for player in players[:3]:
    print(player.title())
Here are the first three players on my team:
Charles
Martina
Michael
3.复制
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]#如若不使用切片则下面的增加会出错。

my_foods.append('cannoli')
friend_foods.append('ice cream')

print("My favorite foods are:")
print(my_foods)

print("\nMy friend's favorite foods are:")
print(friend_foods)
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']

My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']

5.元组

1.定义元组

定义不可修改的值,不使用方括号用圆括号

dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
200
50

尝试修改会报错。

2.遍历元组中的值
for dimension in dimensions:
    print(dimension)
200
50
3.修改元组变量

重新定义赋值

6.字典

alien_0 = {'color': 'green', 'points': 5}
#访问字典中的值
print(alien_0['color'])
print(alien_0['points'])

new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
#添加键-值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
#修改字典中的值
print("The alien is " + alien_0['color'] + '.')
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + '.')
alien_0['speed'] = 'medium'
print(alien_0)
#删除键-值对
del alien_0['color']
del alien_0['points']
print(alien_0)

print("Original x-position: " +str(alien_0['x_position']))
#向右移动外星人
#根据外星人当前的速度决定将其移动多远
if alien_0['speed'] == 'slow':
    x_increment = 1
elif alien_0['speed'] == 'medium':
    x_increment = 2
else:
    #这个外星人的速度一定很快
    x_increment =3
#新位置等于老位置加上增量
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))
alien_0['speed'] = 'fast'
if alien_0['speed'] == 'slow':
    x_increment = 1
elif alien_0['speed'] == 'medium':
    x_increment = 2
else:
    #这个外星人的速度一定很快
    x_increment =3
#新位置等于老位置加上增量
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))
green
5
You just earned 5 points!
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
The alien is green.
The alien is now yellow.
{'color': 'yellow', 'points': 5, 'x_position': 0, 'y_position': 25, 'speed': 'medium'}
{'x_position': 0, 'y_position': 25, 'speed': 'medium'}
Original x-position: 0
New x-position: 2
New x-position: 5

favorite_languages = {
    'jen': 'python' ,
    'sarah': 'c' ,
    'edward': 'ruby',
    'phil': 'python',
    }
print("Sarah's favorite language is " +
      favorite_languages['sarah'].title()+
      ".")  
#方法items()遍历键-值对      
for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " +
          language.title() + ".")
#方法keys()遍历键或者直接打:      values()可遍历所有值
for name in favorite_languages.keys():
    print(name.title())           
Sarah's favorite language is C.
>>> favorite_languages['sarah']
'c'
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.
Jen
Sarah
Edward
Phil

对包含重复元素的列表调用set().

favorite_languages = {
    'jen': 'python' ,
    'sarah': 'c' ,
    'edward': 'ruby',
    'phil': 'python',
    }
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
	print(language.title())
The following languages have been mentioned:
Python
Ruby
C

嵌套

字典列表

aliens=[]
for alien_number in range(30):
    new_alien = {'color':'green','points':5,'speed':'slow'}
    aliens.append(new_alien)
for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10
for alien in aliens[4:6]:        
    if alien['color'] == 'green':
        alien['color'] = 'red'
        alien['speed'] = 'fast'
        alien['points'] = 15
for alien in aliens[:10]:
    print(alien)
    print("...")
print("Total number of aliens:" + str(len(aliens)))
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
...
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
...
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
...
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
{'color': 'red', 'points': 15, 'speed': 'fast'}
...
{'color': 'red', 'points': 15, 'speed': 'fast'}
...
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens:30

在字典里储存列表

pizza = {
    'crust' : 'thick',
    'toppings':['mushrooms','extra cheese'],
    }
print("You ordered a " + pizza['crust'] + "-crust pizza " +
      "with the following toppings:")
for topping in pizza['toppings']:
    print("\t" +topping)
    
You ordered a thick-crust pizza with the following toppings:
	mushrooms
	extra cheese
favorite_languages = {
    'jen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
    }
for name,languages in favorite_languages.items():
    print("\n" + name.title() + "'s favorite languages are :")
    for language in languages:
        print("\t" +language.title())
    
    

Jen's favorite languages are :
	Python
	Ruby

Sarah's favorite languages are :
	C

Edward's favorite languages are :
	Ruby
	Go

Phil's favorite languages are :
	Python
	Haskell

在字典中存储字典

users = {
    'aeinstein':{
        'first':'albert',
        'last':'einstein',
        'location':'princeton',
        },
    'mcurie':{
        'first':'marie',
        'last':'curie',
        'location':'paris',
        },
    }
for username,user_info in users.items():
    print("\nUsername: " +username)
    full_name = user_info['first'] +" "+ user_info['last']
    location = user_info['location']
    print("\tFull name: " + full_name.title())
    print("\tLocation:" + location.title())
    

Username: aeinstein
	Full name: Albert Einstein
	Location:Princeton

Username: mcurie
	Full name: Marie Curie
	Location:Paris

用户输入和while循环

函数input()的工作原理

函数input()让程序暂停运行,等待用户输入一些文本,输入后存储在一个变量中,方便使用。
input()让输入变成字符串

prompt = "请输入你的名字"
prompt += ":"

name = input (prompt)
print("\n 你好,"+ name +"!")

请输入你的名字:hh

 你好,hh!

使用int()来获取数值输入

height = input("How tall are you, in inches?")
height = int(height)

if height >=36:
    print("\nYou're tall enough to ride!")
else:
    print("\nYou'll be able to ride when you're a little older.")

How tall are you, in inches?71

You're tall enough to ride!

求模运算符%

只指出余数是多少,可以用来判断一个数是基数还是偶数

number = input("输入一个数字高数你是奇数还是偶数:")
number = int(number)

if number % 2 == 0:
    print("\nThe number "+ str(number) +" is even.")
else:    
    print("\nThe number "+ str(number) +" is odd.")
    

输入一个数字高数你是奇数还是偶数:42

The number 42 is even.

While循环

prompt = "\n输入内容,将在下面输出:"
prompt += "\n输入'quit'结束运行"

message =  " "
while message != 'quit':
    message = input(prompt)
    if message != 'quit':
        print(message)

prompt = "\n输入内容,将在下面输出:"
prompt += "\n输入'quit'结束运行"

active = True
while active:
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)
# active 作为标志判断程序是否继续运行
输入内容,将在下面输出:
输入'quit'结束运行hello
hello

输入内容,将在下面输出:
输入'quit'结束运行quit
>>> 
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finnished.)"

while True:
    city = input(prompt)

    if city == 'quit':
        break
    else:
        print("I'd love to go to " + city.title() + "!")
#使用break终止循环
current_number = 0
while current_number < 10:
    current_number +=1
    if current_number % 2 == 0:
        continue

    print(current_number)
#在循环中用continue    
1
3
5
7
9

如果程序陷入无限循环可以用ctrl c

用while处理列表和字典

#在列表中移动元素
#首先,创建一个待验证用户列表
#和一个用于储存已验证用户的空列表。
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []
#验证每个用户,直到没有未验证用户为止
#将每个经过验证的列表都移到已验证的用户列表中
while unconfirmed_users:
    current_user =unconfirmed_users.pop()

    print("Verifying user:" + current_user.title())
    confirmed_users.append(current_user)
#显示所有已经验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())
    

Verifying user:Candace
Verifying user:Brian
Verifying user:Alice

The following users have been confirmed:
Candace
Brian
Alice
#删除包含特定值的所有列表元素
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')
print(pets)

['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
#使用用户输入来填充字典
responses = {}
# 设置一个标志,指出调查是否继续
polling_active = True

while polling_active:
    #提示输入被调查者的名字和回答
    name = input("\nWhat is your name? ")
    response = input("Which mountain would you like to climb someday? ")

    #将答卷存储在字典中
    responses[name] = response
    #看看是否还有人要参与调查
    repeat = input("Would you like to let another person respond? (yes/no) ")
    if repeat == 'no':
        polling_active = False
    #调查结束,显示结果
print("\n--- poll Results ---")
for name, response in responses.items():
    print(name +" would like to climb " + response + ".")
        

What is your name? 1
Which mountain would you like to climb someday? 2
Would you like to let another person respond? (yes/no) yes

What is your name? 3
Which mountain would you like to climb someday? 4
Would you like to let another person respond? (yes/no) no

--- poll Results ---
1 would like to climb 2.
3 would like to climb 4.

函数

定义函数

def greet_user(username):
    print("Hello, " + username.title() + "!")

greet_user('jesse')

Hello, Jesse!

username是形参
jesse是实参

位置实参

调用函数时,必须将函数调用中的每个实参都关联到函数定义中的一个形参,最简单的关联方式是基于实参的顺序。这种关联方式被成为位置实参。

def describe_pet(animal_type,pet_name):
    print("\nI have a " + animal_type +".")
    print("My "+ animal_type + "'s name is " +pet_name.title() +".")

describe_pet('hamster','harry')
describe_pet('dog','willie')
describe_pet(animal_type='hamster',pet_name='harry')#关键字实参
describe_pet(pet_name='harry',animal_type='hamster')

I have a hamster.
My hamster's name is Harry.

I have a dog.
My dog's name is Willie.

I have a hamster.
My hamster's name is Harry.

I have a hamster.
My hamster's name is Harry.

混用

def describe_pet(pet_name,animal_type='dog'):
    print("\nI have a " +animal_type +".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('willie')
describe_pet(pet_name='willie')
describe_pet(pet_name='harry',animal_type='hamster')
describe_pet(animal_type='hamster',pet_name='harry')
describe_pet(pet_name='harry',animal_type='hamster')

I have a dog.
My dog's name is Willie.

I have a dog.
My dog's name is Willie.

I have a hamster.
My hamster's name is Harry.

I have a hamster.
My hamster's name is Harry.

I have a hamster.
My hamster's name is Harry.

返回值

def get_formatted_name(first_name,last_name):
    full_name = first_name + ' ' +last_name
    return full_name.title()

musician = get_formatted_name('jimi','hendrix')
print(musician)

Jimi Hendrix

让实参变成可选的

def get_formatted_name(first_name,last_name,middle_name=' '):
    if middle_name:
        full_name = first_name + ' ' + middle_name + ' ' + last_name
    else:
        full_name = first_name + ' ' + last_name
    return full_name.title()
musician = get_formatted_name('jimi','hendrix')
print(musician)
musician = get_formatted_name('john','hooker','lee')
print(musician)
      

Jimi   Hendrix
John Lee Hooker

返回字典

def build_person(first_name,last_name,age=''):
    person = {'first':first_name,'last':last_name}
    if age:
        person['age'] = age
    return person

musician = build_person('jimi','hendrix',age=27)
print(musician)

{'first': 'jimi', 'last': 'hendrix', 'age': 27}

结合使用函数和while循环

def get_formatted_name(first_name,last_name):
    full_name = first_name + ' ' +last_name
    return full_name.title()
while True:
    print("\nPlease tell me your name:")
    print("enter 'q' at any time to quit)")
    
    f_name = input("First name: ")
    if f_name == 'q':
        break
    
    l_name = input("Last name:")
    if l_name == 'q':
        break

    formatted_name = get_formatted_name(f_name,l_name)
    print("\nHello, " + formatted_name + "!")
    

Please tell me your name:
enter 'q' at any time to quit)
First name: 1
Last name:2

Hello, 1 2!

Please tell me your name:
enter 'q' at any time to quit)
First name: q

传递列表

def greet_users(names):
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)
usernames = ['hannah','ty','margot']
greet_users(usernames)


Hello, Hannah!
Hello, Ty!
Hello, Margot!

在函数中修改列表

unprinted_desighs = ['ipone case','robot pendant','dodecahedron']
completed_models = []

while unprinted_desighs:
    current_desigh = unprinted_desighs.pop()

    print("Printing modle: "+ current_desigh)
    completed_models.append(current_desigh)

print("\nThe folling models have been printed:")
for completed_model in completed_models:
    print(completed_model)

Printing modle: dodecahedron
Printing modle: robot pendant
Printing modle: ipone case

The folling models have been printed:
dodecahedron
robot pendant
ipone case

修改版

def print_models(unprinted_designs,completed_models):
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print("Printing model:" + current_design)
        completed_models.append(current_design)

def show_completed_models(completed_models):
    print("\nThe folling models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['ipone case','robot pendant','dodecahedron']
completed_models = []

print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)

禁止函数修改列表
将列表的副本传递给函数
function_name(list_name[:])
切片表示法[:]创建列表的副本。在上一个程序中如果不想清空未打印的设计列表,可以如下调用print_models():
print_models(uprinted_designs[:],completed_models)
这样函数print_models()仍然能完成其任务。但是是unprinted_designs的副本

结合使用任意数量或的实参和结合位置实参

def make_pizza(size,*toppings):
    print("\nMaking a " +str(size) +"-inch pizza with the folling toppings:")
    for topping in toppings:
        print("- " +topping)

make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')

Making a 16-inch pizza with the folling toppings:
- pepperoni

Making a 12-inch pizza with the folling toppings:
- mushrooms
- green peppers
- extra cheese

使用任意数量的关键字实参

def build_profile(first,last,**user_info):
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key,value in user_info.items():
        profile[key] = value
    return profile
user_profile = build_profile('albert','einstein',
                             location = 'princeton',
                             field = 'physics')
print(user_profile)

{'first_name': 'albertd', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

将函数存储在模块中

先创建一个模块,包含要导入到程序的代码。然后在文件目录中再创建另一个文件导入模块
在第一行输入inport +模块名可以导入整个模块
可以使用模块名.函数名()来使用其中任意一个函数
还可以倒数特定的函数

from 模块名 import 函数名
通过逗号分隔函数名,可根据需要从模块中导入任意数量的函数
使用as给函数指定别名
from + 模块名 import 函数名 as xx
使用as给模块指定别名
import 模块名 as xx
导入模块所有函数
from 模块名 import *

函数编写指南

编写函数时,要牢记几个细节。应给函数指定描述性名称,且只在其中使用小写字母和下划线。描述性名称可以帮你和别人明白代码想做什么。
每个函数应包含简要地阐述其功能的注释,该注释应紧跟在函数定义后面,并采用文档字符串格式。文档良好的函数让其他程序员只需阅读文档字符串中的描述就能使用他:他们完全可以相信代码如描述的那样运行,只要知道函数的名称,需要的实参以及返回值的类型就能在自己的程序中使用它。
给形参指定默认值时,等号两边不要有空格,对于函数调用中的关键字实参也应遵循这种约定。

class 类名(继承列表):
def init(self, [形参列表]):
语句块
方法__init__()
初始化方法名必须是’init’ 不可改变
初始化方法会在构造函数创建实例后自动调用,且将实例自身通过第一个参数 self 传入 init 方法
构造函数的实参将通过 init 方法的参数列表传入到 init 方法中
初始化方法内如果需要 return 语句,则只能返回 None
根据类创建实例

class Dog():
    def __init__(self,name,age ):#初始化属性name,age
        self.name = name
        self.age = age
    def sit(self):
        print(self.name.title() + " is now sitting.")
    def roll_over(self):
        print(self.name.title() + " rolled over!")
    

my_dog = Dog('willie',6)
your_dog = Dog('lucy',3)
print("我的狗的名字是"+ my_dog.name.title() + ".")
print("我的狗"+ str(my_dog.age) + "岁.")              
my_dog.sit()
my_dog.roll_over()
print("你的狗的名字是"+ my_dog.name.title() + ".")
print("你的狗"+ str(my_dog.age) + "岁.")                 
your_dog.sit()

我的狗的名字是Willie.
我的狗6.
Willie is now sitting.
Willie rolled over!
你的狗的名字是Willie.
你的狗6.
Lucy is now sitting.

使用类和实例

class Car():
    def __init__(self,make,model,year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0
        
    def get_descriptive_name(self):
        long_name = str(self.year) +' ' + self.make + ' ' + self.model
        return long_name.title()

    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")

    def update_odometer(self,mileage):#通过方法进行修改
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self,miles):#递增
        self.odometer_reading +=miles
        
         
my_new_car = Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car.odometer_reading 
my_new_car.read_odometer()
my_new_car.update_odometer(25)
my_new_car.read_odometer()
my_new_car.update_odometer(21)
my_new_car.read_odometer()
my_new_car.increment_odometer(100)
my_new_car.read_odometer()
#将Battey提出来作为它的一个属性
class Battery():
    def __init__(self,battery_size=70):
        self.battery_size = battery_size

    def describe_battery(self):
        print("This car has a " + str(self.battery_size) + "-kwh battery.")

    def get_range(self):
        if self.battery_size ==70:
            range = 240
        elif self.battery_size == 85:
            range = 270
        message = "This car can go approximately " + str(range)
        message += " miles on a full charge."
        print(message)
  
#继承
#子类的方法__init__()
class ElectricCar(Car):

    def __init__(self,make,model,year):      #初始化父类的属性
        super().__init__(make,model,year)
        #self.battery_size = 70
        self.battery = Battery()

    '''def describe_battery(self):
        print("This car has a " + str(self.battery_size) + "-kwh battery.")'''
    def fill_gas_tank(self):#重写父类方法
        print("This car doesn't need a gas tank!")

my_tesla = ElectricCar('tesla' , 'model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()


2016 Audi A4
This car has 0 miles on it.
This car has 0 miles on it.
This car has 25 miles on it.
You can't roll back an odometer!
This car has 25 miles on it.
This car has 125 miles on it.
2016 Tesla Model S
This car has a 70-kwh battery.
This car can go approximately 240 miles on a full charge.

导入类

导入一个类

from car inport Car#此处的car是上文class Car():

my_new_car = Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())

my_new_car.odometer_reading = 23
my_new_car.read_odometer()

2016 Audi A4
This car has 23 miles on it.

储存多个类

from car import ElectricCar

my_resla = ElectricCar('tesla','model s',2016)

print(my_tesla.get_descriptive_name())
my_tesla.bettery.describe_battery()
my_tesla.battery.get_range()
#输出同上

从一个模块中导入多个类

from car import Car,ElectricCar

my_beetle = Car('volkswagen','beetle',2016)
print(my_beetle.get_descriptive_name())

my_tesla = ElectricCar('tesla','roadster',2016)
print(my_tesla.get_descriptive_name())

2016 Volkswagen Beetle
2016 Tesla Roadster

导入整个模块
import car
导入模块所有类
from module_name import*

文件和异常

先创建一个文件
pi_digits.txt
3.1415926535
8979323846
2643383279

with open('pi_digits.txt')as file_object:
    contents = file_object.read()#read方法 特点:读取整个文件,将文件内容放到一个字符串变量中。
    print(contents)#改为print(contents.rstrip())
    
3.1415926535
  8979323846
  2643383279

>>> #多出空行是read()到达文件结尾返回一个空字符串。删除空行可以在print语句中使用rstrip()

将地址存在一个变量中会有利于调用

filename = 'pi_digits.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line)
#逐行提取,加入rstrip和上文一样
3.1415926535

  8979323846

  2643383279

>>> 

或者这样

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.rstrip())

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''

for line in lines:
    pi_string +=line.rstrip()#删除换行符
   #pi_string +=line.strip()#删除所有空格
print(pi_string)
print(len(pi_string))


3.1415926535  8979323846  2643383279
36
>>> 

3.141592653589793238462643383279
32

如果想使用这些数字,需要转换类型。

filename = 'pi.txt'#创建一个圆周率txt

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''
for line in lines:
    pi_string +=line.strip()

print(pi_string[:52] + "...")
print(len(pi_string))
      

filename = 'pi.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''
for line in lines:
    pi_string +=line.strip()

birthday = input("Enter your birthday,in the form mmddyy: ")
if birthday in pi_string:
    print("Your birthday appears in the first millon digits of pi!")
else:
    print("Your birthdat does not appear in the first million digits of pi.")
#检测你的生日是否在圆周率值中    

写入文件

保存数据最简单的方式之一就是将其写入文件中,通过将输出写入文件,即便关闭包含程序输出的终端窗口,这些输出也依然存在。

filename = 'programming.txt'

with open(filename,'w')as file_object:#如果文件不存在open()将自动创建他
    #读取模式('r')写入模式('w')附加模式('a')读取和写入模式('r+')
    #写入模式打开文件会清除文件内所有内容
    file_object.write("I love programming.\n")
    file_object.write("I love creating new games.\n")
    #附加模式不会删除原有内容。

异常

使用try-except代码块

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")
    
#后面的代码将继续运行。
You can't divide by zero!

使用异常避免崩溃

print("Give me two numbers,and I'll divide them.")
print("Enter 'q' to quit.")

while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("Second number:")    
    if second_number == 'q':
        break
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)
    

Give me two numbers,and I'll divide them.
Enter 'q' to quit.

First number: 5
Second number:0
You can't divide by 0!

First number: 5
Second number:2
2.5

First number: q

方法split()将字符串拆分成一个个单词

def count_words(filename):
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        #pass   加入pass可以跳过一个错误
        msg = "Sorry, the file " + filename + " does not exist."
        print(msg)
    else:
        words = contents.split()
        num_words = len(words)
        print("The file " +filename + " has about " + str(num_words) +" words.")

filenames = ['alice.txt','siddhartha.txt','moby_dick.txt',"litter_women.txt"]
for filename in filenames:
    count_words(filename)
    
#统计多个文件的单词数

存储数据

使用json.dump()和json.load()
函数json.dump()接受两个实参:要储存的数据以及可用于存储数据的文件对象。

import json

numbers = [2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename,'w')as f_obj:
    json.dump(numbers,f_obj)
    

读取上述文件

import json

filename = 'numbers.json'
with open(filename) as f_obj:
    numbers = json.load(f_obj)

print(numbers)

保存和读取用户生成的数据

import json

username = input("What's your name?")

filename = 'username.json'
with open(filename,'w')as f_obj:
    json.dump(username,f_obj)
    print("We'll remember you when you come back, " +username + "!")

import json

filename = 'username.json'

with open(filename) as f_obj:
    username = json.load(f_obj)
    print("Welcome back, " +username +"!")
    

合并

import json
filename = 'username.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("What is your name?")
    with open(filename,'w')as f_obj:
        json.dump(username,f_obj)
        print("We'll rember you when you come back, " + username + "!")
else:
    print("Welcome back, " +username +"!")

重构

import json

def get_stored_username():
    filename = 'username.json'
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    username = input("What is your name?")
    filename = 'username.json'
    with open(filename,'w')as f_obj:
        json.dump(username,f_obj)
    return username

def greet_user():    
    username =  get_stored_username()
    if username:
        print("Welcome back, " +username +"!" )
    else:
        username = get_new_username()
        
        print("We'll rember you when you come back, " + username + "!")
   

greet_user()

What is your name?OY
We'll rember you when you come back, OY!

测试代码

from name_function import get_formatted_name
print("Enter 'q' at any time to quit.")
while True:
    first = input("\nPlease give me a first name:")
    if first == 'q':
        break
    last = input("Please give me a last name:")
    if last == 'q':
        break

    formatted_name = get_formatted_name(first,last)
    print("\nNeatly formatted name:" + formatted_name + '.')
    

Enter 'q' at any time to quit.

Please give me a first name:1
Please give me a last name:2

Neatly formatted name:1 2.

Please give me a first name:3
Please give me a last name:4

Neatly formatted name:3 4.

Please give me a first name:q

def get_formatted_name(first,last):
    full_name = first + ' ' + last
    return full_name.title()

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):

    def test_first_last_name(self):
        formatted_name = get_formatted_name('janis','joplin')
        self.assertEqual(formatted_name,'Janis Joplin')

unittest.main()        
 
.
----------------------------------------------------------------------
Ran 1 test in 0.028s

OK
def get_formatted_name(first,last,middle = ''):
    if middle:
        full_name = first +' ' + middle + ' ' + last
    else:
        full_name = first + ' ' + last
    return full_name.title()

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):

    def test_first_last_name(self):
        formatted_name = get_formatted_name('janis','joplin')
        self.assertEqual(formatted_name,'Janis   Joplin')

    def test_first_last_middle_name(self):
        formatted_name = get_formatted_name(
            'wolfgang','mozart','amadeus')
        self.assertEqual(formatted_name,'Wolfgang Amadeus Mozart')



unittest.main()        


..
----------------------------------------------------------------------
Ran 2 tests in 0.053s

OK

测试类

各种断言方法
assertEqual(a,b) 核实 a == b
assertNotEqual(a,b) 核实 a!=b
assertTrue(x) 核实x为True
assertFalse(x) 核实x为False
assertIn(item,list) 核实item在list中
assertNotIn(item,list) 核实item不在list中

class AnonymousSurvey():

    def __init__(self,question):
        self.question = question
        self.responses = []

    def show_question(self):
        print(self.question)

    def store_response(self,new_response):
        self.responses.append(new_response)

    def show_results(self):
        print("Survey results:")
        for response in self.responses:
            print('- '+response)
            

from survey import AnonymousSurvey

question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)

my_survey.show_question()
print("Enter 'q' at any time to quie.\n")
while True:
    response = input("Language: ")
    if response == 'q':
        break
    my_survey.store_response(response)

print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()

What language did you first learn to speak?
Enter 'q' at any time to quie.

Language: English
Language: Spanish
Language: English
Language: Mandarin
Language: q

Thank you to everyone who participated in the survey!
Survey results:
- English
- Spanish
- English
- Mandarin
import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):

    def test_store_single_response(self):

        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        my_survey.store_response('English')

        self.assertIn('English',my_survey.responses)

unittest.main()

.
----------------------------------------------------------------------
Ran 1 test in 0.054s

OK

方法setUp()

import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):

    def setUp(self):

        question = "What language did tou first learn to speak?"
        self.my_survey = AnonymousSurvey(question)
        self.responses = ['English','Spanish','Mandarin']

    def test_store_single_response(self):

        self.my_survey.store_response(self.responses[0])
        self.assertIn(self.responses[0],self.my_survey.responses)

    def test_store_three_responses(self):

        for response in self.responses:
            self.my_survey.store_response(response)
        for response in self.responses:
            self.assertIn(response,self.my_survey.responses)

unittest.main()

完结撒花

你可能感兴趣的:(笔记,python,面向对象编程)