关于python:该程序计算一个人的BMI。 如何在不使用其他条件循环的情况下阻止用户输入零?

This program calculates the BMI of a person. How can I prevent user from inputting a zero without having to use another conditional loop?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
flag='yes'
#while loop for reccursion
while flag != 'no':
    print ("
 BMI Calculator"
)
    #Exception block for catching non integer inputs
    try:
        #Prompting user to input weight
        weight = int(input('Enter your weight in pounds : '))
        while weight == 0:
            sys.exit()
    except ValueError:
        print ('Oops!! Kindly enter only numbers.')
        flag = input('Do you want to try again? yes/no : ')
        continue

    try:
        #Prompting user to input height
        height = float(input('Enter your height in inches : '))
        while height == 0:
            sys.exit()
    except ValueError:
        print ('Oops!! Kindly enter only numbers.')
        flag = input('Do you want to try again? yes/no : ')
        continue

    #Function for calculating BMI    
    def bmi_calculator():
        #Exception block for catching division by zero
        try:
            #Formula for calculating BMI
            BMI = round(weight * 703/(height*height), 2)
            return (BMI)
        except ZeroDivisionError:
            print ('Oops!! Cannot divide by zero.')
            sys.exit()

是否有任何异常处理可用于仅接受非零输入? 有没有办法避免另一个while或if循环?


如果要正确处理0个数字,其中一种方法是在输入0时引发异常:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#Function for calculating BMI    
def bmi_calculator():
    flag='yes'
    while flag != 'no':
        print ("
 BMI Calculator"
)
        #Exception block for catching non integer inputs
        try:
            #Prompting user to input weight
            weight = int(input('Enter your weight in pounds : '))
            if weight == 0:
                raise ValueError
        except ValueError:
            print ('Oops!! Kindly enter non-zero numbers only.')
            flag = input('Do you want to try again? yes/no : ')
            continue

        try:
            #Prompting user to input height
            height = float(input('Enter your height in inches : '))
            if height == 0:
                raise ValueError
        except ValueError:
            print ('Oops!! Kindly enter non-zero numbers only.')
            flag = input('Do you want to try again? yes/no : ')
            continue

        #Formula for calculating BMI
        BMI = round(weight * 703/(height*height), 2)
        return (BMI)

print(bmi_calculator())

我还用if语句替换了while weight == 0while height == 0 - 它们看起来更合适,我将main while循环放在函数defintion bmi_calculator中,这样就可以在需要时调用它。