5-2 更多的测试条件
#检查字符串相等和不等,lower()的测试
cars = ["audi","BMW","Subaru","toyato"]
for car in cars:
if car.lower() == 'bmw':
print(car.upper())
else:
print(car.title())
#检查特定值在不在列表中
car = 'pheonix'
if car not in cars:
print(car.title() + " is not in car list")
car = 'toyato'
if car in cars:
print(car.upper() + " is in car list")
输出结果为:
Audi
BMW
Subaru
Toyato
Pheonix is not in car list
TOYATO is in car list
5-5 外星人颜色
alien_color = ["green","yellow","red"]
for alien in alien_color:
if alien == "green":
print("You get 5 points")
elif alien == "yellow":
print("You get 10 points")
else:
print("You get 15 points")
输出结果为:
You get 5 points
You get 10 points
You get 15 points
5-6 人生的不同阶段
ages = [1,3,9,18,35,92]
for age in ages:
if age < 2:
print("年龄是"+str(age)+",他是婴儿")
elif age < 4:
print("年龄是"+str(age)+",他正蹒跚学步")
elif age < 13:
print("年龄是"+str(age)+",他是儿童")
elif age < 20:
print("年龄是"+str(age)+",他是青少年")
elif age < 65:
print("年龄是"+str(age)+",他是成年人")
else:
print("年龄是"+str(age)+",他是老年人")
输出结果为:
年龄是1,他是婴儿
年龄是3,他正蹒跚学步
年龄是9,他是儿童
年龄是18,他是青少年
年龄是35,他是成年人
年龄是92,他是老年人
5-8,5-10 检查用户名
current_users = ["admin","eric","lilei","hanmeimei","madongmei"]
new_users = ["Alexander","nepoleon","john","LILEI","admin"]
for i in range(0,len(new_users)):
if new_users[i].lower() == 'admin':
print("Hello admin, would you like to see a status report")
elif new_users[i].lower() not in current_users:
print("Hello " + new_users[i] +", thank you for logging in again")
else:
judge = True;
while(judge):
name = input("该用户名 " + new_users[i] + "已被使用,请输入其他名字: ")
if name.lower() not in current_users:
current_users.append(name.lower())
judge = False
print("Hello " + name +", thank you for logging in again")
输出结果为:
Hello Alexander, thank you for logging in again
Hello nepoleon, thank you for logging in again
Hello john, thank you for logging in again
该用户名 LILEI已被使用,请输入其他名字: susan
Hello susan, thank you for logging in again
Hello admin, would you like to see a status report
5-11 序数
lists = [i for i in range(1,10)]
for num in lists:
if num == 1:
print("1st")
elif num == 2:
print("2nd")
elif num == 3:
print("3rd")
else:
print(str(num)+"th")
输出结果为:
1st
2nd
3rd
4th
5th
6th
7th
8th
9th