13

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.

codeforester
  • 39,467
  • 16
  • 112
  • 140
monkey334
  • 327
  • 2
  • 8
  • 23

7 Answers7

19

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I didn't downvote it. Someone else must of. – monkey334 Sep 13 '13 at 17:55
  • 2
    @user2756717: I wasn't accusing anyone. :-) I just would appreciate the feedback, someone thought it worthy of a downvote, and if they'd share *why* then I can remedy the problem they saw perhaps. Better answers help everyone! – Martijn Pieters Sep 13 '13 at 17:57
  • But just to let you know, your answer was very helpful, and it actually worked for me too too :D – monkey334 Sep 13 '13 at 17:58
10

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 False
    start()
River Tam
  • 3,096
  • 4
  • 31
  • 51
  • 4
    Recursion risks hitting the recursion limit. So that would be the wrong approach here. In Python, recursion is best used for divide-and-conquer style algorithms, not as a general purpose looping construct. – Steven Rumbalski Sep 13 '13 at 17:26
  • Agreed, but it is actually closer to a "goto" in practice than looping. I'll edit my answer to reflect the dangers. – River Tam Sep 13 '13 at 17:28
  • I updated my question detailing the code I'm using and why it doesn't work for me. – monkey334 Sep 13 '13 at 17:32
  • The problem with recursion isn't the memory, it's the recursion limit. – Steven Rumbalski Sep 13 '13 at 17:39
  • The recursion limit is set by the amount of memory you have. Recursing adds a function call to the stack, which is a place in memory. The stack will at some point overflow, which is due to a lack of space in the stack, and therefore a lack of space in memory (and stack overflow). – River Tam Sep 13 '13 at 17:41
  • How will I use your first example into practice within my code then? – monkey334 Sep 13 '13 at 17:44
  • @user2756717: You likely won't want to use a `while True`, but rather a `while response_invalid`. Create a variable above the whole program called "response_invalid" that starts True. Then, when you take in a valid response, change "response_invalid" to False, which will break out of the loop. Do you understand? – River Tam Sep 13 '13 at 17:47
  • Not really, sorry, I'm really new to Python :/ Could you perhaps show me an example? – monkey334 Sep 13 '13 at 17:51
  • I added a bunch of stuff to the answer; check it out, it should answer your question perfectly. – River Tam Sep 13 '13 at 17:58
  • Using a global here is not the best idea. Why not return that value from the function instead? – Martijn Pieters Sep 13 '13 at 17:59
  • He came into this question not understanding loops. I'd rather not confuse him too much with the intricacies of the matter. This is a very basic loop. It's not great practice, but it's simple. – River Tam Sep 13 '13 at 18:02
  • I see the code, and I sort of understand it. However, I don't understand what the while invalid_input = False actually means? – monkey334 Sep 13 '13 at 18:04
  • `while (condition) :` is a control structure. At the end of the block that it creates, if the condition is still true, the block will run again. Otherwise, the program flow will continue after the while loop. I recommend looking up how python loops work. – River Tam Sep 13 '13 at 19:53
  • @RiverTam Hi everyone, I am trying a similar thing as a new Python learner and I tried adding in this while loop into my code, but the issue I seem to have is even when my while condition is false, it still seems to run the code. I used this as a template for my code and started off with next = y as my starter before my main function. Then at the end, I created a while loop that said when next == y, then run the main function. However even if I set next to something else, it still runs the main function again. Why does this happen? – Kaish Dec 23 '16 at 22:32
3

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

K DawG
  • 13,287
  • 9
  • 35
  • 66
2

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 forever and ever, and only exit the program if the user inputs the character 'q' for quit.

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.

Shashank
  • 13,713
  • 5
  • 37
  • 63
1

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

A.J.
  • 91
  • 6
1

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.

Infamouslyuseless
  • 922
  • 2
  • 8
  • 15
-1
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