我需要添加一个try / except用户拼错单词" Male"或者"女性。"
以下是我现在在代码中的使用方法,但是我的作业要求我加入试试/除了错误拼写的"男性"或者"女性。"我使用的以下try / except代码帮助解决了用户输入单词的年龄而不是拼错他们的性别的问题。
感谢任何帮助。
fem_names = []
fem_ages = []
male_names = []
male_ages = []
while True:
try:
name = raw_input('Enter name:')
age = raw_input('Enter age:')
sex = raw_input('Enter female or male:')
if (sex == 'female'):
fem_names.append(name)
fem_ages.append(float(age))
else:
male_names.append(name)
male_ages.append(float(age))
reply = raw_input('Type yes to continue or no to stop:')
if (reply == "no"):
break
except Exception:
print('Please enter correct information')
tot_fem = len(fem_names)
tot_fem_ages = sum(fem_ages)
if(tot_fem == 0):
avg_fem_age = 0.0
else:
avg_fem_age = tot_fem_ages/tot_fem
tot_male = len(male_names)
tot_male_ages = sum(male_ages)
if(tot_male == 0):
avg_male_age = 0.0
else:
avg_male_age = tot_male_ages/tot_male
print "There are", tot_fem , "total females with an average age of" , avg_fem_age, "years."
print "There are", tot_male , "total males with an average age of" , avg_male_age, "years."
答案 0 :(得分:0)
你可以先检查一下性别'使用' if'
sex = raw_input('Enter female or male:')
if sex in ['male', 'female']:
if (sex == 'female'):
fem_names.append(name)
fem_ages.append(float(age))
else:
male_names.append(name)
male_ages.append(float(age))
else:
# raise error here
print "invalid sex"