Python3 学习笔记(四)if语句
参考书籍《Python编程:从入门到实践》【美】Eric Matthes
假设在游戏中刚射杀了一个外星人,请创建一个名为alien_color 的变量,并将其设置为’green’ 、’yellow’ 或’red’ 。编写一条if 语句,如果外星人是绿色的,就打印一条消息,指出玩家获得了5个点。如果外星人是黄色的,就打印一条消息,指出玩家获得了10个点。如果外星人是红色的,就打印一条消息,指出玩家获得了15个点。
alien_color = 'yellow'
if alien_color == 'green':
print('You get 5 score')
elif alien_color == 'yellow':
print('You get 10 score')
else:
print('You get 15 score')
创建一个列表,其中包含你喜欢的水果,再编写一系列独立的if 语句,检查列表中是否包含特定的水果。将该列表命名为favorite_fruits ,并在其中包含三种水果。编写5条if 语句,每条都检查某种水果是否包含在列表中,如果包含在列表中,就打印一条消息。
favorite_fruits = ['apple', 'orange', 'pear']
if 'apple' in favorite_fruits:
print('You really like apple')
if 'banana' in favorite_fruits:
print('You really like banana')
if 'peak' in favorite_fruits:
print('You really like peak')
if 'orange' in favorite_fruits:
print('You really like orange')
if 'pear' in favorite_fruits:
print('You really like pear')
创建一个至少包含5个用户名的列表,且其中一个用户名为’admin’ 。想象你要编写代码,在每位用户登录网站后都打印一条问候消息。遍历用户名列表,并向每位用户打印一条问候消息。如果用户名为’admin’ ,就打印一条特殊的问候消息,如“Hello admin, would you like to see a status report?”。否则,打印一条普通的问候消息,如“Hello Eric, thank you for logging in again”。
users = ['cannon', 'admin', 'leg', 'god', 'universe']
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')
检查用户名列表是否为空。如果为空,就打印消息“We need to find some users!”。
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!')
按下面的说明编写一个程序,模拟网站确保每位用户的用户名都独一无二的方式。创建一个至少包含5个用户名的列表,并将其命名为current_users 。再创建一个包含5个用户名的列表,将其命名为new_users ,并确保其中有一两个用户名也包含在列表current_users 中。遍历列表new_users ,对于其中的每个用户名,都检查它是否已被使用。如果是这样,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指出这个用户名未被使用。确保比较时不区分大消息;换句话说,如果用户名’John’ 已被使用,应拒绝用户名’JOHN’ 。
current_users = ['cannon', 'admin', 'leg', 'gOd', 'universe']
new_users = ['ran', 'azen', 'Leg', 'GOD', 'cat']
for new_user in new_users:
for current_user in current_users:
if new_user.title() == current_user.title():
print('This name ' + new_user + ' has been used')
序数表示位置,如1st和2nd。大多数序数都以th结尾,只有1、2和3例外。在一个列表中存储数字1~9。遍历这个列表。在循环中使用一个if-elif-else 结构,以打印每个数字对应的序数。输出内容应为1st 、2nd 、3rd 、4th 、5th 、6th 、7th 、8th 和9th ,但每个序数都独占一行。
for value in range(1,10):
if value == 1:
print(str(value) + 'st')
elif value == 2:
print(str(value) + 'nd')
elif value == 3:
print(str(value) + 'rd')
else:
print(str(value) + 'th')