Python - How to make program go back to the top of the code instead of closing
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 by Martijn Pieters for Python - How to make program go back to the top of the code instead of closing
Use an infinite loop:
while True: print('Hello world!')
This certainly can apply to your start()
function as well; you can exit the loop with either break
, or use return
to exit the function altogether, which also terminates 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 were to add an option to quit as well, that could be:
if op.lower() in {'q', 'quit', 'e', 'exit'}: print("Goodbye!") return
for example.
Answer by A.J. for Python - How to make program go back to the top of the code instead of closing
write a for or while loop and put all of your code inside of it? Goto type programming is a thing of the past.
https://wiki.python.org/moin/ForLoop
Answer by Shashank for Python - How to make program go back to the top of the code instead of closing
Python has control flow statements instead of goto
statements. One implementation of control flow is Python's while
loop. You can give it a boolean condition (boolean values are either True or False in Python), and the loop will execute repeatedly until that condition becomes false. If you want to loop forever, all you have to do is start an infinite loop.
Be careful if you decide to run the following example code. Press Control+C in your shell while it is running if you ever want to kill the process. Note that the 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. It doesn't execute anything. pass
is just a placeholder in python that basically says "Hi, I'm a line of code, but skip me because I don't do anything."
Now let's say you want to repeatedly ask the user for input
You could do something like this:
while True: cmd = raw_input('Do you want to quit? Enter \'q\'!') if cmd == 'q': break
cmd
will just store whatever the user inputs (the user will be prompted to type something and hit enter). If cmd
stores just the letter 'q', the code will forcefully break
out of its enclosing loop. The break
statement lets you escape any kind of loop. Even an infinite one! It is extremely useful to learn if you ever want to program user applications which often run on infinite loops. If the user does not type exactly the letter 'q', the user will just be prompted repeatedly and infinitely until the process is forcefully killed or the user decides that he's had enough of this annoying program and just wants to quit.
Answer by River Tam for Python - How to make program go back to the top of the code instead of closing
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()
Answer by Infamouslyuseless for Python - How to make program go back to the top of the code instead of closing
You need to use a while loop. If you make a while loop, and there's no instruction after the loop, it'll become an infinite loop,and won't stop until you manually stop it.
Answer by K DawG for Python - How to make program go back to the top of the code instead of closing
You can easily do it with loops, there are two types of loops
For Loops:
for i in range(0,5): print 'Hello World'
While Loops:
count = 1 while count <= 5: print 'Hello World' count += 1
Each of these loops print "Hello World" five times
Answer by ChipperChimp968 for Python - How to make program go back to the top of the code instead of closing
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
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72
0 comments:
Post a Comment