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)時如何回傳
uj5u.com熱心網友回復:
據我了解,您想獲取用戶輸入并回傳值 - 可能來自函式?那么你應該考慮回傳兩者x,h如果你打算在你的代碼中進一步使用它們。
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)
您可能還想查看此答案。有幾個因素必須在您的代碼中進行修改或更改。
解釋
如您所見,while函式中使用了兩個回圈input_weight()。
- 第一個回圈將繼續向用戶詢問公制系統,如果用戶輸入除此之外的任何內容
['P', 'p', 'K', 'k'],回圈將重新運行,提示用戶輸入錯誤。 - 類似地,第二個回圈詢問用戶重量。如果權重不是數字,那么它會繼續要求用戶提供正確的輸入。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/371050.html
