如果我的问题看起来很长,我深表歉意。我会尽量简洁。
问题:编写一个程序,将估算的重量(公斤)转换为磅。如果用户输入负值,程序应要求玩家重新输入数字。
我创建了三个函数。 第一个函数 - 返回玩家输入 第二个函数 - 返回以磅为单位的重量 第三个函数 - 如果重量为正,则返回以磅为单位的值;如果重量为负,则要求另一个输入。
# function that asks for player input in kg
def weight_input () :
return float (input ("Enter valid weight: "))
weight_kg = weight_input()
# formula to convert kg into pounds
def weight_conversion():
return 2.2 * weight_kg
weight_pds = weight_conversion ()
def weight_info () :
while True :
weight_kg
if weight_kg > 0 : # if weight > 0 we return the weight in pds
return weight_pds
else :
print("Invalid weight.")
continue # go back to the start of the loop and ask for input
return weight_pds
print (weight_info () )
如果相同的值为正值,我的程序将返回正确的值。然而,当我输入负 float 时,我的程序永远打印“无效重量”。有人告诉我,每当我在循环内写入 continue 时,我都会返回到同一循环的开头,但是我无法停止我的程序。
最佳答案
打印“无效重量”的原因。永远因为您只接受一次输入并每次都使用它,即一旦输入,weight_kg就永远不会更新。
尝试代码
# function that asks for player input in kg
def weight_input () :
return float (input ("Enter valid weight: "))
# formula to convert kg into pounds
def weight_conversion(weight_kg):
return 2.2 * weight_kg
def weight_info () :
while True :
weight_kg = weight_input()
if weight_kg > 0 : # if weight > 0 we return the weight in pds
return weight_conversion (weight_kg)
else :
print("Invalid weight.")
continue # go back to the start of the loop and ask for input
return weight_pds
print (weight_info () )
提示:如果使用函数,请勿使用全局变量。它们将保留最后的值,如果您的代码需要它们在每次调用中更改/重置,则更喜欢使用函数参数
关于python - 我怎样才能回到循环的开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58538595/