0

I'm trying to do a menu, it's so easy but I don't understand why never ends my loop, I attach my code:

def main():
    menu_bool = False
    while(menu_bool == False):
        print("Menu:\n\t1. Copiar")
        x = input()
        if x == 1:
            print("You have selected option 1.")
            menu_bool = True

# Ejecutamos la función main
if __name__ == '__main__':
    main()

Why when I press "1" ask me again to choose an option? I have declared a boolean variable for stop it, menu_bool = True, but I don't know why my main function is in loop.

I try it doing a global variable but it don't works too. Then this means that my menu_bool = True is never done but I don't understand why.

menu_bool = False
def main():
    global menu_bool
    while(menu_bool == False):
        print("Menu:\n\t1. Copiar")
        x = input()
        if x == 1:
            print("You have selected option 1.")
            menu_bool = True

# Ejecutamos la función main
if __name__ == '__main__':
    main()

Thank you so much!

Lleims
  • 1,275
  • 12
  • 39
  • 2
    `input` returns a string; you are comparing its return value to an `int`. – chepner Feb 27 '19 at 17:04
  • @lurker Yep I'm sure, it's what chepner says. Thank you so much! – Lleims Feb 27 '19 at 17:06
  • @NEA my bad, I ran it on Python2, which behaves differently in this case (`input` returns the number 1, not the string '1'). In Python3, which you have tagged, it fails for the reason @chepner points out. – lurker Feb 27 '19 at 17:07

1 Answers1

1

As others have said, basically you are comparing strings with ints. Also I'd suggest being a bit more pythony with bools, in this case using not instead of comparing explicitly via comparison operator.

def main():
    menu_bool = False
    while(not menu_bool):
        print("Menu:\n\t1. Copiar")
        x = input()
        if x == '1':
            print("You have selected option 1.")
            menu_bool = True
Edword
  • 80
  • 11
  • Could also get rid of the bool entirely by using while(True) and a break statement inside the conditional. – John Feb 27 '19 at 17:14