赞
踩
print("Hello Python world!")
message="Hello Python world!"
print(message)
message="Hello Python Crash Course world!"
print(message)
name='ada lovelace'
print(name.title())
##输出:Ada Lovelace
---------------------
name='Ada Lovelace'
print(name.upper())
print(name.lower())
#ADA LOVELACE
#ada lovelace
##拼接
first_name='ada'
last_name='lovelace'
full_name=first_name+" "+last_name
print(full_name)
#输出为:ada lovelace
-----------------------------------
print("Hello, "+full_name.title()+"!")
#输出为:Hello, Ada Lovelace!
-----------------------------------
message="Hello, "+full_name.title()+"!"
print(message)
#输出为:Hello, Ada Lovelace!
print("Python") print("\tPython") #Python # Python ------------------ print("Languages:\nPython\nC\nJavaScript") #Languages: #Python #C #JavaScript ''' print("Languages:\n\tPython\n\tC\n\tJavaScript") #Languages: # Python # C # JavaScript
favorite_language='python ' favorite_language favorite_language.rstrip() favorite_language #'python' #'python ' #'python' -------------------------- favorite_language='python ' favorite_language=favorite_language.rstrip() favorite_language #输出为:'python' -------------------------- favorite_language=' python ' favorite_language.rstrip() favorite_language.lstrip() favorite_language.strip() #输出为:' python' 'python ' 'python'
2 + 3 = 5
3 - 2 = 1
2 * 3 = 6
3 / 2 = 1.5
3 ** 2 = 9
3 ** 3 = 27
10 ** 6 = 1000000
2 + 3 * 4 = 14
(2 + 3) * 4 =20
0.1 + 0.1 = 0.2
0.2 + 0.2 = 0.4
2 * 0.1 = 0.2
2 * 0.2 = 0.4
age=23
message="Happy "+str(age)+"rd Birthday!"
print(message)
Happy 23rd Birthday!
#向大家问好
print("Hello Python people!")
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!
bicycles=['trek','cannondale','redline','specialized']
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
bicycles=['trek','cannondale','redline','specialized']
print(bicycles[0])
print(bicycles[0].title())
trek
Trek
bicycles=['trek','cannondale','redline','specialized']
print(bicycles[1])
print(bicycles[2])
print(bicycles[3])
print(bicycles[-1])
print(bicycles[-2])
cannondale
redline
specialized
specialized
redline
bicycles=['trek','cannondale','redline','specialized']
message="My first bicycle was a "+bicycles[0].title()+"."
print(message)
My first bicycle was a Trek.
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
motorcycles[0]='ducati'
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'ducati']
motorcycles=[]
print(motorcycles)
motorcycles.append('honda')
print(motorcycles)
motorcycles.append('yamaha')
print(motorcycles)
motorcycles.append('suzuki')
print(motorcycles)
[]
['honda']
['honda', 'yamaha']
['honda', 'yamaha', 'suzuki']
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
motorcycles.insert(0,'ducati')
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['ducati', 'honda', 'yamaha', 'suzuki']
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
del motorcycles[1]
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['honda', 'suzuki']
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
popped_motorcycles=motorcycles.pop()
print(motorcycles)
print(popped_motorcycles)
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki
motorcycles=['honda','yamaha','suzuki']
first_owned=motorcycles.pop(0)
print('The first motorcycle I owned was a '+ first_owned.title() + '.')
The first motorcycle I owned was a Honda.
motorcycles=['honda','yamaha','suzuki','ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
motorcycles=['honda','yamaha','suzuki','ducati']
print(motorcycles)
too_expensive='ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA "+too_expensive.title()+" is too expensive for me.")
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
A Ducati is too expensive for me.
cars=['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
cars=['bmw','audi','toyota','subaru']
cars.sort(reverse=True)
print(cars)
['audi', 'bmw', 'subaru', 'toyota']
['toyota', 'subaru', 'bmw', 'audi']
cars=['bmw','audi','toyota','subaru']
print('Here is the original list:')
print(cars)
print('\nHere is the sorted list:')
print(sorted(cars))
print('\nHere is the original list:')
print(cars)
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
cars=['bmw','audi','toyota','subaru']
print(cars)
cars.reverse()
print(cars)
cars.reverse()
print(cars)
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']
['bmw', 'audi', 'toyota', 'subaru']
cars=['bmw','audi','toyota','subaru']
print(len(cars))
4
magicians=['alice','david','carolina']
for magician in magicians:
print(magician)
alice
david
carolina
for magician in magicians:
for cat in cats:
for dog in dogs:
for item in list_of_items:
magicians=['alice','david','carolina']
for magician in magicians:
print(magician.title()+', that was a great trick !')
print("I can't wait to see your next trick, "+magician.title()+".\n")
Alice, that was a great trick !
I can't wait to see your next trick, Alice.
David, that was a great trick !
I can't wait to see your next trick, David.
Carolina, that was a great trick !
I can't wait to see your next trick, Carolina.
magicians=['alice','david','carolina']
for magician in magicians:
print(magician.title()+', that was a great trick !')
print("I can't wait to see your next trick, "+magician.title()+".\n")
print("Thank you , everyone. That was a great magic show !")
Alice, that was a great trick !
I can't wait to see your next trick, Alice.
David, that was a great trick !
I can't wait to see your next trick, David.
Carolina, that was a great trick !
I can't wait to see your next trick, Carolina.
Thank you , everyone. That was a great magic show !
for value in range(1,5):
print(value)
print("\n")
for value in range(1,6):
print(value)
1
2
3
4
1
2
3
4
5
numbers=list(range(1,6)) print(numbers) even_numbers=list(range(2,11,2)) print(even_numbers) print("\n") squares=[] for value in range(1,11): square=value**2 squares.append(square) print(squares) print("\n") squares=[] for value in range(1,11): squares.append(value**2) print(squares)
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
digits=[1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
0
9
45
squares=[value**2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
players=['charles','martina','michael','florence','eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[2:])
print(players[-3:])
['charles', 'martina', 'michael']
['martina', 'michael', 'florence']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
players=['charles','martina','michael','florence','eli']
print("Here are the first three players on my team")
for player in players[0:3]:
print(player.title())
Here are the first three players on my team
Charles
Martina
Michael
my_foods=['pizza','falafel','carrot cake']
friend_foods=my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
dimensions=(200,50)
print(dimensions[0])
print(dimensions[1])
200
50
dimensions=(200,50)
for dimension in dimensions:
print(dimension)
200
50
dimensions=(200,50)
print("Original,dimensions")
for dimension in dimensions:
print(dimension)
dimensions=(400,100)
print("\nModified dimensions")
for dimension in dimensions:
print(dimension)
Original,dimensions
200
50
Modified dimensions
400
100
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car=='bmw':
print(car.upper())
else:
print(car.title())
Audi
BMW
Subaru
Toyota
car='bmw'
print(car=='bmw')
car='bmw'
print(car=='audi')
True
False
car='Audi'
print(car=='audi')
car='Audi'
print(car.lower()=='audi')#lower()不改变原变量的值
print(car)
False
True
Audi
requested_topping='mushroom'
if requested_topping!='anchovies':
print("Hold the anchovies")
Hold the anchovies
age=18
print(age==18)
answer=17
if answer !=42:
print("That is not the correct answer.Please try again!")
age=19
print(age<21)
print(age<=21)
print(age>21)
print(age>=21)
True
That is not the correct answer.Please try again!
True
True
False
False
age_0=22
age_1=18
print(age_0>=21 and age_1>=21)
age_1=22
print(age_0>=21 and age_1>=21)
False
True
age_0=22
age_1=18
print(age_0>=21 or age_1>=21)
age_0=18
print(age_0>=21 or age_1>=21)
True
False
requested_toppings=['mushrooms','onions','pineapple']
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)
True
False
banned_user=['andrew','carolina','david']
user='marie'
if user not in banned_user:
print(user.title()+", you can post a response if you wish")
Marie, you can post a response if you wish
game_active=True
can_edit=False
age = 19
if age >=18:
print("You are old enough to vote")
print("Have you registered to vote yet ?")
You are old enough to vote
Have you registered to vote yet ?
age = 17
if age >=18:
print("You are old enough to vote")
print("Have you registered to vote yet ?")
else:
print("Sorry,you are too young to vote")
print("Please register to vote as soon as you turn 18 !")
Sorry,you are too young to vote
Please register to vote as soon as you turn 18 !
age=12 if age<4: print("Your admission cost is $0.") elif age < 18: print("Your admission cost is $5.") else: print("Your admission cost is $10.") age=12 if age<4: price=0 elif age<18: price=5 else: price=10 print("Your admission cost is $"+str(price)+".")
Your admission cost is $5.
Your admission cost is $5.
age=12
if age<4:
price=0
elif age<18:
price=5
elif age<65:
price=10
else:
price=5
print("Your admission cost is $"+str(price)+".")
Your admission cost is $5.
age=12
if age<4:
price=0
elif age<18:
price=5
elif age<65:
price=10
elif age>=65:
price=5
print("Your admission cost is $"+str(price)+".")
Your admission cost is $5.
requested_toppings=['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if "pepperoni" in requested_toppings:
print("Adding pepperoni")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese")
print("\nFinished making your pizza!")
Adding mushrooms.
Adding extra cheese
Finished making your pizza!
requested_toppings=['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print("Adding "+requested_topping+".")
print("\nFinished making your pizza !")
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza !
requested_toppings=[]
if requested_toppings :
for requested_topping in requested_toppings:
print("Adding "+requested_topping+".")
print("\nFinished making your pizza !")
else:
print("Are you sure you want a plain pizza ?")
Are you sure you want a plain pizza ?
available_toppings=['mushrooms','olives','green peppers','prpperoni','pineapple','extra cheese']
requested_toppings=['mushrooms','french fries','extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding "+requested_topping+'.')
else:
print("We don't have "+requested_topping + ".")
print("\nFinished making your pizza !")
Adding mushrooms.
We don't have french fries.
Adding extra cheese.
Finished making your pizza !
alien_0 ={'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])
green
5
alien_0 ={'color':'green','points':5}
alien_0 ={'color':'green'}
print(alien_0)
{'color': 'green'}
alien_0={'color':"green",'points':5}
print(alien_0['color'])
new_points=alien_0['points']
print("You just earned "+str(new_points)+" points")
green
You just earned 5 points
alien_0={'color':'green','points':5}
print(alien_0)
alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
alien_0={}
alien_0['color']='green'
alien_0['points']=5
print(alien_0)
{'color': 'green', 'points': 5}
alien_0={'color':'green'} print("The alien is "+ alien_0['color'] +".") alien_0={'color':'yellow'} print("The alien is now "+ alien_0['color'] +".") alien_0={'x_position':0,'y_position':25,'speed':'medium'} print("Original x-position: "+str(alien_0['x_position'])) #向右移动外星人 #据外星人当前速度决定将其移动多远 if alien_0['speed']=='slow': x_increment=1 elif alien_0['speed']=='medium': x_increment=2 else: # 这个外星人的速度一定很快 x_increment=3 # 新位置等于老位置加上增量 alien_0['x_position']=alien_0['x_position']+x_increment print("New x_position: "+str(alien_0['x_position']))
The alien is green.
The alien is now yellow.
Original x-position: 0
New x_position: 2
alien_0={'color':"green",'points':5}
print(alien_0)
del alien_0['points']
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green'}
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print("Sarah's favorite languages is "+favorite_languages['sarah'].title()+".")
Sarah's favorite languages is C.
user_0={ 'username':'efermi', 'first':'enrico', 'last':'fermi', } for key,value in user_0.items(): print("\nKey: "+key) print("Value: "+value) print("\n") favorite_languages={ 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } for name,language in favorite_languages.items(): print(name.title()+"'s favorite language is "+language.title()+".")
Key: username
Value: efermi
Key: first
Value: enrico
Key: last
Value: fermi
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.
favorite_languages={ 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } for name in favorite_languages.keys(): print(name.title()) print("\n") friends=['phil','sarah'] for name in favorite_languages.keys(): print(name.title()) if name in friends: print(" Hi "+name.title()+", I see your favorite language is "+favorite_languages[name].title()+"!")
Jen
Sarah
Edward
Phil
Jen
Sarah
Hi Sarah, I see your favorite language is C!
Edward
Phil
Hi Phil, I see your favorite language is Python!
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title()+", thank you for taking the poll.")
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
print("\n")
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
The following languages have been mentioned:
Python
C
Ruby
Python
The following languages have been mentioned:
Python
C
Ruby
alien_0={'color':'green','points':5} alien_1={'color':'yellow','points':10} alien_2={'color':'red','points':15} aliens=[alien_0,alien_1,alien_2] for alien in aliens: print(alien) print("\n-----------------------------") # 创建一个用于存储外星人的空列表 aliens=[] # 创建30个绿色的外星人 for alien_number in range(30): new_alien={'color':'green','points':5,'speed':'slow'} aliens.append(new_alien) for alien in aliens[0:3]: if alien['color']=='green': alien['color']='yellow' alien['speed']='medium' alien['points']=10 elif alien['color']== 'yellow': alien['color']='red' alien['speed']='fast' alien['points']=15 #显示前五个外星人 for alien in aliens[:5]: print(alien) print(".....") #显示创建了多少个外星人 print("Total number of aliens: "+str(len(aliens)))
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
-----------------------------
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
.....
Total number of aliens: 30
# 存储所点比萨的信息 pizza={ 'crust':'thick', 'toppings':['mushrooms','extra cheese'] } #概述所点的比萨 print("You ordered a "+pizza['crust']+"-crust pizza "+"with the following toppings:") for topping in pizza['toppings']: print("\t"+topping) print("--------------------------") favorite_languages={ 'jen':['python','ruby'], 'sarah':['c'], 'edward':['ruby','go'], 'phil':['python','haskell'], } for name,languages in favorite_languages.items(): print("\n"+name.title()+"'s favorite languages are:") for language in languages: print("\t"+language.title())
You ordered a thick-crust pizza with the following toppings: mushrooms extra cheese -------------------------- Jen's favorite languages are: Python Ruby Sarah's favorite languages are: C Edward's favorite languages are: Ruby Go Phil's favorite languages are: Python Haskell
users={ 'aeinstein':{ 'first':'albert', 'last':'aeinstein', 'location':'priceton', }, 'mcurie':{ 'first':'marie', 'last':'curie', 'location':'pairs', }, } for username,user_info in users.items(): print("\nUsername: "+username) full_name=user_info['first']+' '+user_info['last'] location=user_info['location'] print("\tFull name: "+full_name.title()) print("\tLocation: "+location.title())
Username: aeinstein
Full name: Albert Aeinstein
Location: Priceton
Username: mcurie
Full name: Marie Curie
Location: Pairs
message=input("Tell me something,and I will repeat it back to you: ")
print(message)
Tell me something,and I will repeat it back to you: Hello everyone!
Hello everyone!
name=input("Please enter your name: ")
print("Hello, "+name+"!")
print("--------------------------------")
prompt="If you tell us who you are,we can personalize the messages you see."
prompt+="\nWhat is your first name?"
name=input(prompt)
print("\nHello, "+name+"!")
Please enter your name: Eric
Hello, Eric!
--------------------------------
If you tell us who you are,we can personalize the messages you see.
What is your first name?Eric
Hello, Eric!
age=input("How old are you? ")
age=int(age)
print(age)
print(age>=18)
print("--------------")
height=input("How tall are you, in inches? ")
height=int(height)
if height>36:
print("\nYou're tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")
How old are you? 22
22
True
--------------
How tall are you, in inches? 71
You're tall enough to ride!
print(4%3)
print(5%3)
print(6%3)
print(7%3)
print("------------")
number=input("Enter a number, and I'll tell you if it's even or odd:")
number=int(number)
if number%2==0:
print("\nThe number "+str(number)+" is even.")
else:
print("\nThe number "+str(number)+" is odd.")
1
2
0
1
------------
Enter a number, and I'll tell you if it's even or odd:42
The number 42 is even.
current_number=1
while current_number<=5:
print(current_number)
current_number+=1
1
2
3
4
5
prompt="\nTell me something, and I will repeat it back to you:"
prompt+="\nEnter 'quit' to end the program."
message=''
while message !='quit':
message=input(prompt)
if message!='quit':
print(message)
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program.Hello everyone!
Hello everyone!
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program.Hello again
Hello again
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program.quit
prompt="\nTell me something, and I will repeat it back to you:"
prompt+="\nEnter 'quit' to end the program."
active=True
while active:
message=input(prompt)
if message=='quit':
active=False
else:
print(message)
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program.Hello everyone!
Hello everyone!
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program.Hello again
Hello again
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program.quit
prompt="\nPlease enter the name of a city you have visited:"
prompt+="\n(Enter 'quit' when you are finished.)"
while True:
city=input(prompt)
if city=='quit':
break
else:
print("I'd love to go to "+city.title()+"!")
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)New York
I'd love to go to New York!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)San Francisco
I'd love to go to San Francisco!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)quit
current_number=0
while current_number<10:
current_number+=1
if current_number%2==0:
continue
print(current_number)
1
3
5
7
9
x=1
while x<=5:
print(x)
#首先,创建一个待验证用户列表
#和一个用于存储已验证用户的空列表
unconfirmed_users=['alice','brian','candace']
confirmed_users=[]
#验证每个用户,直到没有未验证用户为止
#将每个经过验证的用户都移到已验证用户列表中
while unconfirmed_users:
current_user=unconfirmed_users.pop()
print("Verifying user: "+current_user.title())
confirmed_users.append(current_user)
#显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
pets=['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
responses={} # 设置一个标志,指出调查是否继续 polling_active=True while polling_active: #提示输入被调查者的名字和回答 name=input("\nWhat is your name? ") response=input("Which mountain would you like to climb someday?") #将答卷存储在字典中 responses[name]=response #看看是否还有人要参与调查 repeat=input("Would you like to let another person respond?(yes/no)") if repeat == 'no': polling_active=False #调查结束,显示结果 print("\n---Poll Result---") for name,response in responses.items(): print(name+" would like to climb "+response+".")
What is your name? Eric
Which mountain would you like to climb someday?Denali
Would you like to let another person respond?(yes/no)yes
What is your name? Lynn
Which mountain would you like to climb someday?Devil's Thumb
Would you like to let another person respond?(yes/no)no
---Poll Result---
Eric would like to climb Denali.
Lynn would like to climb Devil's Thumb.
def greet_user():
'''显示简单的问候语'''
print("Hello!")
greet_user()
Hello!
def greet_user(username):
"""显示简单的问候语"""
print("Hello, "+username.title()+"!")
greet_user("jeese")
Hello, Jeese!
def greet_user(username):##username:形参
"""显示简单的问候语"""
print("Hello, "+username.title()+"!")
greet_user("jeese")## jeese:实参
def describe_pet(animal_type,pet_name):
"""显示宠物的信息"""
print("\nI have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet("hamster",'harry')
I have a hamster.
My hamster's name is Harry.
def describe_pet(animal_type,pet_name):
"""显示宠物的信息"""
print("\nI have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet("hamster",'harry')
describe_pet("dog",'willie')
I have a hamster.
My hamster's name is Harry.
I have a dog.
My dog's name is Willie.
def describe_pet(animal_type,pet_name):
"""显示宠物的信息"""
print("\nI have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet("harry",'hamster')
I have a harry.
My harry's name is Hamster.
def describe_pet(animal_type,pet_name):
"""显示宠物的信息"""
print("\nI have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet(animal_type='hamster',pet_name="harry")
describe_pet(pet_name="harry",animal_type='hamster')
I have a hamster.
My hamster's name is Harry.
I have a hamster.
My hamster's name is Harry.
def describe_pet(pet_name,animal_type='dog'):
"""显示宠物的信息"""
print("\nI have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet(pet_name='willie')
describe_pet('willie')
I have a dog.
My dog's name is Willie.
I have a dog.
My dog's name is Willie.
def describe_pet(pet_name,animal_type='dog'):
"""显示宠物的信息"""
print("\nI have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
#一条名为Willlie的小狗
describe_pet("willie")
describe_pet(pet_name='willie')
#一只名为Harry的仓鼠
describe_pet('harry','hamster')
describe_pet(pet_name='harry',animal_type='hamster')
describe_pet(animal_type='hamster',pet_name='harry')
I have a dog.
My dog's name is Willie.
I have a dog.
My dog's name is Willie.
I have a hamster.
My hamster's name is Harry.
I have a hamster.
My hamster's name is Harry.
I have a hamster.
My hamster's name is Harry.
def get_formatted_name(first_name,last_name):
"""返回整洁的姓名"""
full_name=first_name+' '+last_name
return full_name.title()
musician=get_formatted_name('jimi','hendrix')
print(musician)
Jimi Hendrix
def get_formatted_name(first_name,last_name,middle_name=''):
"""返回整洁的姓名"""
if middle_name:
full_name=first_name+' '+middle_name+' '+last_name
else:
full_name=first_name+' '+last_name
return full_name.title()
musician=get_formatted_name('jimi','hendrix')
print(musician)
musician=get_formatted_name('john','hooker','lee')
print(musician)
Jimi Hendrix
John Lee Hooker
def build_person(first_name,last_name,age=''):
"返回一个字典,其中包含有关一个人的信息"
person={'first':first_name,'last':last_name}
if age:
person['age']=age
return person
musician=build_person('jimi','hendrix',age=27)
print(musician)
{'first': 'jimi', 'last': 'hendrix', 'age': 27}
def get_formatted_name(first_name,last_name):
"""返回整洁的姓名"""
full_name=first_name+' '+last_name
return full_name.title()
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any time to quit)")
f_name=input("First name: ")
if f_name=='q':
break
l_name=input("Last name: ")
if l_name=='q':
break
formatted_name=get_formatted_name(f_name,l_name)
print("\nHello, "+formatted_name +"!")
Please tell me your name:
(enter 'q' at any time to quit)
First name: eric
Last name: matthes
Hello, Eric Matthes!
Please tell me your name:
(enter 'q' at any time to quit)
First name: q
def greet_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg="Hello, "+name.title()+"!"
print(msg)
usernames=['hannah','ty','margot']
greet_users(usernames)
Hello, Hannah!
Hello, Ty!
Hello, Margot!
def print_models(unprinted_designs,completed_models): """ 模拟打印每个设计,直到没有未打印的设计为止 打印每个设计后,都将其移动到列表completed——models中 """ while unprinted_designs: current_design=unprinted_designs.pop() # 模拟根据设计制作3D打印模型的过程 print("Printing model: "+current_design) completed_models.append(current_design) def show_completed_models(completed_models): """显示打印好的所有模型""" print("\nThe following models have been printed: ") for completed_model in completed_models: print(completed_model) unprinted_designs=['iphone case','robot pendant','dodecahedron'] completed_models=[] print_models(unprinted_designs,completed_models) show_completed_models(completed_models)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case
The following models have been printed:
dodecahedron
robot pendant
iphone case
## 向函数传递列表的副本而不是原件;这样函数所做的任何修改都只影响副本,而丝毫不影响原件
function_name(list_name[:])
## 切片表示法[:]创建列表的副本
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("-"+topping)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
Making a pizza with the following toppings:
-pepperoni
Making a pizza with the following toppings:
-mushrooms
-green peppers
-extra cheese
def make_pizza(size,*toppings):
"""概述要制作的比萨"""
print("\nMaking a "+str(size)+"-inch pizza with the following toppings:")
for topping in toppings:
print("-"+topping)
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra toppings')
Making a 16-inch pizza with the following toppings:
-pepperoni
Making a 12-inch pizza with the following toppings:
-mushrooms
-green peppers
-extra toppings
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
user_profile=build_profile('albert','einstein',
location='princeton',
field='physics'
)
print(user_profile)
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
def make_pizza(size,*toppings):
"""概述要制作的比萨"""
print("\nMaking a "+str(size)+"-inch pizza with the following toppings:")
for topping in toppings:
print("-"+topping)
#将上述代码命名为pizza.py的文件
#用import pizza导入
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'mushrooms','green peppers','extra toppings')
导入方法的语法如下:
from module_name import function_name
若使用这种语法,调用函数时就无需使用句点
from module_name import function_name as fn
import module_name as mn
from pizza import *
由于导入了每个函数,可通过名称来调用每个函数,而无需使用句点表示法。
然而,这种用法并不建议使用!!!
因为模块中有函数的名称与你的项目中使用的名称相同,可能导致意想不到的结果。
class Dog():
'''一次模拟小狗的简单尝试'''
def __init__(self,name,age):
self.name=name
self.age=age
def sit(self):
'''模拟小狗被命令时蹲下'''
print(self.name.title()+" is now sitting.")
def roll_over(self):
'''模拟小狗被命令时打滚'''
print(self.name.title()+" rolled over!")
class Dog(): '''一次模拟小狗的简单尝试''' def __init__(self,name,age): self.name=name self.age=age def sit(self): '''模拟小狗被命令时蹲下''' print(self.name.title()+" is now sitting.") def roll_over(self): '''模拟小狗被命令时打滚''' print(self.name.title()+" rolled over!") my_dog=Dog('willie',6) print("My dog's name is "+my_dog.name.title()+".") print("My dog is "+str(my_dog.age)+" years old.")
My dog's name is Willie.
My dog is 6 years old.
my_dog.name
'willie'
my_dog.sit()
my_dog.roll_over()
Willie is now sitting.
Willie rolled over!
my_dog=Dog('willie',6)
your_dog=Dog('lucy',3)
print("My dog's name is "+my_dog.name.title()+".")
print("My dog is "+str(my_dog.age)+" years old.")
my_dog.sit()
print("\nYour dog's name is "+your_dog.name.title()+".")
print("Your dog is "+str(your_dog.age)+" years old.")
your_dog.sit()
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.
Your dog's name is Lucy.
Your dog is 3 years old.
Lucy is now sitting.
class Car():
'''一次模拟汽车的简单尝试'''
def __init__(self,make,model,year):
'''初始化描述汽车的属性'''
self.make=make
self.model=model
self.year=year
def get_descriptive_name(self):
'''返回整洁的描述性信息'''
long_name=str(self.year)+' '+self.make+' '+self.model
return long_name.title()
my_new_car=Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())
2016 Audi A4
class Car(): '''一次模拟汽车的简单尝试''' def __init__(self,make,model,year): '''初始化描述汽车的属性''' self.make=make self.model=model self.year=year self.odometer_reading=0 def get_descriptive_name(self): '''返回整洁的描述性信息''' long_name=str(self.year)+' '+self.make+' '+self.model return long_name.title() def read_odometer(self): '''打印一条指出汽车里程的消息''' print("This car has "+str(self.odometer_reading)+" miles on it.") my_new_car=Car('audi','a4',2016) print(my_new_car.get_descriptive_name()) my_new_car.read_odometer()
2016 Audi A4
This car has 0 miles on it.
class Car(): '''一次模拟汽车的简单尝试''' def __init__(self,make,model,year): '''初始化描述汽车的属性''' self.make=make self.model=model self.year=year self.odometer_reading=0 def get_descriptive_name(self): '''返回整洁的描述性信息''' long_name=str(self.year)+' '+self.make+' '+self.model return long_name.title() def read_odometer(self): '''打印一条指出汽车里程的消息''' print("This car has "+str(self.odometer_reading)+" miles on it.") my_new_car=Car('audi','a4',2016) print(my_new_car.get_descriptive_name()) my_new_car.read_odometer() my_new_car.odometer_reading=23 my_new_car.read_odometer()
2016 Audi A4
This car has 0 miles on it.
This car has 23 miles on it.
class Car(): '''一次模拟汽车的简单尝试''' def __init__(self,make,model,year): '''初始化描述汽车的属性''' self.make=make self.model=model self.year=year self.odometer_reading=0 def get_descriptive_name(self): '''返回整洁的描述性信息''' long_name=str(self.year)+' '+self.make+' '+self.model return long_name.title() def read_odometer(self): '''打印一条指出汽车里程的消息''' print("This car has "+str(self.odometer_reading)+" miles on it.") def update_odometer(self,mileage): '''将里程表读数设置为指定的值''' if mileage>=self.odometer_reading: self.odometer_reading=mileage else: print("You can't roll back an odometer!") my_new_car=Car('audi','a4',2016) print(my_new_car.get_descriptive_name()) my_new_car.update_odometer(23) my_new_car.read_odometer() my_new_car.update_odometer(13)
2016 Audi A4
This car has 23 miles on it.
You can't roll back an odometer!
class Car(): '''一次模拟汽车的简单尝试''' def __init__(self,make,model,year): '''初始化描述汽车的属性''' self.make=make self.model=model self.year=year self.odometer_reading=0 def get_descriptive_name(self): '''返回整洁的描述性信息''' long_name=str(self.year)+' '+self.make+' '+self.model return long_name.title() def read_odometer(self): '''打印一条指出汽车里程的消息''' print("This car has "+str(self.odometer_reading)+" miles on it.") def update_odometer(self,mileage): '''将里程表读数设置为指定的值 禁止将里程表读数往回填 ''' if mileage>=self.odometer_reading: self.odometer_reading=mileage else: print("You can't roll back an odometer!") def increment_odometer(self,miles): '''将里程表读数增加指定的量''' self.odometer_reading+=miles my_used_car=Car('subaru','outback',2013) print(my_used_car.get_descriptive_name()) my_used_car.update_odometer(23500) my_used_car.read_odometer() my_used_car.increment_odometer(100) my_used_car.read_odometer()
2013 Subaru Outback
This car has 23500 miles on it.
This car has 23600 miles on it.
class Car(): def __init__(self,make,model,year): self.make=make self.model=model self.year=year self.odometer_reading=0 def get_descriptive_name(self): long_name=str(self.year)+' '+self.make+' '+self.model return long_name.title() def read_odometer(self): print("This car has "+str(self.odometer_reading)+" miles on it.") def update_odometer(self,mileage): if mileage>=self.odometer_reading: self.odometer_reading=mileage else: print("You can't roll back an odometer!") def increment_odometer(self,miles): self.odometer_reading+=miles class ElectricCar(Car): '''电动汽车的独特之处''' def __init__(self,make,model,year): '''初始化父类的属性''' super().__init__(make,model,year) my_tesla=ElectricCar('tesla','model s',2016) print(my_tesla.get_descriptive_name())
2016 Tesla Model S
class Car(): def __init__(self,make,model,year): self.make=make self.model=model self.year=year self.odometer_reading=0 def get_descriptive_name(self): long_name=str(self.year)+' '+self.make+' '+self.model return long_name.title() def read_odometer(self): print("This car has "+str(self.odometer_reading)+" miles on it.") def update_odometer(self,mileage): if mileage>=self.odometer_reading: self.odometer_reading=mileage else: print("You can't roll back an odometer!") def increment_odometer(self,miles): self.odometer_reading+=miles class ElectricCar(Car): '''电动汽车的独特之处 初始化父类的属性,再初始化电动汽车特有的属性 ''' def __init__(self,make,model,year): '''初始化父类的属性''' super().__init__(make,model,year) self.battery_size=70 def describe_battery(self): """打印一条描述电瓶容量的消息""" print("This car has a "+str(self.battery_size)+"-kwh battery.") my_tesla=ElectricCar('tesla','model s',2016) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery()
2016 Tesla Model S
This car has a 70-kwh battery.
class ElectricCar(Car): '''电动汽车的独特之处 初始化父类的属性,再初始化电动汽车特有的属性 ''' def __init__(self,make,model,year): '''初始化父类的属性''' super().__init__(make,model,year) self.battery_size=70 def describe_battery(self): """打印一条描述电瓶容量的消息""" print("This car has a "+str(self.battery_size)+"-kwh battery.") def fill_gas_tank(self): '''电动汽车没有油箱''' print("This car does't need a gas tank") my_tesla=ElectricCar('tesla','model s',2016) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery() my_tesla.fill_gas_tank()
2016 Tesla Model S
This car has a 70-kwh battery.
This car does't need a gas tank
class 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) class ElectricCar(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()
2016 Tesla Model S
This car has a 70-kwh battery.
This car can go approximately 240 miles on a full charge
"""一个可用于表示汽车的类""" class Car(): """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): """初始化描述汽车的属性""" self.make = make self.model = model self.yaer = year self.odometer_reading = 0 def get_descriptive_name(self): """返回整洁的描述性名称""" long_name = str(self.yaer) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """打印一条消息,指出汽车的里程""" print("This car has " + str(self.odometer_reading) + " miles on it.") def upgrade_odometer(self, mileage): """ 将里程表读数设置为指定的值 拒绝将里程表往回拨 """ if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): """将里程表读数增加指定的量""" self.odometer_reading += miles
运行如下代码:
from car import Car
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
运行结果如下:
"""一个可用于表示燃油汽车和电动汽车的类""" class Car(): """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): """初始化描述汽车的属性""" self.make = make self.model = model self.yaer = year self.odometer_reading = 0 def get_descriptive_name(self): """返回整洁的描述性名称""" long_name = str(self.yaer) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """打印一条消息,指出汽车的里程""" print("This car has " + str(self.odometer_reading) + " miles on it.") def upgrade_odometer(self, mileage): """ 将里程表读数设置为指定的值 拒绝将里程表往回拨 """ if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): """将里程表读数增加指定的量""" self.odometer_reading += miles class 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) class ElectricCar(Car): """模拟电动汽车的独特之处""" def __init__(self,make,model,year): """ 初始化父类的属性,再初始化电动汽车特有的属性 """ super().__init__(make, model, year) self.battery=Battery()
from car import ElectricCar
my_tesla=ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
运行结果如下:
from car import Car,ElectricCar
my_beetle=Car('volkswagen','bettle',2016)
print(my_beetle.get_descriptive_name())
my_tesla=ElectricCar('tesla','roadster',2016)
print(my_tesla.get_descriptive_name())
2016 Volkswagen Bettle
2016 Tesla Roadster
import car
my_beetle=car.Car('volkswagen','beetle',2016)
print(my_beetle.get_descriptive_name())
my_tesla=car.ElectricCar('tesla','roadster',2016)
print(my_tesla.get_descriptive_name())
2016 Volkswagen Beetle
2016 Tesla Roadster
from module_name import *
from collections import OrderedDict
favorite_languages=OrderedDict()
favorite_languages['jen']='python'
favorite_languages['sarah']='c'
favorite_languages['edward']='ruby'
favorite_languages['phil']='python'
for name,language in favorite_languages.items():
print(name.title()+"'s favorite language is "+language.title()+'.')
from collections import OrderedDict
favorite_languages=OrderedDict()
favorite_languages['jen']='python'
favorite_languages['sarah']='c'
favorite_languages['edward']='ruby'
favorite_languages['phil']='python'
for name,language in favorite_languages.items():
print(name.title()+"'s favorite language is "+language.title()+'.')
with open('pi_digits.txt')as file_object:
contents=file_object.read()
print(contents)
print(contents.rstrip())
3.1415926535
8979323846
2643383279
3.1415926535
8979323846
2643383279
file_path='C:\Users\ehmatthes\other\files\text_files\filename.txt'
with open(file_path)as file_object:
filename='pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
3.1415926535
8979323846
2643383279
3.1415926535
8979323846
2643383279
filename='pi_digits.txt'
with open(filename) as file_object:
lines=file_object.readlines()
for line in lines:
print(line.rstrip())
3.1415926535
8979323846
2643383279
filename='pi_digits.txt'
with open(filename) as file_object:
lines=file_object.readlines()
pi_string_1=''
pi_string_2=''
for line in lines:
pi_string_1+=line.rstrip()
pi_string_2+=line.strip()
print(pi_string_1)
print(len(pi_string_1))
print(pi_string_2)
print(len(pi_string_2))
3.1415926535 8979323846 2643383279
36
3.141592653589793238462643383279
32
filename='pi_million_digits.txt'
with open(filename)as file_object:
lines=file_object.readlines()
pi_string=''
for line in lines:
pi_string+=line.strip()
print(pi_string[:52]+"...")
print(len(pi_string))
3.14159265358979323846264338327950288419716939937510...
1000002
filename='pi_million_digits.txt'
with open(filename)as file_object:
lines=file_object.readlines()
pi_string=''
for line in lines:
pi_string+=line.strip()
birthday=input("Enter your birthday,In the form mmddy:")
if birthday in pi_string:
print("Your birthday appears in the first million digits of pi!")
else:
print("Your birthday does not appear in the first million figits of pi.")
Enter your birthday,In the form mmddy:041900
Your birthday appears in the first million digits of pi!
filename='programming.txt'
with open(filename,'w') as file_object:
file_object.write("I love programming.")
filename='programming.txt'
with open(filename,'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")
filename='programming.txt'
with open(filename,'a') as file_object:
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")
print(5/0)
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_2232\785342039.py in <module>
----> 1 print(5/0)
ZeroDivisionError: division by zero
try:
print(5/0)
except:
print("You can't divide by zero!")
You can't divide by zero!
print("Give me two numbers: and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number=input("\nFirst number: ")
if first_number=='q':
break
second_number=input("Second number: ")
if second_number=='q':
break
answear=int(first_number)/int(second_number)
print(answear)
Give me two numbers: and I'll divide them.
Enter 'q' to quit.
First number: 1
Second number: 0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_2232\744485532.py in <module>
10 if second_number=='q':
11 break
---> 12 answear=int(first_number)/int(second_number)
13 print(answear)
ZeroDivisionError: division by zero
print("Give me two numbers: and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number=input("\nFirst number: ")
if first_number=='q':
break
second_number=input("Second number: ")
try:
answear=int(first_number)/int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answear)
Give me two numbers: and I'll divide them.
Enter 'q' to quit.
First number: 5
Second number: 0
You can't divide by 0!
First number: 5
Second number: 2
2.5
First number: q
filename='alice.txt'
try:
with open(filename) as f_obj:
contents=f_obj.read()
except FileNotFoundError:
msg="Sorry, the file "+filename+" does not exist."
print(msg)
Sorry, the file alice.txt does not exist.
filename='alice.txt'
try:
with open(filename) 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=len(words)
print("The file "+filename+" has about "+str(num_words)+" words.")
The file alice.txt has about 29461 words.
def count_words(filename): """计算一个文件大致包含多少个单词""" try: with open(filename) 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=len(words) print("The file "+filename+" has about "+str(num_words)+" words.") filenames=['alice.txt','siddhartha.txt','moby_dict.txt','little_women.txt'] for filename in filenames: count_words(filename)
The file alice.txt has about 29461 words.
Sorry, the file siddhartha.txt does not exist.
The file moby_dict.txt has about 215136 words.
The file little_women.txt has about 189079 words.
def count_words(filename): """计算一个文件大致包含多少个单词""" try: with open(filename) as f_obj: contents=f_obj.read() except FileNotFoundError: pass else: #计算文件大致包含多少个单词 words=contents.split() num_words=len(words) print("The file "+filename+" has about "+str(num_words)+" words.") filenames=['alice.txt','siddhartha.txt','moby_dict.txt','little_women.txt'] for filename in filenames: count_words(filename)
The file alice.txt has about 29461 words.
The file moby_dict.txt has about 215136 words.
The file little_women.txt has about 189079 words.
import json
numbers=[2,3,5,7,9,11,13]
filename='numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)
import json
numbers=[2,3,5,7,9,11,13]
filename='numbers.json'
with open(filename,'r') as f_obj:
numbers=json.load(f_obj)
print(numbers)
[2, 3, 5, 7, 9, 11, 13]
import json # 如果以前存储了用户名,就加载它 #否则,就提示用户输入用户名并存储它 filename='username.json' try: with open(filename)as f_obj: username=json.load(f_obj) except FileNotFoundError: username=input("What is your name?") with open(filename,'w') as f_obj: json.dump(username,f_obj) print("We'll remember you when you come back, "+username+"!") else: print("Welcome back, "+username+"!")
What is your name?Eric
We'll remember you when you come back, Eric!
import json def greet_user(): """问候用户,并指出其名字""" filename='username.json' try: with open(filename)as f_obj: username=json.load(f_obj) except FileNotFoundError: username=input("What is your name?") with open(filename,'w') as f_obj: json.dump(username,f_obj) print("We'll remember you when you come back, "+username+"!") else: print("Welcome back, "+username+"!") greet_user()
Welcome back, Eric!
import json def get_stored_username(): """如果存储了用户名,就获取它""" filename='username.json' try: with open(filename)as f_obj: username=json.load(f_obj) except FileNotFoundError: return None else: return username def get_user_username(): """提示用户输入用户名""" username=input("What is your name?") filename='username.json' with open(filename,'w') as f_obj: json.dump(username,f_obj) return username def greet_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()
Welcomg back, Eric!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。