目录
蟒蛇书答案,自己写的,可能有错,包含了基础部分第2章到第9章的内容
第二章和第三章:变量和简单数据类型、列表简介
#p18
a = "Hello python world!"
# print(a)
a = "again good luck!"
print(a)
#p23
Name = "Eric"
print("hello "+Name+",would you like to learn some Python today?")
print(Name.lower())
print(Name.upper())
print(Name.title())
#2-5&2-6
Famous_person = "Albert Einstein"
message = "A person who never made a mistake never tried anything new."
print(Famous_person.title()+" once said: "+message.title())
#2-7
person_name = "\tJ\n\tJ\nJ"
print(person_name)
person_name_a = ' J '
print(person_name_a.lstrip())
print(person_name_a.rstrip())
print(person_name_a.strip())
#####2-8#####
print(2+6)
print(10-2)
print(2*4)
print(int(16/2))
#####2-9#####
number = 1
message = "My favorite number is "+str(number)+"!"
print(message)#str:将非字符串转换为字符串
#####3-1&3-2#####
names = ['C','J','L','C']
for i in range(4):
print(names[i].title()+" How is your day?")
###3-3#####
tool = ['walk','bicycle']
print("I would like the "+tool[1].title()+' rather than '+tool[0].title())
#####3-4#####
name_list = ['A','B','C','D']
for i in range(4):
print(name_list[i]+", would you like to have dinner with me?")
#####3-5#####
name_list = ['A','B','C','D']
print('B cannot be here.')
name_list[1] = 'E'
for i in range(4):
print(name_list[i]+", would you like to have dinner with me?")
#####3-6#####
name_list = ['A','B','C','D']
print('B cannot be here.')
name_list[1] = 'E'
print('I have found a bigger place')
name_list.insert(0,'F')
name_list.insert(2,'G')
name_list.append('H')
for i in range(len(name_list)):
print(name_list[i]+", would you like to have dinner with me?")
#####3-7#####
name_list = ['A','B','C','D']
print('B cannot be here.')
name_list[1] = 'E'
print('I have found a bigger place')
name_list.insert(0,'F')
name_list.insert(2,'G')
name_list.append('H')
print("Only two")
for i in range(len(name_list)):
if i <5:
print("Sorry"+name_list.pop())
else:
print("Welcome" + name_list[i-5])
del name_list[0]
del name_list[0]
print(name_list)
######方法的调用是列表.方法();如果是函数,列表作为参数使用格式是:函数(列表),括号中都可以增加一些参数的说明比如reverse = True
#####3-8#####
place = ['Nuowei','Fenlan','England','Jiangnan','Haibian']
# print(place)
# print(sorted(place))
# print(sorted(place,reverse=True))
# print(place)
# place.reverse()
# print(place)
# place.reverse()
# print(place)
place.sort()
print(place)
place.sort(reverse=True)
print(place)
######3-9######
name_list = ['A','B','C','D']
print('B cannot be here.')
name_list[1] = 'E'
print('I have found a bigger place')
name_list.insert(0,'F')
name_list.insert(2,'G')
name_list.append('H')
print(len(name_list))
######3-11######
place = ['Nuowei','Fenlan','England','Jiangnan','Haibian']
print(place[4])
第四章:操作列表
######4-1######
pizzas = ['vegetable','fruit','french fries','liulian']
for pizza in pizzas:
print(pizza)
pizzas = ['vegetable','fruit','french fries','liulian']
for pizza in pizzas:
print('I like '+pizza+' pizza!')
pizzas = ['vegetable','fruit','french fries','liulian']
for pizza in pizzas:
print('I like '+pizza+' pizza!')
print('I really love pizza!')
######4-3######
for number in range(1,21):
print(number)
######4-4######
numbers = list(range(1,1000001))
for number in numbers:
print(number)
######4-5######
numbers = list(range(1,1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
######4-6######
numbers = list(range(1,21,2))
for number in numbers:
print(number)
######4-7######
numbers = []
for value in range(1,11):
number = value*3
numbers.append(number)
print(numbers)
######4-8######
numbers = []
for value in range(1,11):
number = value**3
numbers.append(number)
print(number)
print(numbers)
######4-9######
numbers=[number**3 for number in range(1,11)]
print(numbers)
######4-10######
numbers=list(range(1,11))
print('The original list is:')
print(numbers)
print('The first three items in the list are:')
print(numbers[0:3])
print('Three items from the middle of the list are:')
print(numbers[3:6])
print('The last three items in the list are:')
print(numbers[-3:])
#####4-11#####
pizzas = ['vegetable','fruit','french fries','liulian']
friend_pizzas = pizzas[:]
pizzas.append('cake')
friend_pizzas.append('candy')
print('My favorite pizzas are:')
for pizza in pizzas:
print(pizza)
print("My friend's favorite pizzas are:")
for friend_pizza in friend_pizzas:
print(friend_pizza)
#####4-12#####
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
for my_food in my_foods:
print('Me:'+my_food)
for friend_food in friend_foods:
print("My friend's: " + friend_food)
#####4-13#####
foods = ('apple','pear','soup','noodle','dessert')
for food in foods:
print(food)
foods[0] = ['juice']
foods = ('juice','coffee','soup','noodle','dessert')
for food in foods:
print(food)
第五章:if语句
#####5-1#####
food = 'apple'
print('Is fruit == apple? I predict True.')
print(food == 'apple')
print('\nIs fruit == pear? I predict False.')
print(food == 'pear')
food = 'orange'
print('Is fruit == orange? I predict True.')
print(food == 'orange')
print('\nIs fruit == pear? I predict False.')
print(food == 'pear')
food = 'strawberry'
print('Is fruit == strawberry? I predict True.')
print(food == 'strawberry')
print('\nIs fruit == pear? I predict False.')
print(food == 'pear')
food = 'banana'
print('Is fruit == banana? I predict True.')
print(food == 'banana')
print('\nIs fruit == pear? I predict False.')
print(food == 'pear')
food = 'pineapple'
print('Is fruit == pineapple? I predict True.')
print(food == 'pineapple')
print('\nIs fruit == pear? I predict False.')
print(food == 'pear')
#####5-2#####
character = 'Good luck'
if character != 'lucky':
print('Lucky is not the character')
else:
print('Lucky is the original character')
food = 'Soup'
print(food == 'soup')
print(food.lower() == 'soup')
number = 55
print(number == 55)
print(number == 67)
print(number > 67)
print(number < 67)
print(number >= 80)
print(number <= 80)
number_1 = 67
number_2 = 98
print(number_1>20 and number_2<100)
print(number_1<20 or number_2>100)
numbers = [13,35,46,68,79,80,98]
print(24 in numbers)
print(98 not in numbers)
#####5-3#####
alien_color = ['green','yellow','red']
color = 'yellow'
if color == 'green':
print("You get 5 points!")
else:
color = 'green'
#####5-4#####
alien_color = ['green','yellow','red']
color = 'yellow'
if color == 'green':
print("You get 5 points!")
else:
print("You get 10 points!")
if color == 'green':
print("You get 5 points!")
if color != 'green':
print("You get 10 points!")
#####5-5#####
alien_color = ['green','yellow','purple']
color = 'purple'
if color == 'green':
print("You get 5 points!")
elif color == 'yellow':
print("You get 10 points!")
else:
print("You get 15 points!")
if color == 'green':
print("You get 5 points!")
if color == 'yellow':
print("You get 10 points!")
if color == 'purple':
print('You get 15 points!')
#####5-6#####
age = 1
if age < 2:
print('You are a baby')
elif age>=2 and age<4:
print("You're a toddler")
elif age>=4 and age<13:
print("You are a child")
elif age>=13 and age<20:
print("You are a teenager")
elif age >= 20 and age < 65:
print("You are an adult")
else:
print("You are an older")
#####5-7#####
favorite_fruits = ['apple','orange','banana']
if 'grape' in favorite_fruits:
a =1
if 'banana' in favorite_fruits:
print('You really like bnanas!')
if 'pineapple' in favorite_fruits:
a =1
if 'strawberry' in favorite_fruits:
a =1
if 'lemon' in favorite_fruits:
a =1
#####5-8#####
names = ['Admin','Eric','Tom','Lisa','Jenny']
for name in names:
if name == 'Admin':
print('Hello, '+name+', would you like to see a status report')
else:
print('Hello '+name+', thank you for logging in again')
#####5-9#####
names = ['Admin','Eric','Tom','Lisa','Jenny']
names = []
if names :
for name in names:
if name == 'Admin':
print('Hello, '+name+', would you like to see a status report')
else:
print('Hello '+name+', thank you for logging in again')
else:
print('We need to find some users!')
#####5-10#####
current_users = ['Admin','Eric','Tom','Lisa','Jenny']
new_users = ['Admin','ERIC','Linda','Jack','John']
for new_user in new_users:
is_duplicate = False # 初始化状态为不重复
for current_user in current_users:
if new_user.lower() == current_user.lower():
is_duplicate = True # 如果找到相同用户名,更新状态为重复
break
if is_duplicate:
print(new_user + ' You need to input another name.')
else:
print(new_user + ' is OK.')
#####5-11#####
numbers = [1,2,3,4,5,6,7,8,9]
for number in numbers:
if number == 1:
print(str(number)+'st')
elif number == 2:
print(str(number)+'nd')
elif number == 3:
print(str(number)+'rd')
else:
print(str(number)+'th')
第六章:字典
#####6-1#####
acquaintance = {'first_name':'a','last_name':'B','age':'87','city':'C'}
print(acquaintance['last_name'])
print(acquaintance['first_name'])
print(acquaintance['age'])
print(acquaintance['city'])
#####6-2#####
like_number = {'A':'1','B':'2','C':'3','D':'4','E':'5'}
print(like_number['A'])
print(like_number['B'])
print(like_number['C'])
print(like_number['D'])
print(like_number['E'])
#####6-3#####
code = {'for':'一种循环','if':'条件假设','and':'与运算','or':'或运算','==':'判断是否相等'}
print('for if and or ==')
print(code['for'],code['if'],code['and'],code['or'],code['=='])
#####6-4#####
code = {'for':'一种循环','if':'条件假设','and':'与运算','or':'或运算','==':'判断是否相等','!=':'不等于','tensor':'创建张量','plt.show()':'绘制图像','x.label':'给x轴起坐标轴的名字','y.label':'给y轴起坐标轴的名字'}
for n,w in code.items():
print('\nName:'+ n)
print('\nWork:'+ w)
#####6-5#####
River_Country = {'nile':'egypt','Changjiang':'China','Yellow River':'China','nile':'egypt'}
for r,c in River_Country.items():
print('The '+ r +' runs through '+c)
for r in River_Country.keys():
print(r.title())
for c in River_Country.values():
print(c.title())
#####6-6#####
favorite_languages = {'jen':'Python','sarah':'c','edward':'ruby','phil':'python'}
for name in favorite_languages.keys():
list = ['jen','edward']
if name in list:
print(name+', thank you for taking the poll.')
else:
print(name+', please take the poll!')
#####6-7#####
acquaintance_1 = {'first_name':'a','last_name':'B','age':'87','city':'C'}
acquaintance_2 = {'first_name':'d','last_name':'E','age':'88','city':'F'}
acquaintance_3 = {'first_name':'g','last_name':'H','age':'89','city':'I'}
acquaintances = [acquaintance_1,acquaintance_2,acquaintance_3]
for ac in acquaintances:
print(ac)
#####6-8#####
dog = {'Hashiqi':'John'}
cat = {'Buou':'Mike'}
fish = {'Gold':'Linda'}
pets = [dog,cat,fish]
for pet in pets:
print(pet)
#####6-9#####
favorite_places = {'Linda':'A,B,C','Mike':'D,E,F','Jack':'G,H,I'}
for name,place in favorite_places.items():
print('\n'+name+' likes '+place)
#####6-10#####
like_number = {'A':'1','B':'2','C':'3','D':'4','E':'5'}
like_number['A'] = ['1,2,3,4']
like_number['B'] = ['5,6,7,8']
like_number['C'] = ['9,10,11,12']
like_number['D'] = ['13,14,15,16']
like_number['E'] = ['17,18,19,20']
for name,numbers in like_number.items():
print(name+"'s favorite number are:")
for number in numbers:
print("\t"+number)
#####6-11#####
cities = {'CityA':{'Country':'A','population':'B','fact':'C'},'CityD':{'Country':'E','population':'F','fact':'G'},'CityH':{'Country':'I','population':'J','fact':'K'}}
for city,infos in cities.items():
print("City's name:"+city)
country = infos['Country']
population = infos['population']
fact = infos['fact']
print('Country: ' + country)
print('Population: ' + population)
print('Fats: ' + fact)
第七章:用户输入和while循环
#####7-1#####
car = input('What kind of car do you like?')
print('Let me see if I can find you a '+ car +'~')
#####7-2#####
guests = input('How many people are dinning?:')
guests = int(guests)
if guests<8:
print("Luckily,there are empty positions~")
else:
print("Sorry,our restaurant is full")
#####7-3#####
number = input("Please input a number:")
number = int(number)
if number%10 == 0:
print('The number is a multiple of 10~')
else:
print('The number is not a multiple of 10')
#####7-4#####
prompt = "What toppings do you like on your pizza?:"
prompt += "\nEnter 'quit' to end the program."
topping = ""
while topping != 'quit':
topping = input(prompt)
if topping !='quit':
print('We will add '+topping)
#####7-5#####
ask = "What is your age?"
ask += "\nEnter 'quit' to end the program."
age = ""
active = True
while active:
age = input(ask)
if age == 'quit':
active = False
else:
age = int(age)
if age<3:
print("Your ticket is free")
elif age>=3 and age<12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
#####7-6#####
##7-4改写##
prompt = "What toppings do you like on your pizza?:"
prompt += "\nEnter 'quit' to end the program."
topping = ""
while True:
topping = input(prompt)
if topping =='quit':
break
else:
print('We will add '+topping)
##7-5改写##
ask = "What is your age?"
ask += "\nEnter 'quit' to end the program."
age = ""
while True:
age = input(ask)
if age == 'quit':
break
else:
age = int(age)
if age<3:
print("Your ticket is free")
elif age>=3 and age<12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
#####7-7#####
while True:
print("Keep on going!Trust yourself!")
#####7-8#####
sandwich_orders = ['fruit','egg','chicken']
finished_sandwiches = []
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print("I made your "+current_sandwich+" sandwich~")
finished_sandwiches.append(current_sandwich)
print("\nThe following sandwiches have been finished:")
for finished_sandwich in finished_sandwiches:
print(finished_sandwich.title())
#####7-9#####
sandwich_orders = ['fruit','pastrami','egg','pastrami','chicken','pastrami']
print("We have ",sandwich_orders)
#这里要注意字符串拼接错误,字符串如果要和列表拼接,需要写成print("We have " + str(sandwich_orders))
#或者是print("We have", sandwich_orders)
print("But now we have run out of pastrami TAT")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print(sandwich_orders)
#####7-10#####
places = {}
active = True
while active:
name = input("What is your name?")
place = input("If you could visit one place in the world, where would you go?")
places[name] = place
repeat = input("Wouuld you like to let another person respond?(yes/no)")
if repeat == 'no':
active = False
print('\n--- Poll Results ---')
for n,p in places.items():
print(n+" would like to go to "+p)
第八章:函数
#####8-1#####
def display_message():
"""打印本章学习的内容"""
print("学习函数")
display_message()
#####8-2#####
def favorite_book(Book_name):
print("One of my favorite books is "+Book_name.title())
favorite_book('alice in wonderland')
#####8-3####
def make_shirt(size,characters):
print("This T-shirt's size is "+ size)
print("\nWith "+ characters.upper() +' on it.')
make_shirt(size="M",characters="GOOD LUCK")#关键字实参
make_shirt("M","GOOD LUCK")#位置实参
#####8-4####
def make_shirt(size = "L",characters = "I Love Python"):
print("This T-shirt's size is "+ size)
print("With "+ characters.upper() +' on it.\n')
make_shirt()
make_shirt(size="M")
make_shirt(characters="GOOD LUCK")
#####8-5####
def describe_city(name,country = "A"):
print(name.title()+" is in "+country)
describe_city(name = "B")
describe_city(name = "C",country="D")
describe_city(name="E", country="F")
#####8-6####
def city_country(city,country):
full = city+","+country
return full.title()
Full = city_country('santiago','chile')
print(Full)
#####8-7####
def make_album(singer,album,number =""):
infor = {'singer':singer,'album':album}
if number:
infor['number'] = number
return infor
music = make_album('Jack','Long Time')
print(music)
music = make_album('Jack','Short Time',3)
print(music)
music = make_album('Jack','No Time',1)
print(music)
#字典添加值,字典名称['键名'] = 值,是数值不用加引号,是字符需要添加引号
#对于可选择的参数,如果想要在最后的结果中不显示,可以在形参时设置为""但是两个引号之间不要加负号,否则不管给不给number赋值,都会在结果中被打印出来
#####8-8####
#定义函数
def make_album(singer,album,number =""):
infor = {'singer':singer,'album':album}
if number:
infor['number'] = number
return infor
#while循环
while True:
print("Please input your favorite singer and album:")
print("(enter 'q' at any time to quit)")
singer = input("The singer:")
if singer == 'q':
break
album = input("The album:")
if album == 'q':
break
prefer = make_album(singer,album)#作为形参名称传递时,不需要添加引号;作为形参内容传递时,添加上引号
print("Here is your favorite singer and album: "+ str(prefer))
#不可以将字符串和字典类型进行直接的拼接,需要将字典转换为字符串
#也就是说,只有相同类型的数据才可以进行直接拼接,不同类型的数据需要进行类型转换,转换成相同类型才可以拼接
#需要注意的是,不是所有的类型都可以转换为字符串类型,如果尝试将不可转换为字符串类型的数据使用 str() 进行转换,会抛出 TypeError 异常。
#####8-9#####
def show_magicians(names):
"""打印出每个魔术师的名字"""
for name in names:
print("Hey,your name is "+ name)
magicians = ["Linda","Max","Caroline"]
show_magicians(magicians)
#####8-10#####
def show_magicians(original_names,modi_names):
"""打印出每个魔术师的名字"""
while original_names:
current_name = original_names.pop()
print("Hey "+ current_name)
modi_names.append(current_name)
def add_The_Great(modi_names):
"""为每个魔术师名字增加The Great"""
modified_names = []
while modi_names:
current_name = modi_names.pop()
modified_names.append("The Great: " + current_name)
print(modified_names)
original_names = ["Linda","Max","Caroline"]
modi_names = []
show_magicians(original_names,modi_names)
add_The_Great(modi_names)
#####8-11#####
def make_great(magicians):
for i in range(len(magicians)):
magicians[i] = "the Great " + magicians[i]
return magicians
def show_magicians(magicians):
for magician in magicians:
print(magician)
magicians = ["David Copperfield", "Criss Angel", "David Blaine"]
great_magicians = make_great(magicians[:])
show_magicians(great_magicians)
show_magicians(magicians)#调用副本,原列表没有发生改变
great_magicians = make_great(magicians)
show_magicians(great_magicians)
show_magicians(magicians)#调用原来的列表,列表发生了改变
#####8-12#####
def make_sandwiches(*toppings):
"""概述要制作的三明治食材"""
print('\nMaking a sandwich with the following toppings: ')
for topping in toppings:
print('-'+topping)
make_sandwiches('chicken','egg','vegetables','bread')
#####8-13#####
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
build_profile('AE','V',location = 'pricton',field = 'physics',prefer = 'swimming')
#如果键是字符串,可以使用单引号或者双引号括起来
#如果键是数字,则不需要括起来
#如果键是变量,使用不带引号的变量名
# 在这里,键由user_info参数传入的字符串类型,所以在代码中使用方括号表示法来表示键名,不用括号括起来
#####8-14#####
def car_info(productor,model,**car_info):
"""创建一个新的字典,包含汽车的一些信息"""
profile = {}
profile['productor'] = productor
profile['model'] = model
for key,value in car_info.items():
profile[key] = value
return profile
info = car_info('subaru','outback',color = 'blue',tow_package = True)
print(info)
#####8-15#####printing_functions.py
#因为没有找到print_models的代码,所以沿用了上一题代码
def car_info(productor,model,**car_info):
"""创建一个新的字典,包含汽车的一些信息"""
profile = {}
profile['productor'] = productor
profile['model'] = model
for key,value in car_info.items():
profile[key] = value
return profile
#####8-15#####print_models.py
from printing_functions import car_info
info = car_info('Audi','L6',color = 'black',tow_package = True)
print(info)
#####8-16#####print_models.py
import printing_functions
info = printing_functions.car_info('Audi','L6',color = 'black',tow_package = True)
print(info)
from printing_functions import car_info
info = car_info('Audi','L6',color = 'black',tow_package = True)
print(info)
from printing_functions import car_info as ci
info = ci('Audi','L6',color = 'black',tow_package = True)
print(info)
import printing_functions as p
info = p.car_info('Audi','L6',color = 'black',tow_package = True)
print(info)
from printing_functions import *
info = car_info('Audi','L6',color = 'black',tow_package = True)
print(info)
第九章:类
#####9-1#####
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
"""初始化属性restaurant_name和cuisine_type"""
self.restaurant_name = restaurant_name#获取存储在形参name中的值,并将其存储到变量name中,然后该变量被关联到当前创建的实例
self.cuisine_type = cuisine_type
def describe_reataurant(self):
"""打印属性信息"""
print("Our reataurant's name is "+ self.restaurant_name.title() + ' .')
print("Our restaurant's type is "+ self.cuisine_type.upper() + ' .')
def open_restaurant(self):
"""指出餐厅正常营业"""
print("We are opening now! Welcome~")
restaurant = Restaurant('GOOD','bbq')
restaurant.describe_reataurant()
restaurant.open_restaurant()
#####9-2#####
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
"""初始化属性restaurant_name和cuisine_type"""
self.restaurant_name = restaurant_name#获取存储在形参name中的值,并将其存储到变量name中,然后该变量被关联到当前创建的实例
self.cuisine_type = cuisine_type
def describe_reataurant(self):
"""打印属性信息"""
print("Our reataurant's name is "+ self.restaurant_name.title() + ' .')
print("Our restaurant's type is "+ self.cuisine_type.upper() + ' .')
def open_restaurant(self):
"""指出餐厅正常营业"""
print("We are opening now! Welcome~")
restaurant_a = Restaurant('GOOD','bbq')#根据类创建实例
restaurant_a.describe_reataurant()#调用方法
restaurant_b = Restaurant('LUCK','hot pot')
restaurant_b.describe_reataurant()
restaurant_c = Restaurant('Work hard','noodle')
restaurant_c.describe_reataurant()
#####9-3#####
class User():
def __init__(self,first_name,last_name,gender,birthday):
"""初始化属性"""
self.first_name = first_name#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
self.last_name = last_name#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
self.gender = gender
self.birthday = birthday
def describe_user(self):
"""打印属性信息"""
print("first_name: "+ self.first_name.title())
print("last_name: "+ self.last_name.title())
print("gender: "+ self.gender.title())
print("birthday: "+ self.birthday.title())
def greet_user(self):
"""发出个性化问候"""
print("Dear "+self.first_name+" "+self.last_name+" Nice to meet you~")
user_a = User('Jack','Black','m','3.2')#仅仅创建实例是不会打印结果的,要调用方法
user_a.describe_user()
user_a.greet_user()
user_b = User('Linde','Wanda','f','9.7')
user_b.describe_user()
user_b.greet_user()
#####9-4#####
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
"""初始化属性restaurant_name和cuisine_type"""
self.restaurant_name = restaurant_name#获取存储在形参name中的值,并将其存储到变量name中,然后该变量被关联到当前创建的实例
self.cuisine_type = cuisine_type
self.number_served = 6
def describe_reataurant(self):
"""打印属性信息"""
print("Our reataurant's name is "+ self.restaurant_name.title() + ' .')
print("Our restaurant's type is "+ self.cuisine_type.upper() + ' .')
def open_restaurant(self):
"""指出餐厅正常营业"""
print("We are opening now! Welcome~")
def set_number_served(self,numbers):
"""设置就餐人数"""
self.number_served = numbers
def increment_number_served(self,incre):
"""将就餐人数进行递增"""
self.number_served += incre
def number_of_diners(self):
"""打印出有多少人就餐"""
print("Here are "+str(self.number_served)+" guests~")
restaurant = Restaurant('GOOD','bbq')
restaurant.describe_reataurant()
restaurant.open_restaurant()
restaurant.set_number_served(30)
restaurant.number_of_diners()
restaurant.increment_number_served(10)
restaurant.number_of_diners()
#####9-5#####
class User():
def __init__(self,first_name,last_name,gender,birthday):
"""初始化属性"""
self.first_name = first_name#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
self.last_name = last_name#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
self.gender = gender
self.birthday = birthday
self.login_attempts = 0
def describe_user(self):
"""打印属性信息"""
print("first_name: "+ self.first_name.title())
print("last_name: "+ self.last_name.title())
print("gender: "+ self.gender.title())
print("birthday: "+ self.birthday.title())
def greet_user(self):
"""发出个性化问候"""
print("Dear "+self.first_name+" "+self.last_name+" Nice to meet you~")
def increment_login_attempts(self):
"""login_attempts值增加1"""
self.login_attempts += 1
return self.login_attempts
def reset__login_attempts(self):
"""将属性login_attempts清0"""
self.login_attempts = 0
return self.login_attempts
user_a = User('Jack','Black','m','3.2')#仅仅创建实例是不会打印结果的,要调用方法
user_a.describe_user()
user_a.greet_user()
num = user_a.increment_login_attempts()
print(num)
num = user_a.increment_login_attempts()
print(num)
num = user_a.increment_login_attempts()
print(num)
num = user_a.reset__login_attempts()
print(num)
#####9-6#####
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
"""初始化属性restaurant_name和cuisine_type"""
self.restaurant_name = restaurant_name#获取存储在形参name中的值,并将其存储到变量name中,然后该变量被关联到当前创建的实例
self.cuisine_type = cuisine_type
def describe_reataurant(self):
"""打印属性信息"""
print("Our reataurant's name is "+ self.restaurant_name.title() + ' .')
print("Our restaurant's type is "+ self.cuisine_type.upper() + ' .')
def open_restaurant(self):
"""指出餐厅正常营业"""
print("We are opening now! Welcome~")
class IceCreamStand(Restaurant):#括号里不要忘记指定父类
"""继承自Restaurant类的IceCreamStand类"""
def __init__(self,restaurant_name,cuisine_type):
super().__init__(restaurant_name,cuisine_type)
self.flavors = []
def describe_flavor(self):
"""显示冰淇淋口味列表"""
print("We have the following flavors:")
for flavor in self.flavors:
print("-"+flavor)
my_ice_cream = IceCreamStand("Ice Cream Palace","Ice Cream")
my_ice_cream.flavors = ["Chocolate","Vanilla","Strawberry"]
my_ice_cream.describe_flavor()
#####9-7#####
class User():
def __init__(self,first_name,last_name,gender,birthday):
"""初始化属性"""
self.first_name = first_name#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
self.last_name = last_name#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
self.gender = gender
self.birthday = birthday
def describe_user(self):
"""打印属性信息"""
print("first_name: "+ self.first_name.title())
print("last_name: "+ self.last_name.title())
print("gender: "+ self.gender.title())
print("birthday: "+ self.birthday.title())
def greet_user(self):
"""发出个性化问候"""
print("Dear "+self.first_name+" "+self.last_name+" Nice to meet you~")
class Admin(User):
"""继承自User类的Admin类"""
def __init__(self,first_name,last_name,gender,birthday):
super().__init__(first_name,last_name,gender,birthday)
self.privileges = []
def show_privileges(self):
print("An admin can:")
for privilege in self.privileges:
print("-"+privilege)
admin = Admin('Jack','White','m','3.4')
admin.privileges = ['can add post','can delete post','can ban user']
admin.show_privileges()
#####9-8#####
class User():
def __init__(self,first_name,last_name,gender,birthday):
"""初始化属性"""
self.first_name = first_name#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
self.last_name = last_name#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
self.gender = gender
self.birthday = birthday
def describe_user(self):
"""打印属性信息"""
print("first_name: "+ self.first_name.title())
print("last_name: "+ self.last_name.title())
print("gender: "+ self.gender.title())
print("birthday: "+ self.birthday.title())
def greet_user(self):
"""发出个性化问候"""
print("Dear "+self.first_name+" "+self.last_name+" Nice to meet you~")
class Privileges():
def __init__(self):
self.privileges = ["can add post", "can delete post", "can ban user"]
def show_privileges(self):
print("An admin can:")
for privilege in self.privileges:
print("-"+privilege)
class Admin(User):
"""继承自User类的Admin类"""
def __init__(self,first_name,last_name,gender,birthday):
super().__init__(first_name,last_name,gender,birthday)
self.privileges = Privileges()#创建一个Privileges实例
#在这里,使用self.privileges 属性来存储一个 Privileges 类的实例对象。
# Admin 类需要使用 Privileges 类中的属性和方法,而 Privileges 类的实例可以作为 Admin 类的属性来实现这一点
#将 self.privileges 初始化为 Privileges()
# 会在 Admin 类的每个实例创建时创建一个新的 Privileges 实例。
# 这样,每个 Admin 实例都会拥有自己的 Privileges 实例,而不是共享同一个实例。
# 这有助于防止多个 Admin 实例之间相互干扰,并使代码更加模块化和易于维护。
#因此,在这里使用实例来创建 self.privileges 属性
# 是为了创建一个独立的 Privileges 实例,而不是仅仅将一个值分配给属性。
#虽然在 self.privileges = Privileges() 这句话中没有传递任何参数,但是在 Privileges 类中的 #__init__ 方法中定义了一个默认的 privileges 属性
#所以在创建 Privileges 实例时,会自动使用这个默认属性。
#因此,self.privileges = Privileges() 这句话中实际上是创建了一个 Privileges 类的实例
#并将其存储在 Admin 类的 self.privileges 属性中。
def show_privileges(self):
self.privileges.show_privileges()
admin = Admin('Linda','Red','f','1990-01-01')
admin.show_privileges()
#####9-9#####
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
"""初始化属性"""
self.make = make#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
self.model = model#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
self.year = year
self.odometer_reading = 0#在_init_中对属性设置了初始值之后,就无需包含为他提供初始值的形参
def get_describe_name(self):
"""返回整洁的描述性信息"""
long_name = str(self.year)+" "+self.make+' '+self.model
return long_name.title()
def update_odometer(self,mileage):#修改属性值方法2:通过方法修改属性值
"""将里程表设置为固定的值
禁止将里程表往回调"""
if mileage>self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):#修改属性值方法3:通过方法对属性值进行递增
"""将里程表读数增加指定的量"""
self.odometer_reading += miles
def read_odometer(self):
"""打印一条指出汽车里程的信息"""
print("This car has "+str(self.odometer_reading)+" miles on it.")
class Battery():#这里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)
def upgrade_battery(self):
if self.battery_size<=85:
self.battery_size = 85
class ElectriCar(Car):
"""电动汽车独特之处"""
def __init__(self,make,model,year):
"""初始化父类特征,再初始化电动汽车特有属性"""
super().__init__(make,model,year)
self.battery = Battery()#注意缩进
my_electric_car = ElectriCar('Tesla', 'Model S', 2022)
my_electric_car.get_describe_name()
my_electric_car.battery.get_range()
my_electric_car.battery.upgrade_battery()
my_electric_car.battery.get_range()
#这里使用battery而不是Battery是因为:battery 是 ElectricCar 类的一个属性
# 这个属性引用了 Battery 类的一个实例。因为在 ElectricCar 的 __init__ 方法中
# 我们创建了一个名为 battery 的 Battery 实例并将其赋值给了 self.battery 属性。
# 所以 my_electric_car.battery 表示 my_electric_car 实例中的 battery 属性
# 这个属性引用了一个 Battery 类的实例。
#####9-10#####
#创建实例,Exer.py
from restaurant import Restaurant
info = Restaurant('SO hot','hot pot')
info.describe_reataurant()
info.open_restaurant()
#类,restaurant.py
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
"""初始化属性restaurant_name和cuisine_type"""
self.restaurant_name = restaurant_name#获取存储在形参name中的值,并将其存储到变量name中,然后该变量被关联到当前创建的实例
self.cuisine_type = cuisine_type
def describe_reataurant(self):
"""打印属性信息"""
print("Our reataurant's name is "+ self.restaurant_name.title() + ' .')
print("Our restaurant's type is "+ self.cuisine_type.upper() + ' .')
def open_restaurant(self):
"""指出餐厅正常营业"""
print("We are opening now! Welcome~")
#####9-11#####
#创建实例,Exer.py
from Admin_info import Admin
admin = Admin('Linda','White','f','1990-01-01')
admin.show_privileges()
#类,Admin_info.py
class User():
def __init__(self,first_name,last_name,gender,birthday):
"""初始化属性"""
self.first_name = first_name#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
self.last_name = last_name#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
self.gender = gender
self.birthday = birthday
def describe_user(self):
"""打印属性信息"""
print("first_name: "+ self.first_name.title())
print("last_name: "+ self.last_name.title())
print("gender: "+ self.gender.title())
print("birthday: "+ self.birthday.title())
def greet_user(self):
"""发出个性化问候"""
print("Dear "+self.first_name+" "+self.last_name+" Nice to meet you~")
class Privileges():
def __init__(self):
self.privileges = ["can add post", "can delete post", "can ban user"]
def show_privileges(self):
print("An admin can:")
for privilege in self.privileges:
print("-"+privilege)
class Admin(User):
"""继承自User类的Admin类"""
def __init__(self,first_name,last_name,gender,birthday):
super().__init__(first_name,last_name,gender,birthday)
self.privileges = Privileges()#创建一个Privileges实例
def show_privileges(self):
self.privileges.show_privileges()
#####9-12#####
#创建实例,Exercise.py
from User_b import Admin
admin = Admin('Linda','White','f','1990-01-01')
admin.show_privileges()
#存放User类的模块 User_a.py
class User():
def __init__(self,first_name,last_name,gender,birthday):
"""初始化属性"""
self.first_name = first_name#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
self.last_name = last_name#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
self.gender = gender
self.birthday = birthday
def describe_user(self):
"""打印属性信息"""
print("first_name: "+ self.first_name.title())
print("last_name: "+ self.last_name.title())
print("gender: "+ self.gender.title())
print("birthday: "+ self.birthday.title())
def greet_user(self):
"""发出个性化问候"""
print("Dear "+self.first_name+" "+self.last_name+" Nice to meet you~")
#存放Privileges和Admin类的模块,User_b.py
from User_a import User
class Privileges():
def __init__(self):
self.privileges = ["can add post", "can delete post", "can ban user"]
def show_privileges(self):
print("An admin can:")
for privilege in self.privileges:
print("-"+privilege)
class Admin(User):
"""继承自User类的Admin类"""
def __init__(self,first_name,last_name,gender,birthday):
super().__init__(first_name,last_name,gender,birthday)
self.privileges = Privileges()#创建一个Privileges实例
def show_privileges(self):
self.privileges.show_privileges()
#####9-13#####
from collections import OrderedDict
code = OrderedDict()
code['for'] = '一种循环'
code['if'] = '条件假设'
code['and'] = '与运算'
code['or'] = '或运算'
code['=='] = '判断是否相等'
for n,w in code.items():
print('\nName:'+ n)
print('\nWork:'+ w)
#####9-14#####
from random import randint
class Die():
def __init__(self,sides = 6):#后期对属性值需要进行更改,这里使用通过方法修改
# 属性值的措施,所以会在初始化中加上sides,这样也有利于后期实例化的时候直接存放数值
self.sides = sides
def roll_die(self):
x = randint(1,self.sides)
print(x)
#创建一个6面的骰子,并掷10次
die6 = Die()
for i in range(10):
die6.roll_die()
# 创建一个 10 面的骰子,并掷 10 次
die10 = Die(10)
for i in range(10):
die10.roll_die()
# 创建一个 20 面的骰子,并掷 10 次
die20 = Die(20)
for i in range(20):
die20.roll_die()