0222

  • 不需要分号,不需要规定类型,直接赋值,且中途可以随时修改变量的值
message="Hello Python world!"
print(message)
message="Hello Python Crash Course world!"
print(message)

Hello Python world!
Hello Python Crash Course world!

  • 只要有引号包含就是字符串,单双引号都可以
message1="This new language’s name is 'Python'!"
message2='I told your friend,"My thought is not enough."'
  • 修改字符串的大小写
  1. title()
message="My name is Zichel, I'm learning Python!"
print(message.title())

My Name Is Zichel, I’M Learning Python!

可以用于识别如名字、地名等需要首字母大写的词语

  1. upper()
message="My name is Zichel, I'm learning Python!"
print(message.upper())

MY NAME IS ZICHEL, I’M LEARNING PYTHON!

  1. lower()
message="My name is Zichel, I'm learning Python!"
print(message.lower())

my name is zichel, i’m learning python!

在存储数据时比较有用,无法依靠用户提供正确大小写,就统一先小写

  • 在字符串中使用变量f函数(3.5以前叫做format)
first_name="ada"
last_name="lovelace"
#注意其中的空格也会被回显出来
full_name=f"{first_name} {last_name}"
print("Hello,{full_name}")

Hello,{full_name}

first_name="ada"
last_name="lovelace"
#注意其中的空格也会被回显出来
full_name=f"{first_name} {last_name}"
print(f"Hello,{full_name.title()}")

Hello,Ada Lovelace

first_name="ada"
last_name="lovelace"
#注意其中的空格也会被回显出来
full_name=f"{first_name} {last_name}"
message=f"Hello,{full_name.title()}"
print(message)

Hello,Ada Lovelace

  • 制表符和换行符
print("Python")
# \t制表符,就是前面空几个
print("\tPython")
# \n换行符
print("Language:\nPython\nC\nJavaScript")
# 同时换行制表
print("Language:\n\tPython\n\tC\n\tJavaScript")

Python
Python
Language:
Python
C
JavaScript
Language:
Python
C
JavaScript

  • 同时给多个变量赋值
x,y,z=0,0,0
  • 常量全大写
MAX_CONNECTION=5000
  • 列表查询增改
  1. 在末尾添加元素append(),帮助动态创建列表
  2. 任意处插入insert()
  3. 不知道列表长度时最后一个元素的索引可以使用-1
letters=['a','b','c','d']
print(letters)
print(letters[0],letters[1],letters[2],letters[-1])
print(letters[0],letters[1],letters[2],letters[3])
letters[0]='z'
print(letters[0])
letters.append('e')
print(letters)
letters.insert(1,'g')
print(letters)

