如何创建一个循环来返回函数python的开头

时间:2016-10-17 14:13:25

标签: python python-2.7

我无法让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  

我似乎无法弄明白,任何帮助都表示赞赏,谢谢

3 个答案:

答案 0 :(得分:2)

你的第二次尝试看起来很接近,但如果所有项目都已完成你需要一个esape:但是看看你的空格:if是在while内:(这段代码未经测试,只是为了显示推理......)

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)

答案 1 :(得分:2)

我评论Visual Studio可能不是最好的python编辑器的原因是其他编辑会警告你在第一次尝试时没有增加函数定义start()后的缩进,也没有在缩进后缩进第二次尝试时while循环的开始。包含您的错误消息以帮助描述您的问题总是有帮助的,但如果我猜测,您正在获得IndentationError消息的调整。

缩进是python编码最重要的概念之一,其作用与java或c ++中的花括号相同。 Wikipedia对如何操作有一个非常简单的描述。

至于编辑,我是spyder的个人粉丝,虽然有很多很棒的人:Pycharmpydev等。

答案 2 :(得分: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

如果用户继续输入不在列表中的值(武器),这将停留在一个常量循环中,因此您可以为每个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