favorite_number=8print('My favorite number is'+' '+str(favorite_number))
My favorite number is 8
2-10 添加注释
# this is a notationprint('a notation is testing.')
a notation is testing.
2-11 Python之禅
import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
names=['Jack','Tom','Mark']print(names[0]+', Nice to meet you !')print(names[1]+', Nice to meet you !')print(names[2]+', Nice to meet you !')
Jack, Nice to meet you !
Tom, Nice to meet you !
Mark, Nice to meet you !
3-3 自己的列表
commutes=['Porsche','Mercedes-Benz','HongQi']print('I would like to own a '+commutes[0]+' car')print('I would like to own a '+commutes[1]+' car')print('I would like to own a '+commutes[2]+' car')
I would like to own a Porsche car
I would like to own a Mercedes-Benz car
I would like to own a HongQi car
3-4 嘉宾名单
guest_list=['Tom','Mike','Mark']print(guest_list[0]+' was invited')print(guest_list[1]+' was invited')print(guest_list[2]+' was invited')
Tom was invited
Mike was invited
Mark was invited
3-5 修改嘉宾列表
guest_list=['Tom','Mike','Mark']print(guest_list[-3]+' is unable to keep the appointment')
guest_list[0]='Marry'print(guest_list[0]+' was invited')print(guest_list[1]+' was invited')print(guest_list[2]+' was invited')
Tom is unable to keep the appointment
Marry was invited
Mike was invited
Mark was invited
3-6 添加嘉宾
print('The bigger table has been found')
guest_list.insert(0,'John')
guest_list.insert(2,'Alice')
guest_list.append('Tony')print(guest_list[0]+' was invited')print(guest_list[1]+' was invited')print(guest_list[2]+' was invited')print(guest_list[3]+' was invited')print(guest_list[4]+' was invited')print(guest_list[5]+' was invited')
The bigger table has been found
John was invited
Marry was invited
Alice was invited
Mike was invited
Mark was invited
Tony was invited
3-7 缩减名单
guest_list=['Tom','Mike','Mark']
guest_list[0]='Marry'
guest_list.insert(0,'John')
guest_list.insert(2,'Alice')
guest_list.append('Tony')print('sorry, we have only two people able to attend this invitation')
a=guest_list.pop(0)print(a+' can not be able to invite')
a=guest_list.pop(0)print(a+' can not be able to invite')
a=guest_list.pop(1)print(a+' can not be able to invite')
a=guest_list.pop(2)print(a+' can not be able to invite')print(guest_list[0]+' was still be invited')print(guest_list[1]+' was still be invited')del guest_list[0]del guest_list[0]print(guest_list)
sorry, we have only two people able to attend this invitation
John can not be able to invite
Marry can not be able to invite
Mike can not be able to invite
Tony can not be able to invite
Alice was still be invited
Mark was still be invited
[]
pizzas=['New York Style','Chicago Style','California Style']for pizza in pizzas:print(pizza)print("I want to eat "+pizza+' pizza')print('\nI really love pizza !')
New York Style
I want to eat New York Style pizza
Chicago Style
I want to eat Chicago Style pizza
California Style
I want to eat California Style pizza
I really love pizza !
4-2 动物
animals=['dog','cat','duck']for animal in animals:print(animal)print("A "+animal+" would make a great pet")print("\nAny of these animals would make a great pet !")
dog
A dog would make a great pet
cat
A cat would make a great pet
duck
A duck would make a great pet
Any of these animals would make a great pet !
4-3 数到20
for value inrange(1,21):print(value)
dog
A dog would make a great pet
cat
A cat would make a great pet
duck
A duck would make a great pet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
4-4 一百万
millions=list(range(1,1000001))for million in millions:print(million)
odds=list(range(1,20,2))for odd in odds:print(odd)
1
3
5
7
9
11
13
15
17
19
4-7 3的倍数
odds=list(range(3,31,3))for odd in odds:print(odd)
3
6
9
12
15
18
21
24
27
30
4-8 立方
cubes=[]for value inrange(1,11):
cubes.append(value**3)print(cubes)
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
4-9 立方解析
cubes=[value**3for value inrange(1,11)]print(cubes)
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
4-10 切片
cities=['Beijing','Shanghai','Hangzhou','Chongqing','Zhengzhou']print("The first three items in the list are:")print(cities[0:3])print("\nThree items from the middle of the list are:")print(cities[1:4])print("\nThe last three items in the list are:")print(cities[-3:])
The first three items in the list are:
['Beijing', 'Shanghai', 'Hangzhou']
Three items from the middle of the list are:
['Shanghai', 'Hangzhou', 'Chongqing']
The last three items in the list are:
['Hangzhou', 'Chongqing', 'Zhengzhou']
4-11 你的比萨和我的比萨
pizzas=['New York Style','Chicago Style','California Style']
friend_pizzas=pizzas[0:3]
pizzas.append("Apples Styles")
friend_pizzas.append("Cheese Stycle")for pizza in pizzas:print(pizza)print("\n")for friend_pizza in friend_pizzas:print(friend_pizza)
New York Style
Chicago Style
California Style
Apples Styles
New York Style
Chicago Style
California Style
Cheese Stycle
4-12 使用多个循环
my_foods=['pizza','falafel','carrot cake','cannoli','ice cream']for my_food in my_foods:print(my_food)print('\n')for i inrange(0,5):print(my_foods[4-i])
alien_color='yellow'if alien_color=='green':print("You get 5 scores")
5-4 外星人颜色#2
alien_color='yellow'if alien_color=='green':print("You get 5 scores")else:print("You get 10 scores")
You get 10 scores
5-5 外星人颜色#3
alien_color='yellow'if alien_color=='green':print("You get 5 scores")elif alien_color=='green':print("You get 10 scores")else:print("You get 15 scores")
You get 15 scores
5-6 人生的不同阶段
age=22if age<2:print("He is a baby")elif age>=2and age<4:print("He is learning to walk")elif age>=4and age<13:print("He's a child")elif age>=13and age<20:print("He's a teenager")elif age>=20and age<65:print("He's an adult")elif age>=65:print("He's an old man")
He's an adult
5-7 喜欢的水果
favourite_fruits=['apple','peach','watermelon','bananas','strawberry']if'apple'in favourite_fruits:print("You really like apples")if'peach'in favourite_fruits:print("You really like peaches")if'watermelon'in favourite_fruits:print("You really like watermelons")if'bananas'in favourite_fruits:print("You really like bananas")if'strawberry'in favourite_fruits:print("You really like strawberries")
You really like apples
You really like peaches
You really like watermelons
You really like bananas
You really like strawberries
5-8 以特殊的方式跟管理员打招呼
users=['admin','Tom','Mark','Jack','Eric']for user in users:if user =='admin':print("Hello admin, would you like to see a status report ?")else:print("Hello "+user+" ,"+" thank you for logging in again")
Hello admin, would you like to see a status report ?
Hello Tom , thank you for logging in again
Hello Mark , thank you for logging in again
Hello Jack , thank you for logging in again
Hello Eric , thank you for logging in again
5-9 处理没有用户的情况
users=['admin','Tom','Mark','Jack','Eric']
users=[]if users:for user in users:if user =='admin':print("Hello admin, would you like to see a status report ?")else:print("Hello "+user+" ,"+" thank you for logging in again")else:print("We need to find some users!")
We need to find some users!
5-10 检查用户名
current_users=['Huang','Tom','Mark','Jack','Eric']
new_users=['John','Alice','Tom','Mark','Mike']
i=0for current_user in current_users:
current_users[i].lower()
i=i+1
i=0for new_user in new_users:
new_users[i].lower()
i=i+1for new_user in new_users:if new_user in current_users:print("Sorry, You need to enter a different user name.")else:print("This user name is not used.")
This user name is not used.
This user name is not used.
Sorry, You need to enter a different user name.
Sorry, You need to enter a different user name.
This user name is not used.
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')
rivers={"HuangHe River":"China","ChangJiang River":"China","nile":"egypt",}for key,value in rivers.items():print("The "+key+" runs through "+value.title())print("\n")for key in rivers.keys():print(key)print("\n")for key inset((rivers.values())):print(key.title())
The HuangHe River runs through China
The ChangJiang River runs through China
The nile runs through Egypt
HuangHe River
ChangJiang River
nile
Egypt
China
6-6 调查
favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',}
people=['jen','sarah','edward','phil','mark']for person in people:if person in favorite_languages.keys():print(person.title()+", Thank you for taking the poll.")else:print(person.title()+", We want to invite you to take the poll")
Jen, Thank you for taking the poll.
Sarah, Thank you for taking the poll.
Edward, Thank you for taking the poll.
Phil, Thank you for taking the poll.
Mark, We want to invite you to take the poll
6-7 人
person_0={"first_name":"A","last_name":"B","age":22,"city":"Beijing"}
person_1={"first_name":"C","last_name":"D","age":21,"city":"Shanghai"}
person_2={"first_name":"E","last_name":"F","age":22,"city":"Zhengzhou"}
people=[person_0,person_1,person_2]for persons in people:print(persons)
favorite_places={'Tom':'Beijing,Shanghai,Tianjin','Mike':'Beijing,Shanghai,Hangzhou','Mark':'Beijing,Shanghai,Zhengzhou'}for key,value in favorite_places.items():print(key+"'s favorite place "+value)
Tom's favorite place Beijing,Shanghai,Tianjin
Mike's favorite place Beijing,Shanghai,Hangzhou
Mark's favorite place Beijing,Shanghai,Zhengzhou
6-10 喜欢的数字
favorite_numbers={"Alice":'1,2',"Tom":'2,3',"Jack":'3,4',"Mike":'4,5',"Mark":'5,6'}for key,value in favorite_numbers.items():print(key+"'s favorite numbers are "+value)
Alice's favorite numbers are 1,2
Tom's favorite numbers are 2,3
Jack's favorite numbers are 3,4
Mike's favorite numbers are 4,5
Mark's favorite numbers are 5,6
6-11 城市
cities={'Beijing':{'nation':'China','population':'3kw','modernation':'good'},'Zhengzhou':{'nation':'China','population':'1kw','modernation':'good'},'Shanghai':{'nation':'China','population':'3kw','modernation':'good'}}for city_name,city_info in cities.items():print(city_name+"'s nation is "+city_info['nation'])print("She has "+city_info['population']+' population')print("she's modernation is "+city_info['modernation'])print("\n")
Beijing's nation is China
She has 3kw population
she's modernation is good
Zhengzhou's nation is China
She has 1kw population
she's modernation is good
Shanghai's nation is China
She has 3kw population
she's modernation is good
7-1 汽车租赁
ask=input("what kind of cars do you want ?")print("Let me see if I can find you a Subaru.")
what kind of cars do you want ?bmw
Let me see if I can find you a Subaru.
7-2 餐馆订位
eat=input("How many people having a meal ?")
eat=int(eat)if eat>8:print("There is no vacant table at present.")else:print("There is a table at present.")
How many people having a meal ?10
There is no vacant table at present.
7-3 10的整数倍
number=input("Please input a number:")
number=int(number)if number%10==0:print("This number is an integral multiple of 10.")else:print("This number is not an integral multiple of 10")
Please input a number:100
This number is an integral multiple of 10
7-4 比萨配料
condition=Truewhile condition:
topping=input("Please tell me a topping in your pizza:")if topping=='quit':breakprint(topping.title()+" will be taken in your pizza.")
Please tell me a topping in your pizza:extra cheese
Extra Cheese will be taken in your pizza.
Please tell me a topping in your pizza:harm
Harm will be taken in your pizza.
Please tell me a topping in your pizza:quit
7-5 电影票
condition=Truewhile condition:
age=input("Please tell me your age:")if age=='quit':break
age=int(age)if age<3:print("We are free for you.\n")elif age>=3and age<12:print("Your ticket's price is $10\n")else:print("Your ticket's price is $15\n")
Please tell me your age:2
We are free for you.
Please tell me your age:8
Your ticket's price is $10
Please tell me your age:22
Your ticket's price is $15
Please tell me your age:quit
7-6 三个出口
active=Truewhile active:
age=input("Please tell me your age:")if age=='quit':break
age=int(age)if age<3:print("We are free for you.\n")elif age>=3and age<12:print("Your ticket's price is $10\n")else:print("Your ticket's price is $15\n")
7-7 无限循环
i=0whileTrue:print(i)
i+=1
7-8 熟食店
sandwich_orders=['apple sandwich','ham sandwich','cheese sandwich']
finished_sandwiches=[]while sandwich_orders:
sandwich_order=sandwich_orders.pop()print("I made your "+sandwich_order)
finished_sandwiches.append(sandwich_order)print(finished_sandwiches)
I made your cheese sandwich
I made your ham sandwich
I made your apple sandwich
['cheese sandwich', 'ham sandwich', 'apple sandwich']
7-9 五香烟熏牛肉(pastrami)卖完了
sandwich_orders=['pastrami','apple sandwich','ham sandwich','pastrami','cheese sandwich','pastrami']print("The pastrami have been sold")
active=Truewhile active:if'pastrami'in sandwich_orders:
sandwich_orders.remove("pastrami")else:
active=Falseprint(sandwich_orders)
The pastrami have been sold
['apple sandwich', 'ham sandwich', 'cheese sandwich']
7-10 梦想的度假胜地
places=[]
polling_active=Truewhile polling_active:
question="If you could visit one place in the world, where would you go ?"
place=input(question)if place =='no':break
places.append(place)print(places)
If you could visit one place in the world, where would you go ?beijing
If you could visit one place in the world, where would you go ?zhengzhou
If you could visit one place in the world, where would you go ?shanghai
If you could visit one place in the world, where would you go ?no
['beijing', 'zhengzhou', 'shanghai']
8-1 消息
defdisplay_message():print("I am learning function.")
display_message()
I am learning function.
8-2 喜欢的图书
deffavorite_book(book_name):print("One of my favorite books is "+book_name)
favorite_book("Alice in Wonderland")
One of my favorite books is Alice in Wonderland
8-3 T恤
defmake_shirt(size,slogan):print("This shirt is "+size+" size"+" and printed '"+slogan+" '")
make_shirt("L","Just do it")
make_shirt(size="L",slogan="Just do it")
This shirt is L size and printed 'Just do it '
This shirt is L size and printed 'Just do it '
8-4 大号T恤
defmake_shirt(size='L',slogan="I love python"):print("This shirt is "+size+" size"+" and printed '"+slogan+" '")
make_shirt()
make_shirt('M')
make_shirt("L","Just do it")
This shirt is L size and printed 'I love python '
This shirt is M size and printed 'I love python '
This shirt is L size and printed 'Just do it '
8-5 城市
defdescribe_city(city,nation="China"):print(city+" is in "+nation)
describe_city('Beijing')
describe_city('Zhengzhou')
describe_city('London',nation='British')
Beijing is in China
Zhengzhou is in China
London is in British
8-6 城市名
defcity_country(city,nation):
result='"'+city+','+nation+'"'return result
print(city_country('Beijing','China'))print(city_country('Seoul','Korea'))print(city_country('Tokyo','Japan'))
{'Singer': 'Westlife', 'Album_Name': 'face to face'}
{'Singer': 'Taylor Swift', 'Album_Name': 'fearless'}
{'Singer': 'The Beatles', 'Album_Name': 'Please Please Me'}
8-8 用户的专辑
defmake_album(singer,name,song_number=''):
describe_album={'Singer':singer,'Album_Name':name}return describe_album
whileTrue:
singer=input("Please input a singer: ")if singer=='q':break
name=input("Input this singer's album: ")if name=='q':break
describe=make_album(singer,name)print(describe)print("\n")
Please input a singer: The Beatles
Input this singer's album: Please Please Me
{'Singer': 'The Beatles', 'Album_Name': 'Please Please Me'}
Please input a singer: Taylor Swift
Input this singer's album: fearless
{'Singer': 'Taylor Swift', 'Album_Name': 'fearless'}
Please input a singer: q
8-9 魔术师
defshow_magicians(names):for name in names:print(name)
magicians=['Tom','Mike','Mark']
show_magicians(magicians)
Tom
Mike
Mark
8-10 了不起的魔术师
defmake_great(magicians):
i=0for magician in magicians:
magicians[i]="the Great "+magician
i+=1defshow_magicians(names):for name in names:print(name)
magicians=['Tom','Mike','Mark']
make_great(magicians)
show_magicians(magicians)
the Great Tom
the Great Mike
the Great Mark
8-11 不变的魔术师
defmake_great(magics):
i=0for magic in magics:
magics[i]="the Great "+magic
i+=1return magics
defshow_magicians(names):for name in names:print(name)
magicians=['Tom','Mike','Mark']
magicians_revise=make_great(magicians[:])
show_magicians(magicians)
show_magicians(magicians_revise)
Tom
Mike
Mark
the Great Tom
the Great Mike
the Great Mark
8-12 三明治
defmake_sandwich(*toppings):"""打印顾客点的所有配料"""print("\nMaking a sandwich with the following toppings:")for topping in toppings:print("-"+topping)
make_sandwich('mushrooms')
make_sandwich('extra cheese','ham')
Making a sandwich with the following toppings:
-mushrooms
Making a sandwich with the following toppings:
-extra cheese
-ham
8-13 用户简介
defbuild_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
user_profile=build_profile('Mark','Huang',
location='China',
field='civil of engineering',
gender='male')print(user_profile)
classRestaurant():def__init__(self,restaurant_name,cuisine_type):
self.restaurant_name=restaurant_name
self.cuisine_type=cuisine_type
defdescribe_restaurant(self):print("Our restaurant is "+self.restaurant_name+" ,we sold "+self.cuisine_type)defopen_restaurant(self):print("The restaurant is open")
restaurant=Restaurant("豫香苑","HeNan Stewed noodles and Hulatang")print(restaurant.restaurant_name)print(restaurant.cuisine_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()
豫香苑
HeNan Stewed noodles and Hulatang
Our restaurant is 豫香苑 ,we sold HeNan Stewed noodles and Hulatang
The restaurant is open
9-2 三家餐馆
classRestaurant():def__init__(self,restaurant_name,cuisine_type):
self.restaurant_name=restaurant_name
self.cuisine_type=cuisine_type
defdescribe_restaurant(self):print("Our restaurant is "+self.restaurant_name+" ,we sold "+self.cuisine_type)defopen_restaurant(self):print("The restaurant is open")
restaurant1=Restaurant("豫香苑","HeNan Stewed noodles and Hulatang")
restaurant2=Restaurant("聚丰园","HeNan Stewed noodles")
restaurant3=Restaurant("方中山","Hulatang")
restaurant1.describe_restaurant()
restaurant2.describe_restaurant()
restaurant3.describe_restaurant()
Our restaurant is 豫香苑 ,we sold HeNan Stewed noodles and Hulatang
Our restaurant is 聚丰园 ,we sold HeNan Stewed noodles
Our restaurant is 方中山 ,we sold Hulatang
9-3 用户
classUser():def__init__(self,first_name,last_name):
self.first_name=first_name
self.last_name=last_name
defdescribe_user(self):print("This user's name is "+self.first_name+" "+self.last_name)defgreet_user(self):print(self.first_name+" "+self.last_name+" Welcome you !")
user1=User('Eloise','Dimucci')
user1.describe_user()
user2=User('Penelope','Liones')
user2.describe_user()
user3=User('Evelyn','Alovis')
user3.describe_user()
This user's name is Eloise Dimucci
This user's name is Penelope Liones
This user's name is Evelyn Alovis
9-4 就餐人数
classRestaurant():def__init__(self,restaurant_name,cuisine_type):
self.restaurant_name=restaurant_name
self.cuisine_type=cuisine_type
self.number_served=0defdescribe_restaurant(self):print("Our restaurant is "+self.restaurant_name+" ,we sold "+self.cuisine_type)defopen_restaurant(self):print("The restaurant is open")defincrement_number_served(self,imp_number):
self.impossible_number=imp_number
print("This restaurant can accommodate "+str(self.impossible_number)+" people every day")
restaurant=Restaurant("豫香苑","HeNan Stewed noodles and Hulatang")print(restaurant.restaurant_name)print(restaurant.cuisine_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()print(str(restaurant.number_served)+" people have dined in this restaurant")
restaurant.number_served=88print(str(restaurant.number_served)+" people have dined in this restaurant")
restaurant.increment_number_served(100)
豫香苑
HeNan Stewed noodles and Hulatang
Our restaurant is 豫香苑 ,we sold HeNan Stewed noodles and Hulatang
The restaurant is open
0 people have dined in this restaurant
88 people have dined in this restaurant
This restaurant can accommodate 100 people every day
9-5 尝试登陆次数
classUser():def__init__(self,first_name,last_name):
self.first_name=first_name
self.last_name=last_name
self.login_attempts=0defdescribe_user(self):print("This user's name is "+self.first_name+" "+self.last_name)defgreet_user(self):print(self.first_name+" "+self.last_name+" Welcome you !")defincrement_login_attempts(self):
self.login_attempts+=1defreset_login_attempts(self):
self.login_attempts=0
my_user=User("A","B")
my_user.increment_login_attempts()print(my_user.login_attempts)
my_user.increment_login_attempts()print(my_user.login_attempts)
my_user.increment_login_attempts()print(my_user.login_attempts)
my_user.reset_login_attempts()print(my_user.login_attempts)
1
2
3
0
9-6 冰淇淋小店
classRestaurant():def__init__(self,restaurant_name,cuisine_type):
self.restaurant_name=restaurant_name
self.cuisine_type=cuisine_type
defdescribe_restaurant(self):print("Our restaurant is "+self.restaurant_name+" ,we sold "+self.cuisine_type)defopen_restaurant(self):print("The restaurant is open")classIceCreamStand(Restaurant):def__init__(self,restaurant_name,cuisine_type):super().__init__(restaurant_name,cuisine_type)
self.flavors=['popsicle','frozen yogurt','gelato']defshow(self):print(self.flavors)
icecream=IceCreamStand('ICECREAM','snack')
icecream.show()
['popsicle', 'frozen yogurt', 'gelato']
9-7 管理员
classUser():def__init__(self,first_name,last_name):
self.first_name=first_name
self.last_name=last_name
defdescribe_user(self):print("This user's name is "+self.first_name+" "+self.last_name)defgreet_user(self):print(self.first_name+" "+self.last_name+" Welcome you !")classAdmin(User):def__init__(self,first_name,last_name):super().__init__(first_name,last_name)
self.privileges=['can add post','can delete post','can ban user']defshow_privileges(self):print(self.privileges)
admin_user=Admin('Eloise','Dimucci')
admin_user.show_privileges()
['can add post', 'can delete post', 'can ban user']
9-8 权限
classPrivileges():def__init__(self,privileges=['can add post','can delete post','can ban user']):
self.privileges=privileges
defshow_privileges(self):print(self.privileges)classUser():def__init__(self,first_name,last_name):
self.first_name=first_name
self.last_name=last_name
defdescribe_user(self):print("This user's name is "+self.first_name+" "+self.last_name)defgreet_user(self):print(self.first_name+" "+self.last_name+" Welcome you !")classAdmin(User):def__init__(self,first_name,last_name):super().__init__(first_name,last_name)
self.PRIVILEGES=Privileges()
admin_user=Admin('Eloise','Dimucci')
admin_user.PRIVILEGES.show_privileges()
['can add post', 'can delete post', 'can ban user']
9-9 电瓶升级
classCar():def__init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=0defget_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
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=240elif self.battery_size==85:range=270
message="This car can go approximately "+str(range)
message+=" miles on a full charge"print(message)defupgrade_battery(self):if self.battery_size !=85:
self.battery_size=85classElectricCar(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()
my_tesla.battery.upgrade_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
This car can go approximately 270 miles on a full charge
10-1 Python学习笔记
filename_path=r'C:\Users\JianFei\Desktop\learning_python.txt'withopen(filename_path)as file_object:
contents=file_object.read()print(contents)print("\n")withopen(filename_path)as file_object:for line in file_object:print(line.rstrip())print("\n")withopen(filename_path)as file_object:
lines=file_object.readlines()for line in lines:print(line)
In Python you can store as much information as you want.
In Python you can connect pieces of information.
In Python you can model real-world situations.
In Python you can store as much information as you want.
In Python you can connect pieces of information.
In Python you can model real-world situations.
In Python you can store as much information as you want.
In Python you can connect pieces of information.
In Python you can model real-world situations.
10-2 C语言学习笔记
filename_path=r'C:\Users\JianFei\Desktop\learning_python.txt'withopen(filename_path)as file_object:
lines=file_object.readlines()for line in lines:
line=line.replace("Python","C")print(line)
In C you can store as much information as you want.
In C you can connect pieces of information.
In C you can model real-world situations.
10-3 访客
filename='guest.txt'withopen(filename,'w')as file_object:
file_object.write(input("Please input your name:"))
filename='reasons.txt'
reason=''withopen(filename,'w')as file_object:whileTrue:
reason=input("Please input a reason why you like programning ?")if reason=='stop':breakelse:
file_object.write(reason+"\n")
10-6 加法运算
print("Give me two numbers: and I'll add them.")
first_number=input("\nFirst number:")try:
first_number=int(first_number)except ValueError:print("You're entering text, Please enter a number.")else:
second_number=input("Second number:")try:
second_number=int(second_number)except ValueError:print("You're entering text, Please enter a number.")else:print(first_number+second_number)
Give me two numbers: and I'll add them.
First number:8
Second number:a
You're entering text, Please enter a number.
10-7 加法计算器
print("Give me two numbers: and I'll add them.")print("Enter 'q' to quit.")whileTrue:
first_number=input("\nFirst number:")if first_number=='q':breaktry:
first_number=int(first_number)except ValueError:print("You're entering text, Please enter a number.")else:
second_number=input("Second number:")if second_number=='q':breaktry:
second_number=int(second_number)except ValueError:print("You're entering text, Please enter a number.")else:print(first_number+second_number)
Give me two numbers: and I'll add them.
Enter 'q' to quit.
First number:8
Second number:8
16
First number:q
10-8 猫和狗
defprint_name(filename):try:withopen(filename)as f_obj:
contents=f_obj.read()except FileNotFoundError:
msg="Sorry, the file "+filename+" does not exist."print(msg)else:print(contents)
filenames=['cats.txt','dogs.txt']for filename in filenames:
print_name(filename)
a
b
c
Sorry, the file dogs.txt does not exist.
10-9 沉默的猫和狗
defprint_name(filename):try:withopen(filename)as f_obj:
contents=f_obj.read()except:passelse:print(contents)
filenames=['cats.txt','dogs.txt']for filename in filenames:
print_name(filename)
a
b
c
10-10 常见单词
filename='War against Germany and Italy.txt'try:withopen(filename,encoding='UTF-8')as f_obj:
contents=f_obj.read()except FileNotFoundError:
msg="Sorry the file "+filename+" does not exist."print(msg)else:
words=contents.split()
num=words.count('the')print("'the' appears "+str(num)+" times")
'the' appears 26 times
10-11 喜欢的数字
import json
filename="favorurite_number.json"
fav_number=input("Please input your favorite number.")withopen(filename,'w')as f_obj:
json.dump(fav_number,f_obj)
Please input your favorite number.8
import json
filename="favorurite_number.json"withopen(filename)as f_obj:
fav_number=json.load(f_obj)print("I know your favourite number!It's "+fav_number)
I know your favourite number!It's 8
10-12 记住喜欢的数字
import json
filename='favourite_number.json'try:withopen(filename)as f_obj:
fav_number=json.load(f_obj)except:
fav_number=input("Please input your favorite number.")withopen(filename,'w')as f_obj:
json.dump(fav_number,f_obj)print("Your favourite number has been recorded !It's "+fav_number)else:print("I know your favourite number!It's "+fav_number)
Please input your favorite number.8
Your favourite number has been recorded !It's 8
10-13 验证用户
import json
defget_stored_username():"""如果存储了用户名,就获取它"""
filename='username.json'try:withopen(filename)as f_obj:
username=json.load(f_obj)except FileNotFoundError:returnNoneelse:return username
defget_user_username():"""提示用户输入用户名"""
username=input("What is your name?")
filename='username.json'withopen(filename,'w')as f_obj:
json.dump(username,f_obj)return username
defgreet_user():"""问候用户,并指出其名字"""
username=get_stored_username()if username:print("Welcomg back, "+username+"!")else:
username=get_new_username()print("We'll remember you when you come back, "+username+"!")
greet_user()