簡體   English   中英

我怎樣才能 go 回到循環的開始?

[英]How can i go back to the start of the loop?

如果我的問題看起來很長,我很抱歉。 我會盡量簡潔。

問題:編寫一個程序,將估算的重量(以千克為單位)轉換為磅。 如果用戶輸入負值,程序應該要求玩家重新輸入數字。

我創建了三個函數。 第一個 function - 返回玩家輸入 第二個 function - 返回以磅為單位的重量 第三個 function - 如果重量為正則返回以磅為單位的值,或者如果重量為正則要求另一個輸入。

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

如果相同的值為正,我的程序將返回正確的值。 但是,當我輸入一個負浮點數時,我的程序將永遠打印“無效重量”。 有人告訴我,每當我在循環中繼續寫入時,我都會返回到同一個循環的開頭,但是我無法停止我的程序。

打印“無效重量”的原因。 永遠因為你只接受一次輸入並且每次都使用它,即 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 () )

提示:如果使用函數,請不要使用全局變量。 它們將保留最后一個值,如果您的代碼需要它們在每次調用中更改/重置,最好使用 function 參數

continue語句用於跳過循環內代碼的 rest,僅用於當前迭代。 循環不會終止,而是繼續下一次迭代。

break語句終止包含它的循環。 程序的控制流向緊跟在循環體之后的語句。 如果 break 語句在嵌套循環內(在另一個循環內循環),break 將終止最內層循環。

所以在你的情況下continue你只是 go 回到while仍然有錯誤的輸入。

您要求輸入一次,當輸入錯誤時您需要再次要求輸入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM