motorcycle=motorcycles.pop(0)#括号内为标索引则默认删除最后一个元素,并将其返回 print(f"The first motorcycle I woned was a {motorcycle.title()}.")
1 2
['honda','yamaha','suzuki'] The first motorcycle I woned was a honda.
根据值删除元素
1 2 3 4 5
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!")
1 2 3
['honda','yamaha','suzuki'] A Ducati is too expensive for me!
#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)
1 2 3 4 5 6 7
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']
#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())
1 2 3 4
Here is the first three player on my team: Charles Martina Michael
#favorite_languages.py favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name insorted(favorite_languages.keys()): print(name.title() + ", thank you for taking the poll.")
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()集合,剔除重复项。
1 2 3 4 5 6 7 8 9 10 11
#favorite_languages.py favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } print("The following languages have been mentioned:") for language inset(favorite_languages.values()): #为剔除重复项,可使用集合(set)。集合类似于列表,但每个元素都必须是独一无二的: print(language.title())
1 2 3 4
The following languages have been mentioned: Python C Ruby
#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)
1 2 3
You ordered a thick-crust pizza with the following toppings: mushrooms extra cheese
1 2 3 4 5 6 7 8 9 10 11
#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())
1 2 3 4 5 6 7 8 9 10 11
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
#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 + "!")
1 2 3 4
If you tell us who you are, we can personalize the messages you see. What is your first name? Eric
Hello, Eric!
获取数值输入int()函数
1 2 3 4 5 6 7 8
>>> 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进行比较
1 2 3 4 5
>>> age = input("How old are you? ") How old are you? 21 >>> age = int(age)#int()函数将字符串强制转换成数值 >>> age >= 18 True
#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.")
1 2
Enter a number, and I'll tell you if it's even or odd: 42 The number 42 is even.
#让用户自己选择是否需要继续 #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)
1 2 3 4 5 6 7 8 9
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
使用标志,改变标志控制循环
1 2 3 4 5 6 7 8 9 10
#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结束循环
1 2 3 4 5 6 7 8 9
#cities.py prompt = "\nPlease enter the name of a city you have visited:" prompt += "\n(Enter 'quit' when you are finished.) " whileTrue: city = input(prompt) if city == 'quit': break else: print("I'd love to go to " + city.title() + "!")
1 2 3 4 5 6 7 8
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结束本层循环,继续下一次循环
1 2 3 4 5 6 7
#counting.py current_number = 0 while current_number < 10: current_number += 1 if current_number % 2 == 0: continue print(current_number,end=' ')
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())
1 2 3 4 5 6 7
Verifying user: Candace Verifying user: Brian Verifying user: Alice The following users have been confirmed: Candace Brian Alice
#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 + ".")
1 2 3 4 5 6 7 8 9
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.
#pizza.py defmake_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')
1 2 3 4 5 6 7 8
Making a pizza with the following toppings: - pepperoni
Making a pizza with the following toppings: - mushrooms - green peppers - extra cheese
#person.py # -*- coding: UTF-8 -*- defbuild_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)
1
{'first': 'jimi', 'last': 'hendrix','age':27}
返回值搭配while循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#greet.py defget_formatted_name(first_name, last_name): """返回整洁的姓名""" full_name = first_name + ' ' + last_name return full_name.title() whileTrue: 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 + "!")
1 2 3 4 5 6 7 8
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
传递列表
向函数中传递列表
1 2 3 4 5 6 7 8 9
#greet_users.py # -*- coding: UTF-8 -*- defgreet_users(names): """向列表中的每一位用户发出简单的问候""" for name in names: msg = "Hello," + name.title() + "!" print(msg) usernames = ['hannah','ty','margot','敬请T期待'] greet_users(usernames)
#模拟打印每一个设计,直到没有未打印的设计为止 #打印每一个设计后,都将其移到列表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)
1 2 3 4 5 6 7 8
Printing model: dodecahedron Printing model: robot pendant Printing model: iphone case
The following models have been printed: dodecahedron robot pendant iphone case
#pizza.py # -*- coding: UTF-8 -*- defmake_pizza(size, *toppings): """概述要制作的比萨""" print("\nMaking a " + str(size) +"-inch pizza with the following toppings:") for topping in toppings: print("- " + topping)
#electric_car.py classCar(): """一次模拟汽车的简单尝试""" def__init__(self, make, model, year):#构造函数对类进行初始化 self.make = make self.model = model self.year = year self.odometer_reading = 0 defget_descriptive_name(self): long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() defread_odometer(self): print("This car has " + str(self.odometer_reading) + " miles on it.") defupdate_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") defincrement_odometer(self, miles): self.odometer_reading += miles deffill_gas_tank(self,size): print("This size of gas tank of the car is "+ str(size)) classElectricCar(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 defdescribe_battery(self): """打印一条描述电瓶容量的消息""" print("This car has a " + str(self.battery_size) + "-kWh battery.") #对父类的fill_gas_tank()方法进行重载 deffill_gas_tank(): """电动车没有油箱""" print("This car doesn't need a tank!")
#electric_car.py classCar(): """一次模拟汽车的简单尝试""" def__init__(self, make, model, year):#构造函数对类进行初始化 self.make = make self.model = model self.year = year self.odometer_reading = 0 defget_descriptive_name(self): long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() defread_odometer(self): print("This car has " + str(self.odometer_reading) + " miles on it.") defupdate_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") defincrement_odometer(self, miles): self.odometer_reading += miles deffill_gas_tank(self,size): print("This size of gas tank of the car is "+ str(size)) classBattery(): """一次模拟电动汽车电瓶的简单尝试""" def__init__(self, battery_size=70): """初始化电瓶的属性""" self.battery_size = battery_size defdescribe_battery(self): """打印一条描述电瓶容量的消息""" print("This car has a " + str(self.battery_size) + "-kWh battery.") defget_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) classElectricCar(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()
1 2 3
2016 Tesla Model S This car has a 70-kWh battery. This car can go approximately 240 miles on a full charge.
#car.py """一个可用于表示汽车的类""" classCar(): """一次模拟汽车的简单尝试""" def__init__(self, make, model, year): """初始化描述汽车的属性""" self.make = make self.model = model self.year = year self.odometer_reading = 0 defget_descriptive_name(self): """返回整洁的描述性名称""" long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() defread_odometer(self): """打印一条消息,指出汽车的里程""" print("This car has " + str(self.odometer_reading) + " miles on it.") defupdate_odometer(self, mileage): """ 将里程表读数设置为指定的值 拒绝将里程表往回拨 """ if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") defincrement_odometer(self, miles): """将里程表读数增加指定的量""" self.odometer_reading += miles
1 2 3 4 5 6
#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()
1 2
2016 Audi A4 This car has 23 miles on it.
从一个模块中导入多个类
from 模块名 import 类名,类名
1 2 3 4 5 6 7 8
#my_cars.py from electric_car import Car,ElectricCar
#remember_me.py import json username = input("What is your name? ") filename = 'username.json' withopen(filename, 'w') as f_obj: json.dump(username, f_obj) print("We'll remember you when you come back, " + username + "!")
1 2
What is your name? Eric We'll remember you when you come back, Eric!