Alternate for goto in python

image
I tried a program to get numbers from the user till he enters ‘done’ and then display the sum of all the numbers he had entered.
I know it can be done in many other ways. I did it with a while loop too and it went well.
But sill I’m eager to learn to do this with if statement
In a few languages, we can simply use a goto function and go to the line we need. I ain’t sure about how to do it in python!
Now I need to go to n=input(…) line form if loop. I know continue ain’t gonna work, but I don’t know what should be done too. I’ll be thankful if someone can help me out in understanding and learning this!

Well, this question sounds a bit like “How can I write C code in Python”? The normal and idiomatic way to do this is with a while statement, and there is no need for another way.

3 Likes

If you import this, you’ll see that part of the Zen of Python (in fact, perhaps the most frequently cited line) is

There should be one–and preferably only one–obvious way to do it.

This isn’t always followed—

Although practicality beats purity

—but it services as a rough guideline for the ethos of the language.

In this case, using a while loop is the one obvious way to do it, so why not do it that way?

In general, the goto statement is (rather famously) considered harmful, and has since half a century ago been replaced by more structured control flow tools in most modern languages, namely for, while, functions, etc.

Finally, note that as code is developed in text editors, not image editors, please don’t upload images of your code:

In addition to the reasons there, it makes your code unreadable to those experts who interact with this forum by email, which includes quite a few of them. Instead, make sure to paste your code into a code block, like this (or just press the </> button in the formatting bar):

```python
PASTE YOUR CODE HERE
```
1 Like

http://entrian.com/goto/

2 Likes

Ha, I remember seeing that a while back…it also takes inspiration from INTERCAL in adding the even more, ahem, “powerful” comefrom statement…

1 Like

This brings back memories of the good old days of BASIC… :+1:

1 Like

Hi !, Thanks for trying to help me.
But there is no such module like goto in python 3.10.4
I ain’t sure about previous ones.

Thanks a lot!
I didn’t know about it
I’m new to this site.

Yeah I know I’m stupid for posting such a question. :sweat_smile:
But I’m just eager to know if there is an alternative method using if loops and break / continue statements.

Skip’s link was about an April Fool’s joke, published as a separate module that you would have had to install. There has never been a goto module in the standard library (i.e. the set of modules you get when you just install Python and nothing else on top of it).

Simple answer: no :slight_smile:

1 Like

No, as others have said, but this might be an XY problem—is there a specific issue with using a while loop for this that’s pushing you toward an alternate approach? If so, and you share you code (as text inside a code block) and the concerns you have with it, perhaps we can give you suggestions on how to improve it.

2 Likes

By Hari Shreehari via Discussions on Python.org at 12Apr2022 13:53:

Yeah I know I’m stupid for posting such a question. :sweat_smile:

No, just new to programming.

But I’m just eager to know if there is an alternative method using if
loops and break / continue statements.

Generally not, in Python (and probably most other modern/recent
languages). You can use exceptions to do a sort of multi-level “break”
but it is usually a bad idea except in very unusual (or tightly
constrained) situations.

Note that you can often avoid “break” by setting your “while” condition
carefully. So a loop like this made up untested example:

while True:
    ans = input("what? ")
    if ans == 'QUIT':
        break
    if ans == 'THE_SECRET':
        print("good guess!")
        break

might be better written:

done = False
while not done:
    ans = input("what? ")
    if ans == 'QUIT':
        done = True
    elif ans == 'THE_SECRET':
        print("good guess!")
        done = True

The reason “goto” is disliked is that it easily-and-often makes for
“spaghetti” code, in which the control jumps all over the place. This
makes it hard to understand the code, and also to change the code
without breaking it (making it behave incorrectly).

While-loops and for-loops are more rigid, but more predicatable and
understandable because there are only two ways through: do the loop
again, or exit at the bottom of the loop. There’s no “goto somewhere
arbitrary”.

The other nice thing about conditions (like the trivial “done” above) is
that in some ways it makes you make the circumstances where things
happen overt. Instead of a goto which jumps out of a loop, you write a
condition for the loop to continue; this amounts to expressing what the
loop should achieve
. With the goto, the reader (even yourself, later)
must figure out when it happens. With the condition, “when” is explicit
and hopefully clear.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

Thank you for sharing your knowledge and spending your time for me :smiley:

No there is no problem with while loop.
I’m just learning Python and am trying a few random programs!
This was a question in my textbook. When I did with while loop and verified with my teacher, she appreciated me and asked me to think of a few more creative ways just for gaining experience.
So I started with this if loop and failed.
Still thanks a lot for explaining these to me! :smiley:

Ah, in that case you could re-organize your functions a bit, use a running sum instead of a list and make use of recursion instead of looping, e.g.

def get_total(running_total=0):
    number = input("Number or 'done' to stop: ")
    if number != "done":
        running_total += int(number)
        running_total = get_total(running_total)
    return running_total

total = get_total()
print(f"Sum of numbers: {total}")

But that’s not very Pythonic, inefficient, runs into stack depth limits and harder to understand. Using a while loop and retaining your existing list-append structure not only avoids these issues, but makes your code more flexible as you can easily change what operation you’re doing on the numbers (mean, max, min, etc) once you have the list:

def get_numbers():
    numbers = []
    while True:
        number = input("Number or 'done' to stop: ")
        if number == "done":
            break
        numbers.append(int(number))
    return numbers

numbers = get_numbers(numbers)
print(f"Sum of numbers: {sum(numbers)}")

As you presumably found out, if blocks are not loops; they merely execute their contents once if the condition is true.

1 Like

Thank a lot Gerlach :smiley:

1 Like

You’re welcome Shreehari :stuck_out_tongue:

Alternatively get_numbers function can be written using assignment expression (walrus operator) introduced in Python 3.8:

def get_numbers():
    numbers = []
    while (number := input("Number or 'done' to stop: ")) != 'done':
        numbers.append(int(number))
    return numbers