[‘a’, ‘b’, ‘c’, ‘d’]
a b c d
a b c d
z
[‘z’, ‘b’, ‘c’, ‘d’, ‘e’]
[‘z’, ‘g’, ‘b’, ‘c’, ‘d’, ‘e’]

  • 列表删除
  1. del语句(已知元素在列表中的位置
  2. pop(),将元素从列表中删除,并接着使用这个值(已知的任意位置
  3. remove()根据值删除,也可以接着使用
letters=['a','b','c','d','e','f']
print(letters)
del letters[0]
print(letters)
popped_letter=letters.pop()
print(letters)
print(popped_letter)
second_letter=letters.pop(1)
print(letters)
print(second_letter)
dont_like='d'
letters.remove(dont_like)
print(letters)
print(f"\n The letter that i don't like is {dont_like}")

[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
[‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
[‘b’, ‘c’, ‘d’, ‘e’]
f
[‘b’, ‘d’, ‘e’]
c
[‘b’, ‘e’]

The letter that i don’t like is d

  • 组织列表
  1. sort()属于永久排序
names=['Adam','Cindy','David','Bob']
names.sort()
print(names)
names.sort(reverse=True)
print(names)

[‘Adam’, ‘Bob’, ‘Cindy’, ‘David’]
[‘David’, ‘Cindy’, ‘Bob’, ‘Adam’]

  1. sorted()临时排序
names=['Adam','Cindy','David','Bob']
print("Here is the original list")
print(names)
print("Here is the sorted list")
print(sorted(names))
print("Here is the original list")
print(names)

Here is the original list
[‘Adam’, ‘Cindy’, ‘David’, ‘Bob’]
Here is the sorted list
[‘Adam’, ‘Bob’, ‘Cindy’, ‘David’]
Here is the original list
[‘Adam’, ‘Cindy’, ‘David’, ‘Bob’]

  1. 逆序打印
names=['1Adam','2Cindy','3David','4Bob']
print(names)
names.reverse()
print(names)

[‘1Adam’, ‘2Cindy’, ‘3David’, ‘4Bob’]
[‘4Bob’, ‘3David’, ‘2Cindy’, ‘1Adam’]

reverse虽然永久改变,但是要变回来再reverse一边就好了

  1. 求长度

lens(列表名)

0223

  • 遍历整个列表

列表一般定义是复数形式,使用for循环的时候直接从单词中截取单数作为变量,即其中的每一项

magicians=['alice','david','carolina']
for magician in magicians:print(f"{magician.title()},that was a great trick!")

Alice,that was a great trick!
David,that was a great trick!
Carolina,that was a great trick!

不用打括号,直接缩进即可

magicians=['alice','david','carolina']
for magician in magicians:print(f"{magician.title()},that was a great trick!")print(f"I can't wait to see {magician.title()} next time.\n")
print("Thank you all")

冒号和缩进注意一下

  • range()生成一系列数
#只生成1-1,从第一个数开始,第二个数的前一个停止
for value in range(1,5):print(value)#也可以只指定一个参数,将从0到这个参数的前一个数
for value in range(6):print(value)

1
2
3
4
0
1
2
3
4
5

  • 创建数字列表使用list()直接转换range即可
numbers=list(range(1,6))
print(numbers)
#还可以指定步长
#从2开始不断+2,直到达到或者超过11
even_numbers=list(range(2,11,2))
print(even_numbers)

[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]

  • 使用range可以创建几乎任意数字集
squares=[]
#使用临时变量版本
for value in range(1,11):square=value**2squares.append(square)
print(squares)#不使用临时变量版本
for value in range(1,11):squares.append(value**2)
print(squares)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

>>> digits=[1,2,3,4,5,6,7,8,9,0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45
  • 列表解析(简化步骤)
  1. 先指定描述性列表名
  2. 然后指定方括号定义表达式,用于生成要存储到列表中的值
  3. 编写for循环,用于给表达式提供值
  4. 此处的for循环没有冒号
squares=[value**2 for value in range(1,11)]
print(squares)
  • 列表生成任意子集
players=['adam','bob','cindy','dory','emily']
print(players[0:2])
#省略第一个,自动从泪飙开头开始
print(players[:2])
print(players[1:3])
#省略第二个,自动停到结尾
print(players[2:])
print(players[-3:])

[‘adam’, ‘bob’]
[‘adam’, ‘bob’]
[‘bob’, ‘cindy’]
[‘cindy’, ‘dory’, ‘emily’]
[‘cindy’, ‘dory’, ‘emily’]

  • 遍历切片
players=['adam','bob','cindy','dory','emily']
print("Here are the first three players in our team:")
for player in players[:3]:print(player)

Here are the first three players in our team:
adam
bob
cindy

  • 复制列表
my_foods=['pizza','falafel','carrot cake']
#全复制
friend_foods=my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
my_foods.append('cannoli')
friend_foods.append('spagetti')
print("Now my favorite foods are:")
print(my_foods)
print("\nNow my friend's favorite foods are:")
print(friend_foods)

My favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’]

My friend’s favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’]
Now my favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’]

Now my friend’s favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘spagetti’]

  • 元组(不可变的列表)
dimensions=(200,50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)#要修改就是重新赋值
dimensions=(400,50)
print("\nModifiled dimensions:")
for dimension in dimensions:
print(dimension)

Original dimensions:
200
50

Modifiled dimensions:
400
50

  • if语句

没有括号有冒号

在if语句作为条件表达式时,Python将在列表至少包含一个元素时返回True,为空时返回false

avaliable_toppings=['a','b','c','d']
requested_toppings=['a','c','e']
for requested_topping in requested_toppings:if requested_topping in avaliable_toppings:print(f"Adding {requested_topping}.")else:print(f"Sorry we don't have {requested_topping}")print("Your pizza is ready!")

Adding a.
Adding c.
Sorry we don’t have e
Your pizza is ready!

0224

  • 键值对添加,修改,删除
alient_0={'color':'green'}
print(alient_0)
alient_0['points']=5
alient_0['x_position']=0
alient_0['y_position']=10
print(alient_0)
alient_0['color']='red'
print(f"The alient looks like {alient_0['color']}")
alient_0['speed']='slow'
#向右移动外星人
#根据当前速度决定移动距离
if alient_0['speed']=='slow':x_increment=1;
elif alient_0['speed']=='medium':x_increment=2;
else:x_increment=3;#新位置=原位置+位移
alient_0['x_position']=alient_0['x_position']+x_increment
print(f"New x_position:{alient_0['x_position']}")del alient_0['color']
print(alient_0)

{‘color’: ‘green’}
{‘color’: ‘green’, ‘points’: 5, ‘x_position’: 0, ‘y_position’: 10}
The alient looks like red
New x_position:1
{‘points’: 5, ‘x_position’: 1, ‘y_position’: 10, ‘speed’: ‘slow’}

一开始也可以直接设置空字典

删除的键值对会永远消失

  • 由类似对象组成的字典
favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',
}
language=favorite_languages['sarah'].title()
print(f"Sarah's favortie language is {language}")

