我如何回到循环的开始?

问题描述 投票:0回答:2

如果问题持续很长时间,我深表歉意。我会尽量简洁。

问题:编写一个程序,将估算的重量(千克)转换为磅。如果用户输入负值,则程序应要求玩家重新输入数字。

我创建了三个功能。第一个功能-返回玩家输入第二功能-以磅为单位返回重量第三个功能-如果重量为正值,则返回以磅为单位的值,如果负值,则要求另一个输入。

 # 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 () )

如果相同的值为正,我的程序将返回正确的值。但是,当我输入一个负浮点数时,我的程序将永远打印“无效重量”。当我在循环中继续写时,我被告知要返回到同一循环的开始,但是我无法停止程序。

python while-loop break continue
2个回答
1
投票

其打印“无效重量”的原因。永远是因为您只接受一次输入,并且每次都使用它,即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 () )

提示:如果使用函数,请不要使用全局变量。它们将保留最后的值,如果您的代码需要在每次调用中更改/重置它们,则它们将保留。首选使用功能参数


0
投票

continue语句仅在当前迭代时用于跳过循环内的其余代码。循环不会终止,但会继续进行下一次迭代。

break语句终止包含它的循环。程序的控制权在循环体之后立即传递到该语句。如果break语句位于嵌套循环(另一个循环内的循环)内,则break将终止最内部的循环。

因此,在使用continue的情况下,您只需返回错误的输入就返回while

您只需要输入一次,当输入错误时就需要输入agian。

© www.soinside.com 2019 - 2024. All rights reserved.