通过python,编写一个篮球运动员初选功能的代码:
1、提示输入姓名;
2、提示输入身高;
如果身高大于等于 180 入选,
如果身高小于等于 180 落选,
3、把入选的与落选的人,通过字典+列表保存起来
4、最后打印初选结果!
脚本——
import sys
V1 = []
V2 = []
dict1 ={
'Selected':V1,
'Uselected':V2
}
while True:
print("Welcome to the screening process")
choose = input ("Enter yes or no: ")
if choose.upper() == 'NO':
break
if choose.upper() == 'YES':
name = input("Enter sb's name: ")
if name.upper() == 'QUIT':
exit()
else:
pass
height = input("Enter sb's height: ")
if height.upper() == 'QUIT':
exit()
elif int(height) < 180:
print("Not suitable for basketball! ")
dict1['Selected'].append(name)
else:
print("Welcome to our training with the team")
dict1['Uselected'].append(name)
else:
continue
print(dict1)
思路:
1、定义两个空列表,‘V1’‘V2’
2、在执行判断的时候,根据判断结果往列表中进行数据添加
执行效果:
Welcome to the screening process
Enter yes or no: yes
Enter sb's name: james
Enter sb's height: 210
Welcome to the screening process
Enter yes or no: yes
Enter sb's name: tom
Enter sb's height: 140
Not suitable for basketball!
Welcome to the screening process
Enter yes or no: yes
Enter sb's name: harden
Enter sb's height: 190
Welcome to the screening process
Enter yes or no: no
{'Selected': ['tom'], 'Uselected': ['james', 'harden']}
通过默认字典的方法,来优化代码:
仅仅摘列修改部分——
from collections import defaultdict
dict1 = defaultdict(list)
不再需要事先创建空列表与字典了