13

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.

eandersson
  • 25,781
  • 8
  • 89
  • 110
Ryan Hosford
  • 519
  • 1
  • 9
  • 25

6 Answers6

19

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.

Edit (after more than nine years):

It seems to me that I forgot the situation for "y". So, let's proceed in a different way:

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

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

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

# decided is not None now, so can only be False or True.
if decided:
    play()
else:
    pass
    # or print "Goodbye." if you want
glglgl
  • 89,107
  • 13
  • 149
  • 217
  • 2
    Creative answer, but the only way to break out of the while loop in this case would be by pressing `n`. I assume that he wants the game to continue after entering `y`. – eandersson Apr 19 '13 at 14:16
4

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
Community
  • 1
  • 1
Duane Moore
  • 926
  • 8
  • 5
3

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, e.g. 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.

eandersson
  • 25,781
  • 8
  • 89
  • 110
  • I don't see a huge difference to other, already 7 hours old answers which make `yn()` return a bool-like value... – glglgl Apr 18 '13 at 09:47
  • I told Ryan that I would provide him with an answer when I woke up. I keep my promises, and I do handle it differently, by adding an `else` statement and making it case-insensitive. http://stackoverflow.com/questions/16071394/cant-get-a-function-to-work/16071446#16071446 – eandersson Apr 18 '13 at 09:53
0

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')
Ed Plese
  • 1,568
  • 10
  • 14
0

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.

dharag
  • 299
  • 1
  • 8
  • 17
0
a = True

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

while a == True:
    print('Solution')
Dmitry Demidovsky
  • 7,557
  • 4
  • 22
  • 22
John H
  • 47
  • 1
  • 7