【问题标题】:How to create return to x?如何创建返回 x?
【发布时间】:2022-01-07 17:35:10
【问题描述】:
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)
   

粗体表示错误 以及如果用户没有输入任何字符如何返回(P/p/K/k)

【问题讨论】:

  • 就目前而言,问题在于这不是一个函数。你不能从不是函数的东西返回。你打算让它成为一个功能吗?为什么你还想回来?你打算对用户的输入做些什么吗?
  • input 总是返回一个字符串。在那里打电话str()是没有意义的。
  • 是的,我打算对用户输入做一些事情。是的,我打算让它成为一个函数。
  • 一旦你把它变成一个函数,return 就可以工作了。
  • 你想让return做什么?您是否要让执行回到x = ... 行?

标签: python if-statement while-loop return


【解决方案1】:

据我了解,您想获取用户输入并返回值 - 可能来自函数?如果您打算在代码中进一步使用它们,那么您应该考虑返回 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-loop。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-15
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 2022-01-14
    相关资源
    最近更新 更多