Sarah’s favortie language is C

  • 用get()访问值

直接取值,若值不存在会造成编译错误

但是如果使用get()函数可以在键值不存在时返回默认语句,从而避免错误

del alient_0['color']
point_value = alient_0.get('color','No color value assigned!')
print(point_value)

{‘color’: ‘green’}
{‘color’: ‘green’, ‘points’: 5, ‘x_position’: 0, ‘y_position’: 10}
The alient looks like red
New x_position:1
No color value assigned!

  • 字典遍历
favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',
}for name in favorite_languages.keys():print(name.title())
#因为遍历字典时会默认遍历所有的键,所以将.keys()省略的结果是一样的
for name in favorite_languages:print(name.title())

Jen
Sarah
Edward
Phil
Jen
Sarah
Edward
Phil

favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',
}
friends=['phil','sarah']
for name in favorite_languages.keys():print(f"Hi {name.title()}.")if name in friends:language = favorite_languages[name].title()print(f"\t{name.title()}, I see you love {language}!")

Hi Jen.
Hi Sarah.
Sarah, I see you love C!
Hi Edward.
Hi Phil.
Phil, I see you love Python!

  • 按照特定的顺序遍历
favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',
}
for name in sorted(favorite_languages.keys()):

Edward, thank you for taking the poll
Jen, thank you for taking the poll
Phil, thank you for taking the poll
Sarah, thank you for taking the poll

  • 遍历所有值

set集合保证每个元素都是独一无二的

favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',
}
supposed_members=['jen','edward','jourlin']
for name in supposed_members:if name in favorite_languages.keys():print(f"Hi {name.title()}, thanking you for taking the poll")else:print(f"Hi {name.title()}, Do you want to have a quit?")

Hi Jen, thanking you for taking the poll
Hi Edward, thanking you for taking the poll
Hi Jourlin, Do you want to have a quit?

  • 嵌套——字典列表
alient_0={'color':'green','points':5}
alient_1={'color':'yellow','points':10}
alient_2={'color':'red','points':15}alients=[alient_0,alient_1,alient_2]
for alien in alients:print(alien)

{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘yellow’, ‘points’: 10}
{‘color’: ‘red’, ‘points’: 15}

使用range自动生成

#创建用于存储外星人的空列表
aliens=[]#创建30个绿色的外星人
for alien_number in range(30):new_alien={'color':'green','points':5,'speed':'slow'}aliens.append(new_alien)#切片显示前5个外星人
for alien in aliens[:5]:print(alien)#显示创建了多少个外星人
print(f"The total number of aliens is {len(aliens)}")#修改前3个外星人的属性
for alien in aliens[:3]:if alien['color']=='green':alien['color']='yellow'alien['points']=10alien['speed']='medium'#切片显示前5个外星人
for alien in aliens[:5]:print(alien)

