tango116 tango116 - 1 month ago 10
Python Question

How to create a loop to return to the start of a function python

I am unable to get my

while
loop to start back at the beginning not to sure what is wrong.

First attempt

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()


second attempt

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


I just can't seem to figure it out.

Answer

Your second attempt looks close, but you need an esape if all items are done: but look at your spaces: the if is inside the while: (this code is untested, just to show the reasoning...)

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)