label/GOTO or similar function in python3

Viewed 441

I am self teaching myself python 3.8 I have some experience with BATCH which has a GOTO function. Is there a function in python that replicates it. I know there's other question about it .But none of them answers how a beginner can understand it.

For example :

try:
   age = int(input('input your age: '))
   print(age)
except ValueError:
   print('Enter a value')

Let's say I want to jump to the beginning whenever user enters something else than a number.

2 Answers

You Can Use Loop Looks Like Below:

user_input = input ("Enter your Age")
con =True

while(con):
    user_input = input("Enter your Age")
    try:
        val = int(user_input)
        print("Input is an integer number. Number = ", val)
        con = False

    except ValueError:
        print("No.. input is not a number. It's a string")
        con = True

To answer your immediate question, you can run an endless loop (while True: because True is always... True) and break out of it when you're happy with the answer:

while True:
    try:
       age = int(input('input your age: '))
       print(age)
       break
    except ValueError:
       print('Enter a value')

That is essentially the minimal answer without changing rest of your code.

There is no goto in Python. But you run a block of code as long as condition is met or you break out of the it: while.

You can see basic example and introduction in the tutorial and follow more on flow control in the next chapter.

Related