1

When I input a choice, with a couple of 'if' statements after it, all the other 'if' statements except for the first one is ignored. For example:

print('1. dostuff')
print('2. stuff')
choice = input('What do you want to do? ')
if choice == '1' or 'dostuff':
    domorestuff()
if choice == '2' or 'stuff':
    stuff()

Whatever I input, it will always go to 'domorestuff()'.

1
  • 2
    Hint: bool('dostuff') Commented Oct 18, 2013 at 14:35

2 Answers 2

7

It should be:

if choice in ('1', 'dostuff'):

Right now, Python is reading your code like this:

if (choice == '1') or 'dostuff':

This means that it will always return True because "dostuff" will always evaluate to True since it is a non-empty string. See a demonstration below:

>>> choice = None
>>> choice == '1' or 'dostuff'
'dostuff'
>>> bool(choice == '1' or 'dostuff')
True
>>>

The solution I gave however uses the in keyword to test if choice can be found in the tuple ('1', 'dostuff').

Sign up to request clarification or add additional context in comments.

Comments

3

This is a very common mistake. It should be something like:

if choice == '1' or choice == 'dostuff':
       domorestuff()
if choice == '2' or choice == 'stuff':
       stuff()

You need to reiterate the choice ==. As is, the condition is being seen as:

if (choice == '1') or ('dostuff'):

which will always be true, since 'dostuff' is truthy.

Comments

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.