monkey334 monkey334 - 3 months ago 8
Python Question

Python - How to make program go back to the top of the code instead of closing

I'm trying to figure out how to make Python go back to the top of the code. In SmallBasic, you do

start:
textwindow.writeline("Poo")
goto start


But I can't figure out how you do that in Python :/ Any ideas anyone?

The code I'm trying to loop is this

#Alan's Toolkit for conversions

def start() :
print ("Welcome to the converter toolkit made by Alan.")
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")

if op == "1":
f1 = input ("Please enter your fahrenheit temperature: ")
f1 = int(f1)

a1 = (f1 - 32) / 1.8
a1 = str(a1)

print (a1+" celsius")

elif op == "2":
m1 = input ("Please input your the amount of meters you wish to convert: ")
m1 = int(m1)
m2 = (m1 * 100)

m2 = str(m2)
print (m2+" m")


if op == "3":
mb1 = input ("Please input the amount of megabytes you want to convert")
mb1 = int(mb1)
mb2 = (mb1 / 1024)
mb3 = (mb2 / 1024)

mb3 = str(mb3)

print (mb3+" GB")

else:
print ("Sorry, that was an invalid command!")

start()


So basically, when the user finishes their conversion, I want it to loop back to the top. I still can't put your loop examples into practise with this, as each time I use the def function to loop, it says that "op" is not defined.

Answer

Python, like most modern programming languages, does not support "goto". Instead, you must use control functions. There are essentially two ways to do this.

1. Loops

An example of how you could do exactly what your SmallBasic example does is as follows:

while True :
    print "Poo"

It's that simple.

2. Recursion

def the_func() :
   print "Poo"
   the_func()

the_func()

Note on Recursion: Only do this if you have a specific number of times you want to go back to the beginning (in which case add a case when the recursion should stop). It is a bad idea to do an infinite recursion like I define above, because you will eventually run out of memory!

Edited to Answer Question More Specifically

#Alan's Toolkit for conversions

invalid_input = True
def start() :
    print ("Welcome to the converter toolkit made by Alan.")
    op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
    if op == "1":
        #stuff
        invalid_input = False # Set to False because input was valid


    elif op == "2":
        #stuff
        invalid_input = False # Set to False because input was valid
    elif op == "3": # you still have this as "if"; I would recommend keeping it as elif
        #stuff
        invalid_input = False # Set to False because input was valid
    else:
        print ("Sorry, that was an invalid command!")

while invalid_input : # this will loop until invalid_input is set to be True
    start()
Comments