字符串
概念定义
字符串是一系列字符
使用字符串
字符串元素的大小写name="Ada Lovelace" print(name) print(name.title())#首字母大写 print(name.upper())#所有字母大写 print(name.lower())#所有字母小写Ada Lovelace Ada Lovelace ADA LOVELACE ada lovelace删除字符串空白>>>language=' python >>>language ' python ' >>>language.lstrip()#删除左端空白 'python ' >>>language.rstrip()#删除右端空白 ' python' >>>language.strip()#删除左右两端空白 'python'删除前缀>>>nostarch_url="https://nostarch.com" >>>nostarch_url.removeprefix('https://') 'nostarch.com'
列表
概念定义
列表(list)是由一系列按照特定顺序排列的元素组成
访问列表元素
利用元素的索引来访问元素值
bicycles=['trek','cannondale','redline','specialized'] print(bicycles[0]) print(bicycles[3]) print(bicycles[-1]) messages=f"My first bicycle was a {bicycles[0].title()}"'''在字符串中插入变量的值,使用f字符串,f为format的简写,Python通过把花括号的变量替换成变量的值来设置字符串的格式''' print(messages) #列表元素的索引是从0开始 '''列表元素索引为3的元素为specialized,而不是redline''' """索引-1表示列表的最后一个元素""" #bicycles[0]为对象;title()为方法即函数; #bicycles[0].title()为对象调用title()方法的形式
trek specialized specialized My first bicyvle was a Trek
修改列表元素
#motorcycles.py motorcycles=['honda','yamaha','suzuki'] print(motorcycles) motorcycles[0]='ducati' print(motorcycles)
['honda','yamaha','suzuki'] ['honda','yamaha','suzuki'] ['ducati','yamaha','suzuki']
添加列表元素
#motorcycles.py motorcycles=['honda','yamaha','suzuki'] motorcycles.append('ducati') print(motorcycles)
['honda','yamaha','suzuki','ducati']
删除列表元素
- 使用del语句删除列表元素
#motorcycles.py motorcycles=['honda','yamaha','suzuki'] print(motorcycles) del motorcycles[1] print(motorcycles)['honda','yamaha','suzuki'] ['honda','suzuki']
- 使用pop()方法删除列表元素,并返回删除值
#motorcycles.py motorcycles=['honda','yamaha','suzuki'] print(motorcycles) motorcycle=motorcycles.pop(0)#括号内为标索引则默认删除最后一个元素,并将其返回 print(f"The first motorcycle I woned was a {motorcycle.title()}.")['honda','yamaha','suzuki'] The first motorcycle I woned was a honda.
- 根据值删除元素
motorcycles=['honda','yamaha','suzuki','ducati'] too_expensive='ducati' mororcycles.remove(too_expensive) print(motorcycles) print(f"\nA {too_expensive.title()} is too expensive for me!")['honda','yamaha','suzuki'] A Ducati is too expensive for me!
使用sort()方法对列表进行永久排序
- 正序(字母表)
#cars.py cars = ['bmw','audi','toyota','subaru'] cars.sort() print(cars)['audi','bmw','subaru','toyota']
- 反序(反字母表)
#cars.py cars = ['bmw','audi','toyota','subaru'] cars.sort(reverse==True) print(cars)['toyota','subaru','bmw','audi']
使用sorted()方法对列表进行临时排序#cars.py cars = ['bmw','audi','toyota','subaru'] print("Here is the orignal list:") print(cars) print("Here is the sorted list:") print(sorted(cars)) print(sorted(cars,reverse==True)) pritn("Here is the orignal list agin:") print(cars)Here is the orignal list: ['bmw','audi','toyota','subaru'] Here is the sorted list: ['audi','bmw','subaru','toyota'] ['toyota','subaru','bmw','audi'] Here is the orignal list agin: ['bmw','audi','toyota','subaru']
反向打印列表#cars.py cars = ['bmw','audi','toyota','subaru'] print(cars) cars.reverse() print(cars)['bmw','audi','toyota','subaru'] ['subaru','toyota','audi','bmw']
使用len()方法列表长度#cars.py cars = ['bmw','audi','toyota','subaru'] len(cars)4
操作列表
遍历列表magicians = ['alice','david','carolina'] for magician in magiccians: print(magician)alice david carolina创建数值列表#values.py for value in range(1,5): print(value) #for 循环打印1-4的整数,range()方法是左闭右开区间[1,5)1 2 3 4#number_list.py numbers = list(range(1,6))#使用强制转换将数字转换成列表 print(numbers)[1,2,3,4,5]#even_numbers_list.py even_numbers = list(range(2,11,2))#range()方法有3个参数时,第三个参数为步长 print(even_numbers)[2,4,6,8,10]#square_numbers.py for value in range(1,11): square = value ** 2 squares.append(square) 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列表推导式#square_numbers.py squares=[value**2 for value in range(1,11)] print(squares)[1,4,9.16,25,36,49,64,81,100]
切片(slice)
创建切片,需要使用第一个元素和最后一个元素的索引,与range()函数一样,Python 在到达指定的第二个索引之前的元素时停止。要输出列表的前三个元素,要指定索引为0和3,将会返回索引分别为0,1,2的元素。
#players.py players = ['charles','martina','michael','florence','eil'] print(players[0:3])
['charles','martina','michael']
如果需要提取列表的第二、三、四个元素,要指定索引为1和4
#players.py players = ['charles','martina','michael','florence','eil'] print(players[1:4])
['martina','michael','florence']
如若未指定第一个索引,Python将自动从列表开头开始
#players.py players = ['charles','martina','michael','florence','eil'] print(players[:4])
['charles',martina','michael','florence']#注意没有到5,则为显示eil
如若未指定结束索引,Python自动遍历至列表尾部
#players.py players = ['charles','martina','michael','florence','eil'] print(players[2:]) print(players[-3:])
['michael','florence','eil'] ['michael','florence','eil']
遍历切片遍历列表中的部分元素,在for循环中使用列表切片。
#players.py players = ['charles','martina','michael','florence','eil'] print("Here is the first three player on my team:") for player in players[:3]:#只遍历前三名队员 print(player.title())
Here is the first three player on my team: Charles Martina Michael
复制列表复制列表,可以创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:])。让Python创建一个起始于第一个元素,终止于最后一个元素的切片,即复制整个列表。
#food.py my_foods=['pizza','falafel','carrot cake'] friend_foods=my_foods[:]#[:]不能省略,此时是将my_foods的副本赋给friend_foods。 #如若是friend_foods=my_foods则是将my_foods赋值给friend_foods,两个指向同一个列表。 my_foods.append('cannoli') print("My favorite foods are:") print(my_foods) print("My friend favorite foods are:") print(friend_foods)
My favorite foods are: ['pizza','falafel','carrot cake','cannoli'] My friend favorite foods are: ['pizza','falafel','carrot cake']
元组
元组定义概念不可变的列表即为元组(tuple)
操作元组定义元组#dimensions.py dimensions = (200,50) print(dimensions[0]) print(dimensions[1])200 50遍历元组#dimensions.py dimensions =(200,50) for dimension in dimensions: print(dimension)200 50修改元组的值元组的元素是无法被修改的,但是可以给表示元组的变量进行赋值,重新定义元组#dimensions.py dimensions = (200,50) print("Orignal dimensions:") for dimension in dimensions: print(dimension) dimensions = (400,100) print("\nModified dimensions:") for dimension in dimensions: print(dimension)Orignal dimensions: 200 50 Modified dimensions: 400 100
条件判度if语句
测试一个条件
只适用仅有一个条件满足的情况
- if语句
if 条件为true,执行后续程序;条件为false,跳出判断后续代码;
- if-else语句
if条件为true,执行if后面程序,否则执行else后面程序
- if-elif-else语句
if 条件为true,执行if后面程序,程序完成跳出条件判断,否则执行elif 判断条件,当条件为true时,执行elif后续程序,程序代码完成跳出判断,否则执行else后面程序代码,执行完成跳出条件判断
- if-elif-elif语句
测试多个条件
需要测试多个条件是否满足的情况
- if-if-if
字典
概念定义
字典(dictionary)是一系列键值对。每一个键都与值关联,可以使用键来访问相关连的值。在Python中字典用放在花括号“{}”中的一系列键值对来表示的。
#aline.py aline_0 = {'color':'green','points':5} print(aline_0['color']) new_points = cline_0['points'] print(f"You just earned {new_points} points!")
green You just earned 5 points!
添加键值对
字典是一种动态结构,可以随时在其中添加键值对。需要依次指定字典名,用方括号括起来的键和键关联的值。字典会保留定义是的元素排列顺序。
#alien.py alien_0 = {'color':'green','points':5} print(alien_0) alien_0['x_position'] = 0 alien_0['y_position'] = 25 print(alien_0)
{'color':'green','points':5} {'color':'green','points':5,'x_position':0,'y_position':25}
如果需要使用字典来存储用户提供的数据或编写能自动生成大量键值对的代码,通常先创建一个空字典。
修改字典中的值
要修改字典中的值,可一次指定字典中的键名,用方括号括起来的键和键关联的新值
#alien.py alien_0 = {'x_position':0,'y_position':25,'speed':'medium'} print(f"Orignal position:{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'] = x_increment + alien_0['x_position'] print(f"Now position:{alien_0['x_position']}")
Orignal position:0 Now position:2
删除键值对(del语句)
#alien.py alien_0 = { 'color':'green', 'position':5, } print(alien_0) del alien_0['position'] print(alien_0)
{'color':'green','position':5} {'color':'green'}#删除后将永久消失
使用get()访问值
使用方括号里的键从字典中获取感兴趣的值,可能会引发问题:当指定的键不存在,则会出现错误。
#alien.py alien_0 = {'color':'green','speed':'slow'} print_value = alien_0.get('points','No point value assigned.') print(print_value)
如果字典中有键'points',则获取键关联的值,否则将获取指定的默认值。在调用get()函数时,如果没有指定第二个参数且指定的键不存在,则Python将放回None。
No point value asigned.
遍历字典
- 遍历所有的键值对
利用for 循环,借用两个变量分别保存键名和值,items()返回键-值对列表
#user.pu user_0 ={ 'username':'efermi', 'first':'enrico', 'last':'fermi', } for key,value in user_0.items(): print(f"\n key:{key}") print(f"\n value:{value}")
key: last Value: fermi Key: first Value: enrico Key: username Value: efermi
注意,即便遍历字典时,键—值对的返回顺序也与存储顺序不同。Python不关心键—值对的存 储顺序,而只跟踪键和值之间的关联关系。
- 遍历所有的键
利用for 循环,用一个变量保存字典的键名,keys()
#favorite_languages favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name in favorite_languages.keys(): print(name.title())
提取字典favorite_languages中的所有键,并依次将它们存储到变量name中。输出列出了每个被调查者的名字:
Jen Sarah Phil Edward
遍历字典时,会默认遍历所有的键.因此,如果将上述代码中的for name in favorite_languages.keys():替换为for name in favorite_languages:,输出将不变。
- 按顺序遍历字典中的所有键
字典总是明确地记录键和值之间的关联关系,但获取字典的元素时,获取顺序是不可预测的。
要以特定的顺序返回元素,一种办法是在for循环中对返回的键进行排序。为此,可使用函
数sorted()来获得按特定顺序排列的键列表的副本:
#favorite_languages.py favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name in sorted(favorite_languages.keys()): print(name.title() + ", thank you for taking the poll.")
dictionary.keys()的结果调用了函数sorted()。这让Python列出字典中的所有键,并在遍历前对这个列表进行排序。输出表明,按顺序显示了所有被调查者的名字:
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.
遍历字典中的所有值
利用for循环,用一个变量存储字典的值,values();set()集合,剔除重复项。
#favorite_languages.py favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } print("The following languages have been mentioned:") for language in set(favorite_languages.values()): #为剔除重复项,可使用集合(set)。集合类似于列表,但每个元素都必须是独一无二的: print(language.title())
The following languages have been mentioned: Python C Ruby
嵌套
可以在列表中嵌套字典、在字典中嵌套列表,可以在字典中嵌套字典。
字典列表
#alien.py alien_0 = {'color': 'green', 'points': 5} alien_1 = {'color': 'yellow', 'points': 10} alien_2 = {'color': 'red', 'points': 15} aliens = [alien_0, alien_1, alien_2] for alien in aliens: print(alien)
{'color': 'green', 'points': 5} {'color': 'yellow', 'points': 10} {'color': 'red', 'points': 15}
将前三个外星人修改为黄色的、速度为中等且值10个点
#alien.py # 创建一个用于存储外星人的空列表 aliens = [] # 创建30个绿色的外星人 for alien_number in range(30): new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} aliens.append(new_alien) #将前三个外星人修改为黄色的、速度为中等且值10个点 for alien in aliens[0:3]: if alien['color'] == 'green': alien['color'] = 'yellow' alien['speed'] = 'medium' alien['points'] = 10 # 显示前五个外星人 for alien in aliens[:5]: print(alien) print("...") # 显示创建了多少个外星人 print("Total number of aliens: " + str(len(aliens)))
{'speed': 'medium', 'color': 'yellow', 'points': 10} {'speed': 'medium', 'color': 'yellow', 'points': 10} {'speed': 'medium', 'color': 'yellow', 'points': 10} {'speed': 'slow', 'color': 'green', 'points': 5} {'speed': 'slow', 'color': 'green', 'points': 5} ... Total number of aliens: 30
字典中存储列表
在字典中将一个键关联到多个值时,可以在字典中嵌套一个列表.
#Pizza.py # 存储所点比萨的信息 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.py 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 Phil's favorite languages are: Python Haskell Edward's favorite languages are: Ruby Go
字典中存储字典
例如,如果有多个网站用户,每个都有独特的用户名,可在字典中将用户名作为键,然后将每位用户的信息存储在一个字典中,并将该字典作为与用户名相关联的值。在下面的程序中,对于每位用户,我们都存储了其三项信息:名、姓和居地;为访问这些信息,我们遍历所有的用户名,并访问与每个用户名相关联的信息字典:
#many_users.py 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
用户输入
文本输入input()函数
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入Python将其存储在一个变量中。input()函数获取的将被视为字符串,即使输入的文本为数字,也将以字符串的形式存储。
#greeter.py prompt = "If you tell us who you are, we can personalize the messages you see." #运算符+=在存储在prompt中的字符串末尾附加一个字符串。 prompt += "\nWhat is your first name? " name = input(prompt) print("\nHello, " + name + "!")
If you tell us who you are, we can personalize the messages you see. What is your first name? Eric Hello, Eric!
获取数值输入int()函数
>>> age = input("How old are you? ") How old are you? 21 >>> age '21'#返回的是'21'——用户输入的数值的字符串表示。 >>> age >= 18 Traceback (most recent call last):#报错提示 File "<stdin>", line 1, in <module> TypeError: unorderable types: str() >= int()
Traceback (most recent call last):#报错提示TypeError: unorderable types: str() >= int()无法将字符串和整数进行比较:不能将存储在age中的字符串'21'与数值18进行比较
>>> age = input("How old are you? ") How old are you? 21 >>> age = int(age)#int()函数将字符串强制转换成数值 >>> age >= 18 True
求模运算(%)[取余运算]
求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数:
>>> 4 % 3 1 >>> 5 % 3 2 >>> 6 % 3 0 >>> 7 % 3 1
如果一个数可被另一个数整除,余数就为0,因此求模运算符将返回0。你可利用这一点来判 断一个数是奇数还是偶数:
#even_or_odd.py number = input("Enter a number, and I'll tell you if it's even or odd: ") number = int(number) if number % 2 == 0:#偶数 print("\nThe number " + str(number) + " is even.") else:#奇数 print("\nThe number " + str(number) + " is odd.")
Enter a number, and I'll tell you if it's even or odd: 42 The number 42 is even.
While()循环
for循环用于针对集合中的每个元素都一个代码块,而while循环不断地运行,直到指定的条 件不满足为止。
current_number = 1 while current_number <= 5: print(current_number,end=',') current_number += 1
1,2,3,4,5
#让用户自己选择是否需要继续 #parrot.py prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " message = "" while message != 'quit': message = input(prompt) print(message)
Tell me something, and I will repeat it back to you: Enter 'quit' to end the program. Hello everyone! Hello everyone! Tell me something, and I will repeat it back to you: Enter 'quit' to end the program. Hello again. Hello again. Tell me something, and I will repeat it back to you: Enter 'quit' to end the program. quit quit
使用标志,改变标志控制循环
#parrot.py prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " active = True while active: message = input(prompt) if message == 'quit': active = False else: print(message)
使用break结束循环
#cities.py prompt = "\nPlease enter the name of a city you have visited:" prompt += "\n(Enter 'quit' when you are finished.) " while True: city = input(prompt) if city == 'quit': break else: print("I'd love to go to " + city.title() + "!")
Please enter the name of a city you have visited: (Enter 'quit' when you are finished.) New York I'd love to go to New York! Please enter the name of a city you have visited: (Enter 'quit' when you are finished.) San Francisco I'd love to go to San Francisco! Please enter the name of a city you have visited: (Enter 'quit' when you are finished.) quit
使用continue结束本层循环,继续下一次循环
#counting.py current_number = 0 while current_number < 10: current_number += 1 if current_number % 2 == 0: continue print(current_number,end=' ')
1 3 5 7 9
使用while循环操作列表
#confirmed_users.py unconfirmed_user = ['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 # -*- coding: UTF-8 -*- pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(pets) while 'cat' in pets:#循环检查cat是否在列表中 pets.remove('cat') print(pets)
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] ['dog', 'dog', 'goldfish', 'rabbit']
使用while循环操作字典
#mountain_poll.py # -*- coding: UTF-8 -*- 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? Eric Which mountain would you like to climb someday? Denali Would you like to let another person respond? (yes/ no) yes What is your name? Lynn Which mountain would you like to climb someday? Devil's Thumb Would you like to let another person respond? (yes/ no) no --- Poll Results --- Lynn would like to climb Devil's Thumb. Eric would like to climb Denali.
函数
def语句定义函数
#greeter.py # -*- coding: UTF-8 -*- def greeter_user(username): print("Hello@"+username) greeter_user(敬请T期待)
Hello@敬请T期待
位置实参
#pets.py # -*- coding: UTF-8 -*- 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')#传递实参hamster,harry
I have a hamster. My hamster's name is Harry.
传递实参时需要注意传递的实参的位置,不能随意变换
关键字实参
# -*- coding: UTF-8 -*- #pets.py 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(animal_type='hamster', pet_name='harry')#传递关键字实参
I have a harry. My harry's name is Hamster.
关键字实参的顺序无关紧要
默认值
编写函数时,可给每个形参指定默认值。在调用函数中给形参提供了实参时,Python将使用指定的实参值;否则,将使用形参的默认值。
# -*- coding: UTF-8 -*- 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(pet_name='willie')#当使用位置关键字时,只有一个实参,默认为pet_name describe_pet(pet_name='harry', animal_type='hamster')
I have a dog. My dog's name is Willie. I have a hamster. My hamster's name is harry.
- 等效的函数调用
# 一条名为Willie的小狗 describe_pet('willie') describe_pet(pet_name='willie') # 一只名为Harry的仓鼠 describe_pet('harry', 'hamster') describe_pet(pet_name='harry', animal_type='hamster') describe_pet(animal_type='hamster', pet_name='harry')
实参可选择化
使用空字符串,将实参进行可选择处理
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)
传递任意数量的实参
形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封 装到这个元组中。
#pizza.py def make_pizza(*toppings): """概述要制作的比萨""" print("\nMaking a pizza with the following toppings:") for topping in toppings: print("- " + topping) make_pizza('pepperoni') make_pizza('mushrooms','green peppers','extra cheese')
Making a pizza with the following toppings: - pepperoni Making a pizza with the following toppings: - mushrooms - green peppers - extra cheese
函数返回值
# -*- coding: UTF-8 -*- #formatted_name.py 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
函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。
#person.py # -*- coding: UTF-8 -*- 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}
#greet.py 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:",end='') print("(enter 'q' to 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: eric Last name: matthes Hello, Eric Matthes! Please tell me your name: (enter 'q' at any time to quit) First name: q
传递列表
#greet_users.py # -*- coding: UTF-8 -*- def greet_users(names): """向列表中的每一位用户发出简单的问候""" for name in names: msg = "Hello," + name.title() + "!" print(msg) usernames = ['hannah','ty','margot','敬请T期待'] greet_users(usernames)
Hello, Hannah! Hello, Ty! Hello, Margot! Hello, 敬请T期待!
在函数中修改列表
#print_models.py #首先创建一个列表,其中包含一些要打印的设计 unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] completed_models = [] #模拟打印每一个设计,直到没有未打印的设计为止 #打印每一个设计后,都将其移到列表completed_models中 while unprinted_designs: current_design = unprinted_designs.pop() #模拟根据设计制作3D打印模型的过程 print("Printing model:" + current_design) completed_models.append(current_design) #显示打印好的所有模型 print("\nThe following models have been printed:") for completed_models in completed_models: print(completed_model)
Printing model: dodecahedron Printing model: robot pendant Printing model: iphone case The following models have been printed: dodecahedron robot pendant iphone case
提高效率版
每个函数都应只负责一项具体的工作。第一个函数打印每个设计,而第二个显示打印好的模型;这优于使用一个函数来完成两项工作。编写函数时,如果你发现它执行的任务太多,请尝试将这些代码划分到两个函数中。别忘了,总是可以在一个函数中调用另一个函数,这有助于将复杂的任务划分成一系列的步骤。
#print_models() # -*- coding: UTF-8 -*- def print_models(unprinted_designs, completed_models): """ 模拟打印每个设计,直到没有未打印的设计为止 打印每个设计后,都将其移到列表completed_models中 """ while unprinted_designs: current_design = unprinted_designs.pop() # 模拟根据设计制作3D打印模型的过程 print("Printing model: " + current_design) completed_models.append(current_design) #show_completed_models() def show_completed_models(completed_models): """显示打印好的所有模型""" print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model) unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] completed_models = [] print_models(unprinted_designs, completed_models) show_completed_models(completed_models)
function_name(list_name[:])
切片表示法[:]创建列表的副本。向函数传递列表的副本可保留原始列表的内容。但除非有充分的理由需要传递副本,否则还是应该将原始列表传递给函数,因为让函数使用现成列表可避免花时间和内存创建副本,从而提高效率,在处理大型列表时尤其如此。
将函数存储在模块中
模块是扩展名为.py的文件,包含要导入到程序中的代码。
import 导入外部模块,但是需要用‘.语句’来调用函数module_name.function_name()调用模块内的函数;
#pizza.py # -*- coding: UTF-8 -*- def make_pizza(size, *toppings): """概述要制作的比萨""" print("\nMaking a " + str(size) +"-inch pizza with the following toppings:") for topping in toppings: print("- " + topping)
#在pizza.py所在的目录中创建另一个名为making_pizzas.py的文件,这个文件导入刚创建的模块,再调用make_pizza()两次: # -*- coding: UTF-8 -*- #making_pizza.py import pizza pizza.make_pizza(16, 'pepperoni') pizza.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
从模块中导入特定的一个函数
利用 from module_name import function_named
通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数:
from module_name import function_0, function_1, function_2
如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名——函数的另一个名称,类似于外号。要给函数指定这种特殊外号,需要在导入它时这样做。
# -*- coding: UTF-8 -*- #turtle.py #导入turtle库画一个正方形 import turtle as t color = ['red','green','purple','#33cc8c'] t.penup() t.begin_fill() t.goto(-100,-100) t.pendown() for i in range(4): t.pencolor(color[i]) t.forward(200) t.left(90) t.fillcolor('pink') t.end_fill() t.down()
# -*— coding: UTF-8 -*- #making_pizza.py from pizza import make_pizza as mp mp(16, 'pepperoni') mp(12, 'mushrooms', 'green peppers', 'extra cheese')
from module_name import *
from pizza import * make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
类
创建和使用类
#dog.py class Dog(): """一次模拟小狗的简单尝试""" def __init__(self, name, age): #注意:init左右两边各有2个”_"是"__"不是"_" """初始化属性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!")
__init__()是一个特殊的方法,对定义类的属性进行初始化,python自动调用,类似于C++的构造函数。注意:init左右两边各有2个”__"是"__"(两个英文下划线)不是"_"在这个方法的定义中,形参self必不可少,还必须位于其他形参的前面。Python调用这个__init__()方法来创建类实例时,将自动传入实参self。每个与类相关联的方法调用都自动传递实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。
调用实例的属性
#dog.py #coding=UTF-8 class Dog(): def __init__(self,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)#创建抽象类的实例化对象 print("My dog's name is "+ my_dog.name.title()) print("My dog is "+str(my_dog.age)+"years old.")
My dog's name is Willie. My dog is 6 years old.
调用实例的方法
#dog.py #coding=UTF-8 class Dog(): def __init__(self,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_dg=Dog('willie',6)#创建抽象类的实例化对象 my_dog.sit()#利用对象调用其包含的方法 my_dog.roll_over()#利用对象调用其包含的方法
Willie is now sitting. Willie rolled over!
创建多个实例
#dog.py #coding=UTF-8 class Dog(): def __init__(self,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) #对my_dog对象进行运用 print("My dog's name is " + my_dog.name.title() + ".") print("My dog is " + str(my_dog.age) + " years old.") my_dog.sit() #对your_dog对象进行运用 print("\nYour dog's name is " + your_dog.name.title() + ".") print("Your dog is " + str(your_dog.age) + " years old.") your_dog.sit()
My dog's name is Willie. My dog is 6 years old. Willie is now sitting. Your dog's name is Lucy. Your dog is 3 years old. Lucy is now sitting.
类中的每个属性都必须有初始值,哪怕这个值是0或空字符串。
#car.py 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 def read_odometer(self): """打印一条指出汽车里程的消息""" print("This car has " + str(self.odometer_reading) + " miles on it.") my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.read_odometer()
2016 Audi A4 This car has 0 miles on it.
三种不同的方式修改属性的值:
- 直接通过实例进行修改;
- 通过方法进行设置;
- 通过方法进行递增(增加特定的值)。
直接通过实例进行修改
#car.py 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 def read_odometer(self): """打印一条指出汽车里程的消息""" print("This car has " + str(self.odometer_reading) + " miles on it.") 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.
通过方法进行设置属性值
#car.py 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 def read_odometer(self): """打印一条指出汽车里程的消息""" print("This car has " + str(self.odometer_reading) + " miles on it def update_odometer(self, mileage): """将里程表读数设置为指定的值""" self.odometer_reading = mileage my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.update_odometer(23) my_new_car.read_odometer()
2016 Audi A4 This car has 23 miles on it.
通过方法对属性的值进行递增
#car.py 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 def read_odometer(self): """打印一条指出汽车里程的消息""" print("This car has " + str(self.odometer_reading) + " miles on it def update_odometer(self, mileage): """将里程表读数设置为指定的值""" self.odometer_reading = mileage def increment_odometer(self, miles): """将里程表读数增加指定的量""" self.odometer_reading += miles my_used_car = Car('subaru', 'outback', 2013) print(my_used_car.get_descriptive_name()) my_used_car.update_odometer(23500) my_used_car.read_odometer() my_used_car.increment_odometer(100) my_used_car.read_odometer()
2013 Subaru Outback This car has 23500 miles on it. This car has 23600 miles on it.
继承
使用super()函数将父类和子类串联起来。创建子类的实例时,Python首先需要完成的任务是给父类的所有属性赋值。创建子类时,父类必须包含在当前文件中,且位于子类前面。
#electric_car.py 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 class ElectricCar(Car): """电动汽车的独特之处""" def __init__(self, make, model, year): """初始化父类的属性""" super().__init__(make, model, year) my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name())
2016 Tesla Model S
#electric_car.py 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 class ElectricCar(Car): """Represent aspects of a car,specific to electric vehicles.""" def __init__(self,make,model,year): """ 电动汽车的独特之处 初始化父类的属性,在初始化电动汽车特有的属性 """ super().__init__(make,model,year) self.battery_size = 70 def describe_battery(self): """打印一条描述电瓶容量的消息""" print("This car has a " + str(self.battery_size) + "-kWh battery.") my_tesla = ElectricCar("tesla",'model s',2016) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery()
2016 Tesla Model S This car has a 70-kWh battery.
#electric_car.py 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 def fill_gas_tank(self,size): print("This size of gas tank of the car is "+ str(size)) class ElectricCar(Car): """Represent aspects of a car,specific to electric vehicles.""" def __init__(self,make,model,year): """ 电动汽车的独特之处 初始化父类的属性,在初始化电动汽车特有的属性 """ super().__init__(make,model,year) self.battery_size = 70 def describe_battery(self): """打印一条描述电瓶容量的消息""" print("This car has a " + str(self.battery_size) + "-kWh battery.") #对父类的fill_gas_tank()方法进行重载 def fill_gas_tank(): """电动车没有油箱""" print("This car doesn't need a tank!")
#electric_car.py 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 def fill_gas_tank(self,size): print("This size of gas tank of the car is "+ str(size)) 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) class ElectricCar(Car): """电动汽车的独特之处""" def __init__(self, make, model, year): """初始化父类的属性,再初始化电动汽车特有的属性""" super().__init__(make, model, year) self.battery = Battery() my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name()) my_tesla.battery.describe_battery() my_tesla.battery.get_range()
2016 Tesla Model S This car has a 70-kWh battery. This car can go approximately 240 miles on a full charge.
导入类
from 文件名 import 类名
#car.py """一个可用于表示汽车的类""" 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_car.py from car import 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 模块名 import 类名,类名
#my_cars.py from electric_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 模块名导入模块中的所有类:from module_name import *
Python标准库
推荐几个查看Python标准库的网址:
一、collestions库中的OrderedDict方法
OrderedDict()创建一个有序字典,它记录了键值对添加的顺序
from collestions import OrderedDict #将字典的键和值的顺序进行记录 favorite_languages = OrderedDict() #调用OrderedDict()函数创建favorite_languages空字典 favorite_languages['jen'] = 'python' favorite_languages['sarah'] = 'c' favorite_languages['edward'] = 'ruby' favorite_languages['phil'] = 'python' for name, language in favorite_languages.items(): print(name.title() + "'s favorite language is " +language.title() + ".")
Jen's favorite language is Python. Sarah's favorite language is C. Edward's favorite language is Ruby. Phil's favorite language is Python.
二、random库中的randint()方法
randint()返回一个位于指定范围内的整数
文件操作
从文件中读取数据
open( 'files_name')打开文件并且返回一个文件对象,注意,该文件和当前执行的文件所在目录相同,如若不同则应该写入文件路径:Linux 和OS X系统中的文件路径用'/'斜杆with open('text_files/filename.txt') as file_object:Windows系统中文件路径用'\'反斜杠with open('text_files\filename.txt') as file_object:
with open('files_name.txt') as file_objecta:#files_name需要带上文件后缀 """关键字with,让Python负责妥善地打开和关闭文件。""" contents = file_object.read() """file_object.read()调用读取函数读取文件中的内容""" print(contents.rstrip())#rstrip会删除字符串末尾的字符
for line in file_object:利用循环进行逐行读取文件内容
pi_digits.txt3.1415926535 8979323846 2643383279
filename = 'pi_digits.txt' with open(filename) as file_object: for line in file_object: print(line.rstrip())
3.1415926535 8979323846 2643383279
lines = file_object.readlines() #调用readlines()函数将文件的各行存储在创建的列表中
filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip())
3.1415926535 8979323846 2643383279
#pi_string.py filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.strip() print(pi_string) print(len(pi_string))
3.141592653589793238462643383279 32
### 写入文件
with open(filename,'a') as file_object:#以附加模式打开文件模式:#读取模式‘r'#写入模式'w,'打开前清空文件内容#附加模式'a'#读取和写入模式'r+'file_object.write("需要写入的内容")注意:Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式。
#write_messages.py filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming.\n") file_object.write("敬请T期待@") file_object.write("KingWempity")
programming.txt
I love programming. 敬请T期待@KingWempity
存储数据
使用json模块来存储数据通常使用文件扩展名.json来指出文件存储的数据为JSON格式。
函数json.dump()接受两个实参:要存储的数据以及可用于存储数据的文件对象。
#number_writer.py import json numbers = [2, 3, 5, 7, 11, 13] filename = 'numbers.json' with open(filename, 'w') as f_obj: json.dump(numbers, f_obj) """ 先导入模块json,再创建一个数字列表。我们指定了要将该数字列表存储到其中的文件的名称。通常使用文件扩展名.json来指出文件存储的数据为JSON格式。接下来,我们以写入模式打开这个文件,让json能够将数据写入其中。我们使用函数json.dump()将数字列表存储到文件numbers.json中。 """
打开文件numbers.json
[2, 3, 5, 7, 11, 13]
函数json.load()加载存储在filename.json中的信息
#number_reader.py import json filename = 'numbers.json' with open(filename) as f_obj: numbers = json.load(f_obj) print(numbers)
[2, 3, 5, 7, 11, 13]
#remember_me.py import json username = input("What is 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 + "!")
What is your name? Eric We'll remember you when you come back, Eric!
#greet_user.py import json filename = 'username.json' with open(filename) as f_obj: username = json.load(f_obj) print("Welcome back, " + username + "!")
Welcome back, Eric!
#remember_me.py 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 remember you when you come back, " + username + "!") else: print("Welcome back, " + username + "!")
首次运行
What is your name? Eric We'll remember you when you come back, Eric!
否则
Welcome back, Eric!
结语
至此,本书第一部分基础知识已基本完结撒花❀❀❀
🎇🎇🎇
推荐几个个版本python知识学习的网址
虽然都是菜鸟教程,但因为版本问题,版本界面有些许变化,笔者更适应第一个,因人而异,最适合自己的才是最好的!Python官网的文档,里面有一切想要了解的东西!教程、标准库、语言参考、安装用法......笔者不才,如有错误还望读者指正,后续会更新评论版块,欢迎大家留言指正!!!敬请T期待!感谢各位读者朋友的支持和理解!❀❀❀
