简体   繁体   中英

breaking while loop with function?

I am trying to make a function that has an if/elif statement in it, and I want the if to break a while loop.. The function is for a text adventure game, and is a yes/no question. Here is what i have come up with so far..

def yn(x, f, g):
    if (x) == 'y':
         print (f)
         break
    elif (x) == 'n'
         print (g)

name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, '+name+'. Are you ready for your adventure?'

while True:
    ready = raw_input('y/n ')
    yn(ready, 'Good, let\'s start our adventure!', 
       'That is a real shame.. Maybe next time')

Now I'm not sure if I am using the function right, but when I try it out, it says I can't have break in the function. So if someone could help me with that problem, and if you could help me if the function and calling the function itself is formatted wrong, that would be very much appreciated.

You can work with an exception:

class AdventureDone(Exception): pass

def yn(x, f, g):
    if x == 'y':
         print(f)
    elif x == 'n':
         print(g)
         raise AdventureDone

name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, '+name+'. Are you ready for your adventure?'

try:
    while True:
        ready = raw_input('y/n ')
        yn(ready, "Good, let's start our adventure!",
           'That is a real shame.. Maybe next time')
except AdventureDone:
    pass
    # or print "Goodbye." if you want

This loops the while loop over and over, but inside the yn() function an exception is raised which breaks the loop. In order to not print a traceback, the exception must be caught and processed.

You need to break out of the while loop within the loop itself, not from within another function.

Something like the following could be closer to what you want:

def yn(x, f, g):
    if (x) == 'y':
        print (f)
        return False
    elif (x) == 'n':
        print (g)
        return True

name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, '+name+'. Are you ready for your adventure?'

while True:
    ready = raw_input('y/n: ')
    if (yn(ready, 'Good, let\'s start our adventure!', 'That is a real shame.. Maybe next time')):
        break

You will need to change the break inside your function to a return, and you need to have an else statement in case that the user did not provide you with the correct input. Finally you need to turn the call in your while loop into a if statement.

This will allow you to break the while statement if the player enters the desired command, if not it will ask again. I also updated your yn function to allow the user to use both lower and upper case characters, as well as yes and no.

def yn(input, yes, no):
    input = input.lower()
    if input == 'y' or input == 'yes':
        print (yes)
        return 1
    elif input == 'n' or input == 'no':
        print (no)
        return 2
    else:
        return 0

name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, %s. Are you ready for your adventure?' % name

while True:
    ready = raw_input('y/n ')
    if yn(ready, 'Good, let\'s start our adventure!',
       'That is a real shame.. Maybe next time') > 0:
        break

The idea behind this is pretty simple. The yn function has three states. Either the user responded with yes, no or invalid. If the user response is either yes or no, the function will return 1 for yes, and 2 for no. And if the user does not provide valid input, eg a blank-space , it will return 0.

Inside the while True: loop we wrap the yn('....', '....') function with an if statement that checks if the yn function returns a number larger than 0. Because yn will return 0 if the user provides us with an valid input, and 1 or 2 for valid input.

Once we have a valid response from yn we call break, that stops the while loop and we are done.

One approach would be to have yn return a boolean value which then would be used to break out of the loop. Otherwise a break within a function cannot break out of a loop in the calling function.

def yn(x, f, g):
    if (x) == 'y':
        print (f)
        return True
    elif (x) == 'n'
        print (g)
        return False

name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, '+name+'. Are you ready for your adventure?'
done = False
while not done:
    ready = raw_input('y/n ')
    done = yn(ready, 'Good, let\'s start our adventure!', 'That is a real shame.. Maybe next time')

Using break , you can come out of the loop even if the condition for the end of the loop is not fulfilled. You cant have break because 'if /elif ' is not a loop, its just a conditional statement.

a = True

def b():
    if input("") == "Quit":
        global a
        a == False
    else:
        pass

while a == True:
    print('Solution')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM