[英]How to create a loop to return to the start of a function python
我無法讓我的while
循環從頭開始重新確定不確定哪里出了問題。
第一次嘗試
def start() :
if choice in weapon:
print('You have taken the ') + choice + (',this is now in your backpack.\n')
inventory.append(choice)
else:
print("Uh oh, I don't know about that item")
start()
第二次嘗試
the_choice = False
while not the_choice:
if choice in weapon:
print('You have taken the ') + choice + (',this is now in your backpack.\n')
inventory.append(choice)
the_choice = True
# boom no loop needed
else:
print("Uh oh, I don't know about that item")
the_choice = False
我似乎無法解決,感謝您的幫助,謝謝
您的第二次嘗試似乎已經結束,但是如果所有項目都已完成,則需要進行簡單檢查:但是請查看您的空格:while中的if :(該代碼未經測試,只是為了說明原因……)
choice = next_choice()
found = false
while not found:
if choice in weapon_stash:
inventory.append(choice)
found = True
else:
choice = next_choice() # get from user?
if choice == None:
break; # break out on some condition otherwise infinite loop
# found is now either true (a thing was found), or false (the user quit)
第二次嘗試中只有壓痕錯誤。 嘗試下面的代碼。
the_choice = False
while not the_choice:
if choice in weapon:
print('You have taken the ') + choice + (',this is now in your backpack.\n')
inventory.append(choice)
the_choice = True
# boom no loop needed
else:
print("Uh oh, I don't know about that item")
the_choice = False
如果用戶不斷輸入不在列表中的值(武器),這將陷入一個恆定的循環,因此您可以為每個False
放置一個計數器並按如下所示進行更新。
counter=0
the_choice = False
while not the_choice:
if choice in weapon:
print('You have taken the ') + choice + (',this is now in your backpack.\n')
inventory.append(choice)
the_choice = True
# boom no loop needed
else:
print("Uh oh, I don't know about that item")
the_choice = False
counter=counter+1
if counter >= 3:
print('You have made 3 wrong attempts ')
break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.