8.1
def display_message():
print("I am study some knowledge of function in python.")
display_message()
I am study some knowledge of function in python.
8.2
def favourite_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
def make_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
def make_shirt(size='large',word='I love python'):
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
def describe_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
8.6
def city_country(city,country):
full_name = f"{city},{country}"
return full_name
print(city_country('shenzhen','China'))
print(city_country('Otaru','Japan'))
print(city_country('PuSan','Korea'))
shenzhen,China
Otaru,Japan
PuSan,Korea
8.7
def make_album(singer,album):
information = {'singer':singer,'album':album}
return information
make_album('WuQingFeng','Tomorrow will be fine')
{'singer': 'WuQingFeng', 'album': 'Tomorrow will be fine'}
def make_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
def make_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
while True:
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)
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']
def show_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 = []
def send_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 = []
def send_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
def sandwishes(*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
def build_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
def make_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
class Restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(f'restaurant_name:{self.restaurant_name}')
print(f'cuisine_type:{self.cuisine_type}')
def open_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
class Restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(f'{self.restaurant_name} restaurant\'s cuisine_type is {self.cuisine_type}.')
def open_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
9.3
class User:
def __init__(self,first_name,last_name,age,sex):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.sex = sex
self.fullname = f'{last_name}{first_name}'
def describe_user(self):
print(f'\nname:{self.fullname}\nage:{self.age}\nsex:{self.sex}\n')
def greet_user(self):
print(f'Hello {self.fullname},Good Moring!')
bao_yu = User('宝玉','贾','14','男')
print(bao_yu.describe_user())
print(bao_yu.greet_user())
dai_yu = User('黛玉','林','13','女')
print(dai_yu.describe_user())
print(dai_yu.greet_user())
bao_chai = User('宝钗','薛','15','女')
print(bao_chai.describe_user())
print(bao_chai.greet_user())
name:贾宝玉
age:14
sex:男
None
Hello 贾宝玉,Good Moring!
None
name:林黛玉
age:13
sex:女
None
Hello 林黛玉,Good Moring!
None
name:薛宝钗
age:15
sex:女
None
Hello 薛宝钗,Good Moring!
None
9.4
class Restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 10
def describe_restaurant(self):
print(f'restaurant_name:{self.restaurant_name}')
print(f'cuisine_type:{self.cuisine_type}')
def open_restaurant(self):
print('Our restaurant is open for business.')
def set_number_served(self,number_of_dinners):
self.number_of_dinners = number_of_dinners
print(f'The number of dinners are {self.number_of_dinners}')
def increment_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
9.5
class User:
def __init__(self,first_name,last_name,age,sex,login_attempts):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.sex = sex
self.fullname = f'{last_name}{first_name}'
self.login_attempts = login_attempts
def describe_user(self):
print(f'\nname:{self.fullname}\nage:{self.age}\nsex:{self.sex}\n')
def greet_user(self):
print(f'Hello {self.fullname},Good Moring!')
def increment_login_attempts(self):
self.login_attempts += 1
print(self.login_attempts)
def reset_login_attempts(self):
self.login_attempts = 0
print(self.login_attempts)
bao_yu = User('宝玉','贾','14','男',5)
print(bao_yu.increment_login_attempts())
print(bao_yu.increment_login_attempts())
print(bao_yu.increment_login_attempts())
print(bao_yu.increment_login_attempts())
print(bao_yu.increment_login_attempts())
print(bao_yu.reset_login_attempts())
6
None
7
None
8
None
9
None
10
None
0
None
9.6
class IceCreamStand(Restaurant):
def __init__(self,flavors):
self.flavors = flavors
def show_icecream(self):
print(self.flavors)
IceCreamStand = IceCreamStand(['matcha','strawberry','chocolate'])
print(IceCreamStand.show_icecream())
['matcha', 'strawberry', 'chocolate']
None
9.7
class Admin(User):
def __init__(self,privileges):
self.privileges = privileges
def show_privileges(self):
print(self.privileges)
Admin = Admin(['can add post','can delete post','can ban user'])
print(Admin.show_privileges())
['can add post', 'can delete post', 'can ban user']
None
9.8
class Privileges:
def __init__(self,privileges=['can add post1','can delete post1','can ban user1']):
self.privileges = privileges
def show_privileges(self):
print(self.privileges)
class Admin(User):
def __init__(self):
self.privileges = Privileges()
Admin = Admin()
print(Admin.privileges.show_privileges())
['can add post1', 'can delete post1', 'can ban user1']
None
9.9
class Battery:
def __init__(self,battery_size=75):
self.battery_size = battery_size
def upgrad_battery(self):
if self.battery_size != 100:
self.battery_size = 100
print(f'battery_size = {self.battery_size}')
def get_range(self):
if self.battery_size == 75:
range = 260
elif self.battery_size == 100:
range = 315
print(f'range = {range}')
Electrical_car = Battery()
Electrical_car.get_range()
Electrical_car.upgrad_battery()
Electrical_car.get_range()
range = 260
battery_size = 100
range = 315
9.10-12 略
9.13
from random import randint
class Die:
def __init__(self,sides=6):
self.sides = sides
def roll_die(self):
print(f'when sides = {self.sides}, random number between[1,{self.sides}] is:{randint(1,self.sides)}')
six_sides = Die()
i = 1
for i in range(10):
six_sides.roll_die()
i += 1
ten_sides = Die(10)
i = 1
for i in range(10):
ten_sides.roll_die()
i += 1
twenty_sides = Die(20)
i = 1
for i in range(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=0
while i < 4:
index = randint(0,14)
prize.append(number_word[index])
i += 1
print(prize)
['a', 5, 0, 'e']
9.15
my_ticket = ['a', 5, 0, 'e']
n=0
prize = []
while my_ticket != prize:
prize = []
i=0
while i < 4:
index = randint(0,14)
prize.append(number_word[index])
i += 1
n += 1
print(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
10.1
with open('learning_python.txt') as L:
contents = L.read()
print(contents.rstrip())
In python you can do everything simply.
In python you can make work more efficiently.
In python you can know that python is very elegent.
with open('learning_python.txt') as L:
for line in L:
print(line.rstrip())
In python you can do everything simply.
In python you can make work more efficiently.
In python you can know that python is very elegent.
with open('learning_python.txt') as L:
lines = L.readlines()
for line in lines:
print(line.rstrip())
In python you can do everything simply.
In python you can make work more efficiently.
In python you can know that python is very elegent.
10.2
message = 'I very like bao_yu'
message.replace('bao_yu','dai_yu')
'I very like dai_yu'
with open('learning_python.txt') as L:
contents = L.read()
print(contents.replace('python','C language'))
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: '
with open('guest.txt','w') as L:
contents = L.write(input(name))
Please input your name: jone
10.4
prompt = 'Please input your name: '
name = 1
while name:
name = input(prompt)
if name == 'q':
break
print(f'Hello,{name}!')
with open('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 = 1
while reason:
reason = input(prompt)
if reason == 'q':
break
with open('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
while True:
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
10.8
with open('cat.txt','a') as cat:
cat.write('paopao\n')
cat.write('dudu\n')
cat.write('niqiu\n')
with open('dog.txt','a') as dog:
dog.write('xiaohui\n')
dog.write('laipi\n')
dog.write('xiaobai\n')
try:
with open('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:
with open('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'
10.9
try:
with open('cat.txt') as cat:
contents = cat.read()
print(f'cats are:\n{contents.rstrip()}')
except FileNotFoundError:
pass
try:
with open('dog.txt') as dog:
contents = dog.read()
print(f'\ndogs are:\n{contents.rstrip()}')
except FileNotFoundError:
pass
cats are:
paopao
dudu
niqiu
dogs are:
xiaohui
laipi
xiaobai
10.10
with open('story of the stone.txt',encoding='utf-8') as H:
count_number_baoyu = 0
count_number_daiyu = 0
count_number_baochai = 0
lines = H.readlines()
for line in lines:
count_number_baoyu += line.count('寶玉')
count_number_daiyu += line.count('黛玉')
count_number_baochai += line.count('寶釵')
print(f'红楼梦中,\'宝玉\'一共出现了{count_number_baoyu}次')
print(f'红楼梦中,\'黛玉\'一共出现了{count_number_daiyu}次')
print(f'红楼梦中,\'宝钗\'一共出现了{count_number_baochai}次')
红楼梦中,'宝玉'一共出现了3832次
红楼梦中,'黛玉'一共出现了1321次
红楼梦中,'宝钗'一共出现了1051次
10.11
import json
number = input('Please input one of your favourate numbers: ')
with open('favourate_number.txt','w') as N:
json.dump(number,N)
with open('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: ')
with open('favourate_number.txt') as N:
content = N.read()
if (number in content):
print(f'I know your favourate number!It\'s {favourate_number}')
else:
with open('favourate_number.txt','w') as N:
json.dump(number,N)
with open('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
def get_stored_username():
"""如果存储了用户名,就获取它。"""
filename = 'username.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
"""提示用户输入用户名。"""
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as f:
json.dump(username, f)
return username
def greet_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
def city_country(city,country):
full = f'{city},{country}'
return full
import unittest
for city_function import city_country
class NamesTestCase(unittest.TestCase):
def test_city_country(self):
formatted_name = city_country('shenzhen','china')
self.assertEqual(formatted_name,'shenzhen,china')
if __name__ == '__main__':
unittest.main()
11.2
def city_country(city,country,population=''):
if population:
full = f'{city},{country}-population {population}'
else:
full = f'{city},{country}'
return full
import unittest
for city_function import city_country
class NamesTestCase(unittest.TestCase):
def test_city_country(self):
formatted_name = city_country('shenzhen','china')
self.assertEqual(formatted_name,'shenzhen,china')
def test_city_country_population(self):
formatted_name = city_country('shenzhen','china',30_000)
self.assertEqual(formatted_name,'shenzhen,china-population 30000')
if __name__ == '__main__':
unittest.main()
11.3
class Employee:
def __init__(self,first_name,last_name,annual_salary,increase=5000):
self.first_name = first_name
self.last_name = last_name
self.annual_salary = annual_salary
self.increase = increase
def give_raise(self):
self.annual_salary = int(self.annual_salary) + int(self.increase)
return self.annual_salary
a = Employee('a','b',10000,6000)
a.give_raise()
16000
import unittest
from employee import Employee
class NameTestCase(unittest.TestCase):
def test_give_default_raise(self):
formatted_name = Employee('yilia','zhu','300_000')
self.assertEqual(formatted_name.give_raise(),305000)
def test_give_custom_raise(self):
formatted_name = Employee('yilia','zhu','300_000','10_000')
self.assertEqual(formatted_name.give_raise(),310000)
if __name__ == '__main__':
unittest.main()