-1

I want to run a Python program function from a main function that controls the program function with

while True:

I'm led to believe this is good practice. I thought a return call in the program function would break me out, but I get stuck in an infinite loop. Typing "n" should break the loop - how do I do it and is this a sensible thing to do?

def main():
    while True:
        runPgm()

def runPgm():
    while True:
        a = str(input("Input?: "))
        if a == 'n':
            break
    return

if __name__ == '__main__':
    main()
user3329732
  • 346
  • 2
  • 15
  • 4
    You have _two_ `while True` loops and you're only breaking out of one. You do not need both. – khelwood Oct 12 '18 at 10:20
  • 1
    The problem is that you also run a `while True`-loop in your `main`-function, so you call the `runPgm`-function over and over again. This second function actually `break`s and `return`s, but immediately is called again in `main`. – Niklas Mertsch Oct 12 '18 at 10:21
  • 1
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Azat Ibrakov Oct 12 '18 at 11:02

4 Answers4

1

You just need one infinite loop

def main():
    runPgm()

def runPgm():
    while True:
        a = str(input("Input?: "))
        if a == 'n':
            return

if __name__ == '__main__':
    main()
Bob
  • 150
  • 6
0

This isn't working because your break statement (and subsequent return) just exits the current call to the runPgm function. But this returns you to the loop in main, which is never broken out of.

In general you can do "multiple breaks" like this by setting a Boolean flag to say you've want to do a further break, which is checked in the outer loop. However, in your case I think the easier solution is simply to only use one of the loops, not both. Just get rid of the main function entirely and call runPgm instead!

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34
0

There are two things for you in this.

  1. Use single while True loop.
  2. rather break just use return here because function exits as soon as return is reached.

see below python3 code example.

def main():
    print(runPgm())

def runPgm():
    while True:
        a = str(input("Input?: "))
        if a == 'n':
            return a

if __name__ == '__main__':
    main()
Chandella07
  • 2,089
  • 14
  • 22
0

The original source for my initial code is the pygame manual, the answers here show that I don't need to follow that method. However, I'm still unsure why the example in pygame resolves itself. But that's beyond the scope of this question and I'm satisfied I don't need to implement it.

user3329732
  • 346
  • 2
  • 15