我將不勝感激:
我嘗試制作一個“那么為什么要擔心”哲學的表格程式:
我寫了這段代碼,但我不明白每次用戶在兩個問題中都沒有輸入“是”或“否”時,我如何讓 while 回圈重復。
problem = str(input("Do you have a problem in life? "))
problem = problem.replace(" ", "").lower() #nevermind caps or spaces
while problem:
if problem not in ("yes","no"):
print("Please enter YES or NO")
if problem == "no":
break
if problem == "yes":
something = str(input("Do you have something to do about it? "))
something = something.replace(" ","").lower()
while something:
if something not in ("yes","no"):
print("Please enter YES or NO")
elif:
break
print("Then why worry?")
uj5u.com熱心網友回復:
我建議使用while True回圈,這樣你就可以把input代碼放一次,然后用正確的條件打破你就可以了
while True:
problem = input("Do you have a problem in life? ").lower().strip()
if problem not in ("yes", "no"):
print("Please enter YES or NO")
continue
if problem == "no":
break
while True:
something = input("Do you have something to do about it? ").lower().strip()
if something not in ("yes", "no"):
print("Please enter YES or NO")
continue
break
break
print("Then why worry?")
使用海象運算子 ( py>=3.8) 可以更輕松地完成
while (problem := input("Do you have a problem in life? ").lower().strip()) not in ("yes", "no"):
pass
if problem == "yes":
while (something := input("Do you have something to do about it? ").lower().strip()) not in ("yes", "no"):
pass
print("Then why worry?")
uj5u.com熱心網友回復:
你的演算法是線性的,里面沒有回圈。因此,唯一需要回圈的地方是當您嘗試從用戶那里獲得正確回應時。所以,我建議你把它移到一個函式中,然后你的例子變成這樣:
def get_user_input(prompt):
while True:
reply = input(prompt).replace(" ", "").lower()
if reply in ['yes', 'no']:
return reply
print("Please enter YES or NO")
problem_exists = get_user_input("Do you have a problem in life? ")
if problem_exists == 'yes':
action_possible = get_user_input("Do you have something to do about it? ")
print("Then why worry?")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/348876.html