{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
The total number of aliens is 30
{‘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’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}

  • 字典中存储列表
#存储点的披萨的信息
pizza={'crust':'thick','toppings':['mushrooms','extra cheese'],
}#概述所点的披萨
print(f"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(f"\n{name.title()}'s favorite languages are:")for language in languages:print(f"\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':'eninsten','location':'princeton',},'mcurie':{'first':'marie','last':'curie','location':'paris',},
}for username, user_info in users.items():print(f"\nUsername: {username}")full_name=f"{user_info['first']} {user_info['last']}"location=user_info['location']print(f"\tFull name:{full_name.title()}")print(f"\tLocation:{location.title()}")

Username: aeinstein
Full name:Albert Eninsten
Location:Princeton

Username: mcurie
Full name:Marie Curie
Location:Paris

  • 在列表间移动元素
#首先创建待验证用户列表
#和一个用于存储已验证用户的空列表
unconfirmed_users=['alice','brain','candace']
confirmed_users=[]#验证每个用户,直到没有未验证用户为止
#将每个经过验证的用户都移到已验证用户列表中
while unconfirmed_users:current_user=unconfirmed_users.pop()print(f"Verifing 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())

Verifing user:Candace
Verifing user:Brain
Verifing user:Alice

The following users have been confirmed:
Candace
Brain
Alice

  • 使用用户输入填充字典
responses = {}#设置一个标志,指出调查是否继续
polling_active = Truewhile 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 persn respond? (yes/no)")if repeat=='no':polling_active=False#调查结束,显示结果
print("\n--- Poll Results ---")
for name, response in responses.item():print(f"{name} would like to climb {response}")

0225

  • 函数
  1. 位置实参
def describe_pet(animal_type, pet_name):"""显示宠物的信息"""print(f"\nI have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name.title()}")describe_pet('hamster','harry')
#多次调用函数
describe_pet('dog','fluffy')

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

I have a dog.
My dog’s name is Fluffy

位置实参的顺序很重要

  1. 关键字实参
def describe_pet(animal_type, pet_name):"""显示宠物的信息"""print(f"\nI have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name.title()}")#关键字实参的顺序就没关系了
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 hamster.
My hamster’s name is Harry

  • 函数默认值

有默认值的形参应该放到后面,否则传入的实参还是会以位置参数的形式传给了形参

def describe_pet( pet_name,animal_type='dog'):"""显示宠物的信息"""print(f"\nI have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name.title()}")describe_pet('harry')

I have a dog.
My dog’s name is Harry

如果一个函数的参数中含有默认参数,则这个默认参数后的所有参数都必须是默认参数,否则会报错:SyntaxError: non-default argument follows default argument de…

  • 返回简单值
def get_formatted_name(first_name, last_name, middle_name=''):"""返回整洁的姓名""""""不是每个人都有中名,故设置空的默认值"""if middle_name:full_name=f"{first_name} {middle_name} {last_name}"else:full_name=f"{first_name} {last_name}"return full_name.title()musician = get_formatted_name('jimi','hendrix','lee')
print(musician)
musician = get_formatted_name('jimi','hendrix')
print(musician)

Jimi Lee Hendrix
Jimi Hendrix

  • 返回字典
def built_person(first_name, last_name,age=None):"""返回一个字典,其中包含有关一个人的信息"""person={'first':first_name, 'last':last_name}if age:person['age']=agereturn person musician= built_person('jimi', 'hendrix',age=27)
print(musician)

{‘first’: ‘jimi’, ‘last’: ‘hendrix’, ‘age’: 27}

  • 加上while循环
def get_formatted_name(first_name, last_name):"""返回整洁的姓名""""""不是每个人都有中名,故设置空的默认值"""full_name=f"{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':breakl_name=input("Last name: ")if l_name=='q':breakformatted_name=get_formatted_name(f_name,l_name)print(f"\nHello, {formatted_name}")
def make_album(singer, name, number=None):album={'singer_name':singer,'album_name':name}if number:album['number']=numberreturn album while True:print("\nPlease input the singer's name, album's name: ")print("enter 'q' at any time to quit.")s_name=input("Singer's name: ")if s_name=='q':breaka_name=input("Album's name: ")if a_name=='q':breakalbum_information=make_album(s_name,a_name)print(f"\n {album_information}")

Please input the singer’s name, album’s name:
enter ‘q’ at any time to quit.
Singer’s name: Ariana Grande
Album’s name: Dangerous Woman

{‘singer_name’: ‘Ariana Grande’, ‘album_name’: ‘Dangerous Woman’}

Please input the singer’s name, album’s name:
enter ‘q’ at any time to quit.
Singer’s name: Maroon 5
Album’s name: Overexposure

{‘singer_name’: ‘Maroon 5’, ‘album_name’: ‘Overexposure’}

Please input the singer’s name, album’s name:
enter ‘q’ at any time to quit.
Singer’s name: q

  • 传递列表
def greet_users(names):"""向列表中的每位用户发出简单的问候"""for name in names:msg=f"Hello, {name.title()}!"print(msg)usernames=['hannah','ty','margot']
greet_users(usernames)

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

  • 函数中修改列表

普通方法

#首先创建一个列表,其中包含一些要打印的设计
unprinted_designs=['phone case','robot pendant','dodecahedron']
completed_models=[]#模拟打印每个设计,知道没有未打印的设计为止
#打印每个设计后,都将其移到列表completed_models中
while unprinted_designs:current_design=unprinted_designs.pop()print(f"Printing model:{current_design}")completed_models.append(current_design)#显示打印好的所有模型
print("\nThe following models have been printed:")
for completed_model in completed_models:print(completed_model)

函数法

def print_models(unprinted_designs, completed_models):#模拟打印每个设计,知道没有未打印的设计为止#打印每个设计后,都将其移到列表completed_models中while unprinted_designs:current_design=unprinted_designs.pop()print(f"Printing model:{current_design}")completed_models.append(current_design)def show_completed_models(completed_models):"""显示打印好的所有模型"""print("\nThe following models have been printed:")for completed_model in completed_models:print(completed_model)#创建一个列表,其中包含一些要打印的设计
unprinted_designs=['phone case','robot pendant','dodecahedron']
completed_models=[]print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)

