如何循环以防止错误的用户输入?

时间:2017-12-10 01:23:22

标签: python loops integer

  

大家好!我的目标是循环年龄,以便正确地打印male_cal或fem_cal(隐式)。请帮忙!非常感谢 - > Pythonidaer< -

print("\nWelcome to the Daily Caloric Intake Calculator!")

我不知道如何像我做爱一样循环年龄。

age = int(input("\nHow old are you in years? "))

sex = input("\nAre you a male or a female? Enter 'male' or 'female'. ").lower()
if sex == "female" or sex == "f":
    sex = "female"
elif sex == "male" or sex == "m":
    sex = "male"
else:
    sex = input("Sorry, there's only two choices: MALE or FEMALE. ").lower()

等式要求年龄为整数。我怎么能万无一失?

height = float(input("\nHow tall are you in inches? "))
metric_height = float(height * 2.54)
weight = float(input("\nWhat is your weight in pounds? "))
metric_weight = int(weight * 0.453592)


activity_level = float(input("""
Please select your activity level:

Sedentary (enter '1.2')
Moderatively Active (enter '1.3')
Active? (enter '1.4')

"""))

male_cal = 10 * metric_weight + 6.25 * metric_height - 5 * age - 161
fem_cal = 10 * metric_weight + 6.25 * metric_height - 5 * age + 5

if (sex == "male"):

carbs = int(male_cal * .45)
protein = int(male_cal * .20)
fats = int(male_cal * .35)
print("\nYour DCI should be: ", int(male_cal), "calories a day.")
print(f"""\nThat means getting:
{carbs} cals from carbs, 
{fats} cals from fats, and 
{protein} cals from protein.""")
elif (sex == "female"):

carbs = int(fem_cal * .45)
protein = int(fem_cal * .20)
fats = int(fem_cal * .35)
print("\nYour DCI should be: ", int(fem_cal), "calories a day.")
print(f"""\nThat means getting:
{carbs} cals from carbs, 
{fats} cals from fats, and 
{protein} cals from protein.""")

1 个答案:

答案 0 :(得分:0)

while True:
    try:
        age = int(input("\nHow old are you in years? "))
        break
    except ValueError:
        print('please put in a number')

这应该做的伎俩