5-2 更多的条件测试
代码:
# test1
str1 = "abc"
print(str1 == "abc")
# test2
str2 = "ABC"
print(str2.lower() == "abc")
# test3
print(1.5 == 1.5)
print(1.5 != 1.5)
print(1.5 >= 1.5)
print(3 > 2)
print(3 < 2)
print(1 <= 2)
# test4
age1 = 23
age2 = 21
print(age1>=23 and age2>=22)
print(age1>22 or age2>22)
# test5
names = ['Mike','Joey','Peter']
print('Peter' in names)
print('Peter' not in names)
运行结果:
5-5 外星人颜色#3
代码:
#test1
alien_color = 'red'
if alien_color == 'green':
print("You just earned 5 points!")
elif alien_color == 'yellow':
print("You just earned 10 points!")
else:
print("You just earned 15 points!")
#test2
alien_color = 'yellow'
if alien_color == 'green':
print("You just earned 5 points!")
elif alien_color == 'yellow':
print("You just earned 10 points!")
else:
print("You just earned 15 points!")
#test3
alien_color = 'green'
if alien_color == 'green':
print("You just earned 5 points!")
elif alien_color == 'yellow':
print("You just earned 10 points!")
else:
print("You just earned 15 points!")
运行结果:
5-7 喜欢的水果
代码:
favorite_fruits = ['apples','bananas','pears']
if 'apples' in favorite_fruits:
print("You really like apples!")
if 'bananas' in favorite_fruits:
print("You really like bananas!")
if 'pears' in favorite_fruits:
print("You really like pears!")
if 'grapes' in favorite_fruits:
print("You really like grapes!")
if 'mangos' in favorite_fruits:
print("You really like mangos!")
运行结果:
5-9 处理没有用户的情形
代码:
usernames = ['admin','Mike','Eric','Joey','Sid']
if usernames:
for username in usernames:
if username == 'admin':
print("Hello admin, would you like to see a status report?")
else:
print("Hello " + username + ", thank you for logging in again.")
else:
print("We need to find some users!")
usernames = []
if usernames:
for username in usernames:
if username == 'admin':
print("Hello admin, would you like to see a status report?")
else:
print("Hello " + username + ", thank you for logging in again.")
else:
print("We need to find some users!")
运行结果:
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")
运行结果: