HeathderandArenter HA
HeathderandArenter HA

Reputation: 23

How to make python "goto" a previous line to get more input?

So i understand goto is a very bad form of coding, however i need a program to go back to a previous line when the input is incorrect in console.

print ("You wake up.")
print ("You do what?")
seg1 = input()
if seg1 == ("Stand") or seg1 == ("stand") or seg1 == ("stand up") or seg1 == ("Stand up") or seg1 == ("Stand Up"):
    print ("You get up")
    print ("You look around you... your in a dark room. A door hangs slightly ajar infront of you.")
    print ("You do what?")
else:
    print ("I dont understand")

After the else statement has run i want it to repeat line 2 and continue with the program from there... how can i do this?

Upvotes: 2

Views: 30843

Answers (2)

user2108599
user2108599

Reputation: 254

Goto statements are typically used in very low level languages like assembly or basic. In higher level languages like python, they are abstracted out so they don't exist. The way you would want to do this is by using a loop(which is the abstraction of a goto statement). This can be achieved with the following code.

valid_input = False
while not valid_input:
    print ("You wake up.")
    print ("You do what?")
    seg1 = input()
    if seg1 == ("Stand") or seg1 == ("stand") or seg1 == ("stand up") or seg1 == ("Stand up") or seg1 == ("Stand Up"):
       print ("You get up")
       print ("You look around you... your in a dark room. A door hangs slightly ajar infront of you.")
       print ("You do what?")
       valid_input = True
   else:
       print ("I dont understand")

Upvotes: 8

TheSoundDefense
TheSoundDefense

Reputation: 6945

You can achieve this with a while loop instead of a goto, like so:

print ("You wake up.")
print ("You do what?")
while True:
    seg1 = input()
    if seg1 == ("Stand") or seg1 == ("stand") or seg1 == ("stand up") or seg1 == ("Stand up") or seg1 == ("Stand Up"):
        print ("You get up")
        print ("You look around you... your in a dark room. A door hangs slightly ajar infront of you.")
        print ("You do what?")
        break
    else:
        print ("I dont understand")

What happens is that the while will loop supposedly forever, but in reality we will break out of it as soon as we get an input we like. That takes care of your issue.

A goto should never, ever be necessary in your code. There's pretty much always a way to restructure your program so it works without a goto, and it will probably work better as a result.

Upvotes: 0

Related Questions