user1594147
user1594147

Reputation: 37

Python 2 - How to make the script go to a specific line?

This is kind of an extension to my last question, but I was wondering if it is possible to make the script go back to a specific line, if an event happens.

print "Type in 'Hello'"
typed = raw_input("> ")
if typed.lower() in ['hello', 'hi']:
    print "Working"
else:
    print "not working" 

On the last line, if 'else' happens, can you make it so it restarts from line 2 again? Any help will be very greatly appreciated, thanks a lot!

Upvotes: 1

Views: 3359

Answers (3)

Hamoudaq
Hamoudaq

Reputation: 1498

there is 2 ways to do it , one with while loop , and one with recursion the two answer before mine solved your problem with while loop , so i'd solve yours with recursion

def Inp():
    print "Type in 'Hello'"
    typed = raw_input("> ")
    if typed.lower() in ['hello', 'hi']:
       print "Working"
    else:
      print "not working"
      Inp()
Inp()

at the end just call the function Inp and it will continue asking for entering the value you want

Upvotes: 0

halex
halex

Reputation: 16403

You could put your code in an endless loop that only exits if the right word is typed in:

print "Type in 'Hello'"
while True:
    typed = raw_input("> ")
    if typed.lower() in ['hello', 'hi']:
        print "Working"
        break
    else:
        print "not working" 

Upvotes: 6

RedBaron
RedBaron

Reputation: 4755

You can let the program lie in a loop till the correct input is given

while True: 
    print "Type in 'Hello'"
    typed = raw_input("> ")
    if typed.lower() in ['hello', 'hi']:
        break

Upvotes: 3

Related Questions