Printing model:dodecahedron
Printing model:robot pendant
Printing model:phone case

The following models have been printed:
dodecahedron
robot pendant
phone case

写成函数更容易扩展和维护

  • 课后小题,禁止函数修改列表
text_info=['hello','sorry','fresh','man']
completed=[]
def show_messages(texts):for text in texts:print(text)show_messages(text_info)
print(text_info)def send_messages(texts):while texts:current=texts.pop()print(current)completed.append(current)send_messages(text_info[:])
print(text_info)
print(completed)

hello
sorry
fresh
man
[‘hello’, ‘sorry’, ‘fresh’, ‘man’]
man
fresh
sorry
hello
[‘hello’, ‘sorry’, ‘fresh’, ‘man’]
[‘man’, ‘fresh’, ‘sorry’, ‘hello’]

  • 结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):"""概述要制作的披萨"""print(f"\nMaking a {size}-inch pizza with the following toppings:")for topping in toppings:print(f"-{topping}")make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')

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

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

经常看到*arg收集任意数量的位置实参

  • 使用任意数量的关键字实参
def build_profile(first, last, **user_info):"""创建一个字典,其中包含我们知道的关于用户的一切"""user_info['first_name']=firstuser_info['last_name']=lastreturn user_infouser_profile=build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)

{‘location’: ‘princeton’, ‘field’: ‘physics’, ‘first_name’: ‘albert’, ‘last_name’: ‘einstein’}

经常看到**kwargs收集任意数量的关键字实参

0227

class Dog:"""一次模拟小狗的简单尝试"""def __init__(self, name, age):"""初始化属性"""self.name = nameself.age = agedef sit(self):"""模拟小狗收到命令时蹲下"""print(f"{self.name} is now sitting.")def roll_over(self):"""模拟小狗收到命令时打滚"""print(f"{self.name} rolled over!")
  • 方法_init_()
  1. 类中的函数被称为方法,根据类创建新实例时,会自动运行该方法。开头末尾都有双下划线!!!!!!!,是避免与其他函数名产生冲突
  2. self必须存在且位于其他形参的前面,是一个指向实例本身的引用,让实例能够访问类中的属性和方法,每当创建一个新的实例时,只需要给除self外的其他形参提供值即可
  3. name和age都有前缀self,以self为前缀的变量可供类中的所有方法使用,这样可以通过实例访问的变量称为属性
  • 根据类创建实例
