defdisplay_message():print("I am study some knowledge of function in python.")
display_message()
I am study some knowledge of function in python.
8.2
deffavourite_book(title):print(f"One of my favourite books is {title}.")
favourite_book('The story of the stone')
One of my favourite books is The story of the stone.
8.3
defmake_shirt(size,word):print(f"The shirt's size is {size}, and the words on it is {word}.")
make_shirt(8,6)
The shirt's size is 8, and the words on it is 6.
8.4
defmake_shirt(size='large',word='I love python'):# if (size == None) and (word == None):# print(f"The shirt's size is large, and the words on it is 'I love python'.")# elif word == None:# print(f"The shirt's size is {size}, and the words on it is 'I love python'.")# else:print(f"The shirt's size is {size}, and the words on it is {word}.")
make_shirt()
make_shirt('medium')
make_shirt(8,6)
The shirt's size is large, and the words on it is I love python.
The shirt's size is medium, and the words on it is I love python.
The shirt's size is 8, and the words on it is 6.
8.5
defdescribe_city(city_name,country='China'):print(f"{city_name} is in {country}")
describe_city('shenzhen')
describe_city('Otaru','Japan')
describe_city('PuSan','Korea')
shenzhen is in China
Otaru is in Japan
PuSan is in Korea
defmake_album(singer,album):
information ={'singer':singer,'album':album}return information
make_album('WuQingFeng','Tomorrow will be fine')
{'singer': 'WuQingFeng', 'album': 'Tomorrow will be fine'}
defmake_album(singer,album,song_number=None):if song_number:
information ={'singer':singer,'album':album,'song_number':{song_number}}else:
information ={'singer':singer,'album':album}return information
print(make_album('WuQingFeng','Tomorrow will be fine'))print(make_album('WuQingFeng','altum','5'))
{'singer': 'WuQingFeng', 'album': 'Tomorrow will be fine'}
{'singer': 'WuQingFeng', 'album': 'altum', 'song_number': {'5'}}
8.8
defmake_album(singer,album,song_number=None):if song_number:
information ={'singer_name':singer,'album_name':album,'song_number':{song_number}}else:
information ={'singer_name':singer,'album_name':album}return information
whileTrue:
singer ='Please input the name of the singer: '
singer +='\n You can input \'q\' to quit this program.'
album ='Please input the name of the album: '
album +='\n You can input \'q\' to quit this program.'
singer_name =input(singer)if singer_name =='q':break
album_name =input(album)if album_name =='q':break
output = make_album(singer_name,album_name)print(output)# print(make_album('WuQingFeng','Tomorrow will be fine'))# print(make_album('WuQingFeng','altum','5'))
Please input the name of the singer:
You can input 'q' to quit this program.wuqingfeng
Please input the name of the album:
You can input 'q' to quit this program.autumn
{'singer_name': 'wuqingfeng', 'album_name': 'autumn'}
Please input the name of the singer:
You can input 'q' to quit this program.q
8.9
messages =['Life is like a box of chocolate.','To be or not to be, that is a question.','nothing is impossible']defshow_messages(note):for message in messages:print(message)
show_messages(messages)
Life is like a box of chocolate.
To be or not to be, that is a question.
nothing is impossible
8.10
messages =['Life is like a box of chocolate.','To be or not to be, that is a question.','nothing is impossible']
sent_messages =[]defsend_messages(note):print(f"messages:\n{messages}")while note:
popped_message = note.pop()
sent_messages.append(popped_message)
send_messages(messages)print(f"messages:\n{messages}")print(f"sent_messages:\n{sent_messages}")
messages:
['Life is like a box of chocolate.', 'To be or not to be, that is a question.', 'nothing is impossible']
messages:
[]
sent_messages:
['nothing is impossible', 'To be or not to be, that is a question.', 'Life is like a box of chocolate.']
8.11
messages =['Life is like a box of chocolate.','To be or not to be, that is a question.','nothing is impossible']
sent_messages =[]defsend_messages(note):print(f"messages:\n{note}")while note:
popped_message = note.pop()
sent_messages.append(popped_message)
send_messages(messages[:])print(f"messages:\n{messages}")print(f"sent_messages:\n{sent_messages}")
messages:
['Life is like a box of chocolate.', 'To be or not to be, that is a question.', 'nothing is impossible']
messages:
['Life is like a box of chocolate.', 'To be or not to be, that is a question.', 'nothing is impossible']
sent_messages:
['nothing is impossible', 'To be or not to be, that is a question.', 'Life is like a box of chocolate.']
8.12
defsandwishes(*name):print(f"The pizza you've ordered is with {name}")
sandwishes('beef','cheese','durian')
sandwishes('strawberry','watermelon')
sandwishes('fish')
The pizza you've ordered is with ('beef', 'cheese', 'durian')
The pizza you've ordered is with ('strawberry', 'watermelon')
The pizza you've ordered is with ('fish',)
8.13
defbuild_profile(first, last,**user_info):
user_info['first_name']= first
user_info['last_name']= last
return user_info
user_profile = build_profile('yilia','zhu',hobby='playing the guitar',favourite_book='the story of the stone')print(user_profile)
{'hobby': 'playing the guitar', 'favourite_book': 'the story of the stone', 'first_name': 'yilia', 'last_name': 'zhu'}
8.14
defmake_car(manufacturer,model,**args):print(f"manufacturer is {manufacturer},model is {model},and {args}")
car = make_car('subaru','outback',color='blue',tow_package=True)
car
manufacturer is subaru,model is outback,and {'color': 'blue', 'tow_package': True}
8.15、8.16、8.17 略
9.1
classRestaurant:def__init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
defdescribe_restaurant(self):print(f'restaurant_name:{self.restaurant_name}')print(f'cuisine_type:{self.cuisine_type}')defopen_restaurant(self):print('Our restaurant is open for business.')
restaurant = Restaurant('fairy','chinese')print(restaurant.describe_restaurant())print(restaurant.open_restaurant())
restaurant_name:fairy
cuisine_type:chinese
None
Our restaurant is open for business.
None
9.2
classRestaurant:def__init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
defdescribe_restaurant(self):print(f'{self.restaurant_name} restaurant\'s cuisine_type is {self.cuisine_type}.')defopen_restaurant(self):print('Our restaurant is open for business.')
restaurant1 = Restaurant('fairy','chinese')print(restaurant1.describe_restaurant())
restaurant2 = Restaurant('QuanJuDe','Peking duck')print(restaurant2.describe_restaurant())
restaurant3 = Restaurant('YongHe','breakfast')print(restaurant3.describe_restaurant())
fairy restaurant's cuisine_type is chinese.
None
QuanJuDe restaurant's cuisine_type is Peking duck.
None
YongHe restaurant's cuisine_type is breakfast.
None
classRestaurant:def__init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served =10defdescribe_restaurant(self):print(f'restaurant_name:{self.restaurant_name}')print(f'cuisine_type:{self.cuisine_type}')defopen_restaurant(self):print('Our restaurant is open for business.')defset_number_served(self,number_of_dinners):
self.number_of_dinners = number_of_dinners
print(f'The number of dinners are {self.number_of_dinners}')defincrement_number_served(self,new_number):
self.number_of_dinners += new_number
print(f'The number of dinners are {self.number_of_dinners} now.')
restaurant = Restaurant('fairy','chinese')print(f'There are {restaurant.number_served} people eatting in {restaurant.restaurant_name}. ')print(f'{restaurant.set_number_served(6)}')print(f'{restaurant.increment_number_served(2)}')
There are 10 people eatting in fairy.
The number of dinners are 6
None
The number of dinners are 8 now.
None
from random import randint
classDie:def__init__(self,sides=6):
self.sides = sides
defroll_die(self):print(f'when sides = {self.sides}, random number between[1,{self.sides}] is:{randint(1,self.sides)}')
six_sides = Die()
i =1for i inrange(10):
six_sides.roll_die()
i +=1
ten_sides = Die(10)
i =1for i inrange(10):
ten_sides.roll_die()
i +=1
twenty_sides = Die(20)
i =1for i inrange(10):
twenty_sides.roll_die()
i +=1
when sides = 6, random number between[1,6] is:6
when sides = 6, random number between[1,6] is:3
when sides = 6, random number between[1,6] is:3
when sides = 6, random number between[1,6] is:3
when sides = 6, random number between[1,6] is:3
when sides = 6, random number between[1,6] is:6
when sides = 6, random number between[1,6] is:2
when sides = 6, random number between[1,6] is:4
when sides = 6, random number between[1,6] is:2
when sides = 6, random number between[1,6] is:2
when sides = 10, random number between[1,10] is:7
when sides = 10, random number between[1,10] is:8
when sides = 10, random number between[1,10] is:8
when sides = 10, random number between[1,10] is:6
when sides = 10, random number between[1,10] is:4
when sides = 10, random number between[1,10] is:10
when sides = 10, random number between[1,10] is:6
when sides = 10, random number between[1,10] is:3
when sides = 10, random number between[1,10] is:1
when sides = 10, random number between[1,10] is:3
when sides = 20, random number between[1,20] is:12
when sides = 20, random number between[1,20] is:9
when sides = 20, random number between[1,20] is:3
when sides = 20, random number between[1,20] is:14
when sides = 20, random number between[1,20] is:3
when sides = 20, random number between[1,20] is:18
when sides = 20, random number between[1,20] is:15
when sides = 20, random number between[1,20] is:1
when sides = 20, random number between[1,20] is:5
when sides = 20, random number between[1,20] is:4
9.14
number_word =[1,2,3,4,5,6,7,8,9,0,'a','b','c','d','e']
prize =[]
i=0while i <4:
index = randint(0,14)
prize.append(number_word[index])
i +=1print(prize)
['a', 5, 0, 'e']
9.15
my_ticket =['a',5,0,'e']
n=0
prize =[]while my_ticket != prize:
prize =[]
i=0while i <4:
index = randint(0,14)
prize.append(number_word[index])
i +=1
n +=1print(f'You will win the prize at the {n}th time of the loop')
You will win the prize at the 24923th time of the loop
In C language you can do everything simply.
In C language you can make work more efficiently.
In C language you can know that C language is very elegent.
10.3
name ='Please input your name: 'withopen('guest.txt','w')as L:
contents = L.write(input(name))
Please input your name: jone
10.4
prompt ='Please input your name: '
name =1while name:
name =input(prompt)if name =='q':breakprint(f'Hello,{name}!')withopen('guest_book.txt','a')as L:
contents = L.write(f'{name}\n')
Please input your name: yilia
Hello,yilia!
Please input your name: jack
Hello,jack!
Please input your name: arial
Hello,arial!
Please input your name: q
10.5
prompt ='Please tell me why you love programming: '
reason =1while reason:
reason =input(prompt)if reason =='q':breakwithopen('why_I_love_programming.txt','a')as L:
contents = L.write(f'{reason}\n')
Please tell me why you love programming: because it is quite interesting.
Please tell me why you love programming: no why.
Please tell me why you love programming: for money.
Please tell me why you love programming: hahaha
Please tell me why you love programming: q
10.6
try:
a =int(input('Please input a number: a = '))
b =int(input('Please input another number: b = '))except ValueError:print('the input must be number but not the string!')else:print(f'a+b = {a+b}')
Please input a number: a = 5
Please input another number: b = 6
a+b = 11
10.7
whileTrue:try:
a =int(input('Please input a number: a = '))
b =int(input('Please input another number: b = '))except ValueError:print('the input must be number but not the string!')else:print(f'a+b = {a+b}')
Please input a number: a = 5
Please input another number: b = 6
a+b = 11
Please input a number: a = 9
Please input another number: b = p
the input must be number but not the string!
Please input a number: a = 0
Please input another number: b = 1
a+b = 1
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-24-cfc312c2d183> in <module>
1 while True:
2 try:
----> 3 a = int(input('Please input a number: a = '))
4 b = int(input('Please input another number: b = '))
5 except ValueError:
D:\anaconda\lib\site-packages\ipykernel\kernelbase.py in raw_input(self, prompt)
858 "raw_input was called, but this frontend does not support input requests."
859 )
--> 860 return self._input_request(str(prompt),
861 self._parent_ident,
862 self._parent_header,
D:\anaconda\lib\site-packages\ipykernel\kernelbase.py in _input_request(self, prompt, ident, parent, password)
902 except KeyboardInterrupt:
903 # re-raise KeyboardInterrupt, to truncate traceback
--> 904 raise KeyboardInterrupt("Interrupted by user") from None
905 except Exception as e:
906 self.log.warning("Invalid Message:", exc_info=True)
KeyboardInterrupt: Interrupted by user
# 读取文件try:withopen('cat.txt')as cat:
contents = cat.read()print(f'cats are:\n{contents.rstrip()}')except FileNotFoundError:print('Sorry,We can not found the \'cat.txt\'')try:withopen('dog.txt')as dog:
contents = dog.read()print(f'\ndogs are:\n{contents.rstrip()}')except FileNotFoundError:print('Sorry,We can not found the \'dog.txt\'')
Sorry,We can not found the 'cat.txt'
Sorry,We can not found the 'dog.txt'
import json
number =input('Please input one of your favourate numbers: ')# 写withopen('favourate_number.txt','w')as N:
json.dump(number,N)# 读withopen('favourate_number.txt')as N:
favourate_number = json.load(N)print(f'I know your favourate number!It\'s {favourate_number}')
Please input one of your favourate numbers: 6
I know your favourate number!It's 6
10.12
import json
number =input('Please input one of your favourate numbers: ')# 读withopen('favourate_number.txt')as N:
content = N.read()if(number in content):print(f'I know your favourate number!It\'s {favourate_number}')else:# 写withopen('favourate_number.txt','w')as N:
json.dump(number,N)withopen('favourate_number.txt')as N:
favourate_number = json.load(N)print(f'I know your favourate number!It\'s {favourate_number}')
Please input one of your favourate numbers: 1
I know your favourate number!It's 1
10.13
import json
defget_stored_username():"""如果存储了用户名,就获取它。"""
filename ='username.json'try:withopen(filename)as f:
username = json.load(f)except FileNotFoundError:returnNoneelse:return username
defget_new_username():"""提示用户输入用户名。"""
username =input("What is your name? ")
filename ='username.json'withopen(filename,'w')as f:
json.dump(username, f)return username
defgreet_user():"""问候用户,并指出其名字。"""
username = get_stored_username()if username:
ask =input(f'Is your name is {username}? (Yes/No)')if(ask =='Yes')or(ask =='yes'):print(f"Welcome back, {username}!")else:
username = get_new_username()print(f"We'll remember you when you come back, {username}!")else:
username = get_new_username()print(f"We'll remember you when you come back, {username}!")
greet_user()
Is your name is ppp? (Yes/No)yes
Welcome back, ppp!
11.1
# city_function.pydefcity_country(city,country):
full =f'{city},{country}'return full
# 不能这样写:return 'city,country'
# city_function.pydefcity_country(city,country,population=''):if population:
full =f'{city},{country}-population {population}'else:
full =f'{city},{country}'return full
# 不能这样写:return 'city,country'