Python - How to get a program to return to the beginning of the code instead of closing

I am trying to figure out how to get Python to return to the beginning of the code. In SmallBasic you do

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

But I can’t understand how you do it in Python: / Any ideas?

The code I'm trying to execute is

 #Alan 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 his conversion, I want him to go back to the top. I still cannot use loop examples in practice, since every time I use the def function for a loop, it says that β€œop” is not defined.

+7
python
source share
7 answers

Python, like most modern programming languages, does not support "goto". Instead, you should use management functions. There are 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 simple.

2. Recursion

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

Note on recursion: do this only if you have a certain number of times when you want to return to the beginning (in this case, add the case where the recursion should stop). It's a bad idea to do infinite recursion, as I defined above, because you will end up running out of memory!

Edited to answer the question more specifically

 #Alan 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() 
+3
source share

Use an infinite loop:

 while True: print('Hello world!') 

This, of course, can be applied to your start() function; you can exit the loop with break or use return to complete the function, which also ends the loop:

 def start(): print ("Welcome to the converter toolkit made by Alan.") while True: 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!") 

If you must add an option to exit, it could be:

 if op.lower() in {'q', 'quit', 'e', 'exit'}: print("Goodbye!") return 

eg.

+16
source share

Python has control flow goto instead of goto . One implementation of the control flow is the Python while . You can give it a boolean condition (booleans either True or False in Python), and the loop will run several times until this condition becomes false. If you want to loop forever, all you have to do is start an endless loop.

Be careful if you decide to run the following code sample. Press Control + C in your shell while it is running, if you ever want to kill the process. Please note that this process must be in the foreground for this to work.

 while True: # do stuff here pass 

The line # do stuff here is just a comment. He does nothing. pass is just a placeholder in python, which basically says "Hi, I am a line of code, but skip me because I am not doing anything."

Now let me say that you want to repeatedly ask the user to enter information forever and always and only exit the program if the user enters the "q" character to exit.

You can do something like this:

 while True: cmd = raw_input('Do you want to quit? Enter \'q\'!') if cmd == 'q': break 

cmd will simply store all user inputs (the user will be prompted to enter something and press enter). If cmd stores only the letter "q", the code will be forced to break from the closed loop. The break statement avoids any loop. Even endless! It is very useful to know if you want to ever program user applications that often run on endless loops. If the user does not enter exactly the letter "q", the user will simply be requested repeatedly and indefinitely until the process is killed by force or the user decides that he has enough of this annoying program and just wants to exit.

+2
source share

You can easily do this with loops, there are two types of loops

For Cycles:

 for i in range(0,5): print 'Hello World' 

Bye Cycles:

 count = 1 while count <= 5: print 'Hello World' count += 1 

Each of these cycles prints "Hello World" five times.

+2
source share

write a for or while loop and put all your code inside it? Programming like Goto is a thing of the past.

https://wiki.python.org/moin/ForLoop

0
source share

You need to use a while loop. If you make a while loop and there is no instruction after the loop, it will become an infinite loop and will not stop until you manually stop it.

0
source share
 def start(): Offset = 5 def getMode(): while True: print('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in 'encrypt e decrypt d'.split(): return mode else: print('Please be sensible try just the lower case') def getMessage(): print('Enter your message wanted to :') return input() def getKey(): key = 0 while True: print('Enter the key number (1-%s)' % (Offset)) key = int(input()) if (key >= 1 and key <= Offset): return key def getTranslatedMessage(mode, message, key): if mode[0] == 'd': key = -key translated = '' for symbol in message: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 translated += chr(num) else: translated += symbol return translated mode = getMode() message = getMessage() key = getKey() print('Your translated text is:') print(getTranslatedMessage(mode, message, key)) if op.lower() in {'q', 'quit', 'e', 'exit'}: print("Goodbye!") return 
0
source share

All Articles