0

Can anyone help as to why my while loop isn't working? It's forcing the user to select either 1, 2 or 3, and not letting them proceed, however regardless of whether you put in 1, 2 or 3, it always says that you've entered a different number, and so says "Please choose level 1, 2 or 3"

level = input("Enter your level by typing 1, 2 or 3\n")
int(level)

levelSelect = 1
while levelSelect == 1:
   if level != int(1) or level != 2 or level != 3:
      level = input("Please choose level 1, 2 or 3\n")
      int(level)
   else:
      print("You have selected level", level)
      levelSelect = 0
3
  • 2
    As another side note, int(1) is always able to be replaced by 1. Commented Jan 9, 2013 at 12:47
  • ...Unless you've done something silly like rebind the name int. Commented Jan 9, 2013 at 13:15
  • You need to change your "or" to "and" in your if statement. It will always fail because level can't be 1 2 and 3. Commented Jan 9, 2013 at 15:33

4 Answers 4

4

The line int(level) doesn't do what you think it does. It creates an integer from a string and returns it. It does not operate in place. Because of this, when you get to your if statement, you're comparing a string to integers which is always unequal.

You probably want:

level = int(level)

As a side note, the condition could also be written using the in operator:

if level in (1,2,3):
   print("level is ...")
else:
   print("pick again!")
   #other code ...
Sign up to request clarification or add additional context in comments.

Comments

1

See mgilson's answer regarding assign level as an integer but your logic in deciding if the 'level' is legitimate is also wrong.

Change:

if level != int(1) or level != 2 or level != 3:

for:

if level not in (1,2,3)

1 Comment

Why do you say that logic is wrong? -- The style isn't ideal, but I don't think I see a problem with the logic.
0

mgilson has indicated the core problem here, however I will make a suggestion to improve your code.

while True:
    level = input('Enter level: ')
    if level not in ('1','2','3'):
        print('Try again!\n')
    else:
        print('You chose level ', level)
        break

Comments

0

I think this is what you want (props to with Inbar Rose)

def get_level():
    while True:
        level = int(input("Enter your level by typing 1, 2 or 3\n"))
            if level in [1, 2, 3]:
                return level

1 Comment

why not put the whole thing into the while loop? pastebin.com/ArVpMNwF : def choose_level(): while True: level = int(input("Enter your level by typing 1, 2 or 3\n")) if level in [1, 2, 3]: return level

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.