class Dog:--snip--my_dog= Dog('Willie',6)print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")

My dog’s name is Willie.
My dog is 6 years old.

  • 调用方法
my_dog.sit()
my_dog.roll_over()

Willie is now sitting.
Willie rolled over!

  • 给属性指定默认值

不用在函数中声明一个新的形参,直接在定义中添加属性

def __init__(self, make, model, year):"""初始化描述汽车的属性"""self.make = makeself.model=modelself.year=yearself.odometer_reading = 0
  • 修改属性的值
  1. 直接修改属性的值

my_new_car.odometer_reading=23

  1. 通过方法修改属性的值
def update_odometer(self, mileage):self.odometer_reading = mileagemy_new_car.read_odometer(12)
  1. 通过方法对属性的值进行递增
def increment_odometer(self, miles):self.odometer_reading += miles

餐厅作业

class Restaurant:def __init__(self, restaurant_name, cuisine_type):self.restaurant_name=restaurant_nameself.cuisine_type=cuisine_typeself.number_served=0def describe_restaurant(self):print(f"\nWe are {self.restaurant_name}, we offer {self.cuisine_type} type food")def open_restaurant(self):print("We are opening~")def read_number(self):print(f"{self.number_served} people have came to {self.restaurant_name}")def set_number_served(self, number):self.number_served = numberdef increment_number_served(self, increase):self.number_served+=increaserestaurant_1=Restaurant('Song Hotpot','Hotpot')
restaurant_1.describe_restaurant()
restaurant_1.open_restaurant()restaurant_2=Restaurant('Tah','taiguocai')
restaurant_2.describe_restaurant()restaurant_3=Restaurant('Malubianbian','BBQ')
restaurant_3.describe_restaurant()restaurant_1.read_number()
restaurant_1.number_served=23
restaurant_1.read_number()restaurant_2.read_number()
restaurant_2.set_number_served(14)
restaurant_2.read_number()restaurant_3.read_number()
restaurant_3.increment_number_served(225)
restaurant_3.read_number()

We are Song Hotpot, we offer Hotpot type food
We are opening~

We are Tah, we offer taiguocai type food

We are Malubianbian, we offer BBQ type food
0 people have came to Song Hotpot
23 people have came to Song Hotpot
0 people have came to Tah
14 people have came to Tah
0 people have came to Malubianbian
225 people have came to Malubianbian

  • 继承

特殊函数super()能够调用父类的方法

class User:def __init__(self, first_name, last_name, gender, hobby):self.first_name=first_nameself.last_name=last_nameself.gender=genderself.hobby=hobbydef describe_user(self):print(f"Name - {self.first_name.title()} {self.last_name.title()}")print(f"Is a {self.gender.title()}. Hobby is {self.hobby}")def greet_user(self):print(f"Hello~ {self.first_name}")class Privileges:def __init__(self):self.privileges=['can add post','can delete post','can ban user']def show_privileges(self):print(f"ADMIN can do things like {self.privileges}.")class Admin(User):def __init__(self, first_name, last_name, gender, hobby):super().__init__(first_name, last_name, gender, hobby)self.privilege = Privileges()admin_user=Admin('ziqi','yin','female','dance')
admin_user.privilege.show_privileges()

ADMIN can do things like [‘can add post’, ‘can delete post’, ‘can ban user’].

  • 导入类

0228

  • 文件和异常
  1. 读取文件路径使用斜杠或者双反斜杠
  2. for line in file_name可用于遍历循环
"""读取整个文件"""
filename = 'learning_python.txt'
with open(filename) as file_object:contents = file_object.read()print(contents.rstrip())"""遍历文件对象"""
with open(filename) as file_object:for line in file_object:print(line.rstrip())"""存储在列表中"""
with open(filename) as file_object:lines = file_object.readlines()for line in lines:print(line.rstrip())

