Chapter 5
# 5-1 条件测试
for i in range(10):
print(i%2==0)
True
False
True
False
True
False
True
False
True
False
# 外星人颜色#1
alien_color = 'green'
if alien_color == 'green':
print("+5")
alien_color = 'red'
if alien_color == 'green':
print("Wrong!")
+5
# 外星人颜色#2
def f(alien_color):
if alien_color == 'green':
print("shot green, +5")
else:
print("+10")
f('green')
f('red')
shot green, +5
+10
# 外星人颜色#2
def f1(alien_color):
if alien_color == 'green':
print('+5')
elif alien_color == 'yellow':
print('+10')
elif alien_color == 'red':
print('+15')
colors = ['green', 'yellow', 'red']
for color in colors:
f1(color)
+5
+10
+15
# 5-8 以特殊方式跟管理员打招呼
userList = ['Tom', 'Jerry', 'admin', 'Amy', 'Ben']
for user in userList:
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 Tom, thank you for logging in again
Hello Jerry, thank you for logging in again
Hello admin, would you like to see a status report?
Hello Amy, thank you for logging in again
Hello Ben, thank you for logging in again
Chapter 6
# 6-1 人
person = {'first_name': 'Taiga', 'last_name': 'Geass', 'city':'GZ'}
for key, value in person.items():
print(key, value)
first_name Taiga
last_name Geass
city GZ
# 6-7 人
person1 = {'first_name': 'Taiga', 'last_name': 'Geass', 'city':'GZ'}
person2 = {'first_name': 'Gaici', 'last_name': 'Bier', 'city':'AM'}
person3 = {'first_name': 'Big', 'last_name': 'Bang', 'city':'NY'}
people = [person1, person2, person3]
for person in people:
for key,value in person.items():
print(key,':', value)
first_name : Taiga
last_name : Geass
city : GZ
first_name : Gaici
last_name : Bier
city : AM
first_name : Big
last_name : Bang
city : NY
# 6-7 喜欢的地方
favorite_places = {
'Tom': ['Beijing', 'Shanghai', 'Fujian'],
'Jerry': ['Guangzhou'],
'Ben': ['Sichuan', 'Hong Kong']
}
for key, value in favorite_places.items():
print(key, value)
Tom ['Beijing', 'Shanghai', 'Fujian']
Jerry ['Guangzhou']
Ben ['Sichuan', 'Hong Kong']
# 6-11 城市
cities = {
'Xiamen': {'country': 'China', 'population': '500w', 'fact': 'Beautiful'},
'Guangzhou': {'country': 'China', 'population': '1000w', 'fact': 'Beautiful'},
'Hong Kong': {'country': 'China', 'population': '100w', 'fact': 'Good'}
}
for key, value in cities.items():
print(key + ':')
for key0, value0 in value.items():
print(key0 + ':', value0)
print('-----')
Xiamen:
country: China
population: 500w
fact: Beautiful
-----
Guangzhou:
country: China
population: 1000w
fact: Beautiful
-----
Hong Kong:
country: China
population: 100w
fact: Good
-----