2

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.

  • 1
    You very much need a more comprehensive tutorial than a Stack Overflow answer can provide. No, there is no GOTO, but that doesn't mean you can't do flow control. Additionally, read Dijkstra's GOTO Considered Harmful http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html – Adam Smith Mar 30 '20 at 16:16
  • 1
    Put your code in a while loop. – khelwood Mar 30 '20 at 16:16
  • 1
    Does this answer your question? [Is there a label/goto in Python?](https://stackoverflow.com/questions/438844/is-there-a-label-goto-in-python) – May.D Mar 30 '20 at 16:18

2 Answers2

1

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
Alirezaarabi
  • 348
  • 8
  • 25
1

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.

Ondrej K.
  • 8,841
  • 11
  • 24
  • 39