In Python you can liebiao
In Python you can shuzu
In Python you can zidian
In Python you can hanshu
In Python you can liebiao
In Python you can shuzu
In Python you can zidian
In Python you can hanshu
In Python you can liebiao
In Python you can shuzu
In Python you can zidian
In Python you can hanshu

  • 10.2替换
filename = 'learning_python.txt'
"""存储在列表中"""
with open(filename) as file_object:lines = file_object.readlines()for line in lines:line=line.rstrip()print(line.replace('Python','C'))

In C you can liebiao
In C you can shuzu
In C you can zidian
In C you can hanshu

  • 调用open()时的实参

第一个是打开的文件名称,第二个是模式,读取’r’,写入’w’,附加’a’,读写模式’r+‘。忽略的话将以默认的只读模式打开文件

filename = 'programming.txt'
##写入多行
with open(filename, 'w') as file_object:file_object.write("I love programming.\n")file_object.write("I love creating new games\n")##附加到文件
with open(filename, 'a') as file_object:file_object.write("I also love finding meaning in large datasets.\n")file_object.write("I love creating apps that can run in a browser.\n")

I love programming
I love creating new games

  • 10_4
filename = 'guest_book.txt'
while True:guest_name = input("Please tell me your name: (Enter 'quit' when you are finished.)")if guest_name == 'quit':breakelse:print(f"\nHello~ {guest_name}")with open(filename, 'a') as file_object:file_object.write(guest_name+" has come here\n")
  • 10_6
print("Give me two numbers and I'll give you the summary")
first_number=input("\nFirst number:")
second_number=input("\nSecond number:")
try:sum=int(first_number)+int(second_number)
except ValueError:print("Please input number!")
else:print(sum)
  • json.dump()
