如何创建return到x?

How to create return to x?

while True:
        print("Welcome to this BMI calculator")
        x = str(input("Are you using Pounds or Kg, if you are using Kg press K if you are using Pounds press P:"))
        if x in ['P', 'p']:
            h = float(input("Key in your weight:"))

        elif x in ['K', 'k']:
            h = float(input("Key in your weight:"))

        else:
            **return(x)**
            print(x)
   

Bold indicates error and how to return if the user does not key in any of the characters (P/p/K/k)

据我了解,您想获取用户输入和 return 值 - 可能来自函数?然后,如果您打算在您的代码中进一步使用它们,您应该考虑 return 同时使用 xh

def input_weight():
    """Ask user for their weight and the metric system they want to use"""
    
    
    while True:
        x = input("Are you using Pounds or Kg, if you are using Kg press K if you are using Pounds press P:")
        
        if x in ['P', 'p', 'K', 'k']:
            break # user has provided correct metric
        else:
            print(x + " is not valid. try again")
            
    while True:
        try:
            h = float(input("Key in your weight:"))
        except ValueError:
            print("sorry this is not a valid weight. try again")
            continue
        else:
            break
            
    return h, x

print("Welcome to this BMI calculator")
h, x = input_weight()
print(h, x)

您可能还想查看 this answer。您的代码中有几个因素必须修改或更改。

说明

如你所见,函数input_weight().

中使用了两个while循环
  1. 第一个循环将继续询问用户公制系统,如果用户输入的不是 ['P', 'p', 'K', 'k'] 以外的任何内容,则循环将重新运行,提示用户输入错误。
  2. 同样,第二个循环询问用户体重。如果重量不是数字,那么它会继续要求用户提供正确的输入。