簡體   English   中英

如何創建循環以返回到函數python的開頭

[英]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)

我之所以評論Visual Studio的可能不是最好的Python編輯器是其他編輯器會警告你,你不增加你的函數定義后的壓痕start()在你的第一次嘗試,也沒有你你開始后縮進while循環第二次嘗試。 總是包含您的錯誤消息以幫助描述您的問題,但是如果我猜想的話,您會發現一些與IndentationError消息有關的東西。

縮進是python編碼中最重要的概念之一,其目的與java或c ++中的花括號相同。 Wikipedia對此有一個非常簡單的描述。

對於編輯器,我是spyder的個人擁護者 ,盡管有很多很棒的人: Pycharmpydev等。

第二次嘗試中只有壓痕錯誤。 嘗試下面的代碼。

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.

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