import json
numbers = [2,3,4,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as f:json.dump(numbers,f)

参数1:要存储的数据

参数2:用于存储数据的文件对象

  • json.load()

将列表读取到内存中:

import jsonfilename='numbers.json'
with open(filename) as f:numbers = json.load(f)print(numbers)
  • 测试
#导入了模块和要测试的函数
import unittest
from name_function import get_formatted_name#创建的NameTestCase类用于包含一系列针对get_formatted_name()的单元测试
#必须继承unittest.TestCase才说明是测试类
class NamesTestCase(unittest.TestCase):"""测试name_function.py"""def test_first_last_name(self):"""能够正确的处理像Janis Joplin这样的姓名吗?"""formatted_name = get_formatted_name('janis','joplin')#使用了断言方法,核实得到的结果是否与期望的结果一致self.assertEqual(formatted_name,'Janis Joplin')#检查特殊变量__name__,是程序执行时设置的
#如果该文件作为主程序执行,变量name将被设置为main,调用unittest.main()来运行测试用例
#如果该文件被测试框架导入,变量__name__的值将不会是main,因此不会调用unittest.main()
if __name__=='__main__':unittest.main()

.

---------------------------—----------------------------------------—

Ran 1 test in 0.000s

OK

【Python编程从入门到实践】学习笔记相关推荐

  1. python基础学习[python编程从入门到实践读书笔记(连载一)]

    写在前面:本文来自笔者关于<python编程从入门到实践>的读书笔记与动手实践记录. 程序员之禅 文章目录 02变量和简单数据类型 03 列表简介 04 操作列表 05 if语句 06 字 ...

  2. python基础学习[python编程从入门到实践读书笔记(连载三)]:django学习笔记web项目

    文章目录 Django项目:学习笔记web网页 项目部署 参考 自己部署的网站,还是小有成就感的,毕竟踩过很多坑,实战技能也有些许进步. 网站链接:http://lishizheng.herokuap ...

  3. python基础学习[python编程从入门到实践读书笔记(连载五)]:数据可视化项目第16章

    文章目录 下载数据 制作全球地震散点图:JSON格式 end 几个实验结果: 每日最高气温: 地震图绘制: 下载数据 CSV文件格式 在文本文件中存储数据,一个简单方式是将数据作为一系列以逗号分隔的值 ...

  4. python编程从入门到实践读书笔记-《Python编程:从入门到实践》项目部分读书笔记(二)...

    鸽了一个暑假没有更新,现在趁着还没开学更一下.咕咕咕 上期作业: 请创建一个Django项目,命名为Blog,建不建立虚拟环境随便你,最后本地跑成了就行. 步骤: ①在需要创建工程的文件夹下打开cmd ...

  5. python基础学习[python编程从入门到实践读书笔记(连载二)]:外星人入侵项目

    第一版游戏demo 添加计分系统:中间是最高得分,右边是本次得分. 显示余下的飞船数 主函数如下,完整程序将上传到笔者的github:https://github.com/shizhengLi/lea ...

  6. python基础学习[python编程从入门到实践读书笔记(连载六)]:数据可视化项目第17章

    文章目录 使用API end 项目结果: 使用plotly可视化github最受欢迎的python仓库: 修改后的可视化图表: 使用API 编写独立的程序,实现对获取的数据可视化.我们使用Web AP ...

  7. python基础学习[python编程从入门到实践读书笔记(连载四)]:数据可视化项目第15章

    文章目录 matplotlib初学 基础绘图用法 随机漫步 使用Plotly模拟掷骰子 matplotlib初学 基础绘图用法 import matplotlib.pyplot as pltsquar ...

  8. python编程:从入门到实践 阅读笔记

    文章目录 第一章 起步 第二章 变量和简单数据类型 String 数字 整数 浮点数 第三章 列表简介 第四章 操作列表 元组 第五章 if 语句 第六章 字典 第七章 用户输入和while循环 第八 ...

  9. 《Python编程从入门到实践》袁国忠 译 P1~P200学习笔记

    <Python编程从入门到实践>袁国忠 译 P1~P200 学习笔记 <Python编程从入门到实践>袁国忠 译 P1~P200之前两天在学习时做的笔记总结,在这里也记录一下, ...

  10. 《python编程从入门到实践》python入门级-学习笔记(1-2章)——持续更新中

    CSDN的小伙伴们你们好~从今天起我开始自学编程了. 恭喜你关注到一个成长型账号. 一以来作为美术出身的TA,我无数次的向往能打出几行属于自己的代码.为了跟上时代的步伐,也为了能更加深入TA这个职业, ...

最新文章

  1. 玩转java(Android)注解
  2. 网传的 Spring 大漏洞
  3. 代码规范之华为公司代码规范
  4. jsp里面声明了utf-8格式,也写了字符编码过滤器,数据库编码也是utf-8,就连java.......
  5. ARCHLinux SETUP WITH FDISK
  6. Spring Boot——不同环境调用不同的配置文件解决方案
  7. 剪映电脑版_2020 年双十一要不要选一个平板电脑?
  8. openstack 安装windows系统
  9. 浅谈面向对象编程与面向过程编程
  10. PAT:1059. Prime Factors (25) AC
  11. 【计算机网络】一文搞懂IP及子网掩码相关问题
  12. 在centos8环境下用asterisk18配置pjsip和webrtc音视频通话教程(一)
  13. TPAMI 2021 | 让时间走向二维,基于文本的视频时间定位新方法:MS-2D-TAN,兼顾速度与精度!...
  14. 编译原理学习 一 什么是编译程序
  15. 写给程序员的编程语言科普——前言
  16. GitHub: ProxyPool 爬虫代理IP池
  17. “后网联时代”聚合支付发展方向思考
  18. python 小说词频统计_Python中文分词及词频统计
  19. suma: error while loading shared libraries: libGLw.so.1: cannot open shared object file: No such
  20. OracleDBA精选面试题

热门文章

  1. 【一分钟学会】用python做一个语音对话ChatGPT的程序——打造私人语音助手
  2. SPSS 操作(一)数据选取 :个案选取和字符变量的筛选
  3. 3D ROTATION MATRIX
  4. GitLab集成gitlab-runner
  5. 云服务器实战篇 - Google免费云申请、登录、使用
  6. 实战四十八:基于python设置的分词系统(完整代码+数据、毕业设计)
  7. GIS数据:4D产品
  8. 复合材料知识概况了解
  9. python倒序输出数组_python如何逆序输出数组
  10. 微信小程序实战篇-商品详情页(二)