Search code examples
pythonwhile-loopinfinite-loopprogram-entry-point

Infinite Loop occurs when using main function


Was playing with loops to prepare for my incoming project. and I found infinite loop when using while loop + main function

#1
def choice(name):
    while True:
        if name == "Eat"
            print("I don't want to eat now")
        elif name == "Drink"
            print("NOPE")
        else:
            print("o.O?")

def main():
    name = input("Eat or Drink ? :")
    choice(name)
main()

#2
while True:
    name = input("Eat or Drink ? :")
    if name == "Eat"
        print("I don't want to eat now")
    elif name == "Drink"
        print("NOPE")
    else:
        print("o.O?")

Number 2 doesn't generate infinite loops despite I don't have any return

But when I use Number 1, so that I can use the name variable into different functions in future, it generates infinite loop.

Can I know the reason why it is happening? and how do I fix it while keeping name variable nested in main function?

Thanks!


Solution

  • It's because in version #2 you read input from console on every loop iteration (this line: name = input("Eat or Drink ? :")). So it is still an infinite loop, but this time it waits on every iteration until you provide some input.

    You can fix it by just adding this line: name = input("Eat or Drink ? :") to your choice function or use:

    for i in range(100):
        ...
    

    If you want to limit the number of iterations.

    EDIT: Ok, so take while True from choice function and put it into main, like this:

    def main():
         while True:
              name = input("Eat or Drink ? :")
              choice(name)
              ... other functions using name