-1

This is a snippet from my script.

while True:

    ## Rules: userInput == [isalpha()=True, isdigit()=True, True, isdigit()=True]

    userInput = raw_input('# ').replace(' ', '').split(',')
    print userInput
    print 'List Index 0', userInput[0].isalpha()
    print 'List Index 1', userInput[1].isdigit()
    print 'List Index 3', userInput[3].isdigit()
    print 'List is', userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit()

    if userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit() == False:
        print 'Error'
        continue
    else:
        print 'Success'
        break

And this is the output I get if I run it with input: 1,1,1,1

# 1,1,1,1
['1', '1', '1', '1']
List Index 0 False
List Index 1 True
List Index 3 True
List is False
Success

As far as I know the if statement is True and should be executed and return to the beginning of the loop until the rules are satisfied. However, the else statement gets executed instead.

What am I missing?

Thank you for your help.

eyhiya
  • 11
  • 2
  • 4
    I think you may be assuming that `if condition1 and condition2 == False` is the same thing as `if (condition1 and condition2) == False`, when it's actually the same thing as `if condition1 and (condition2 == False)`. – Kevin Nov 16 '17 at 14:01
  • your if statement reads `if False and True and True` which is false, I'd bet it is exactly as Kevin says – Robbie Milejczak Nov 16 '17 at 14:02
  • Thank you!!! putting the if statement in brackets worked perfectly! – eyhiya Nov 16 '17 at 14:03

3 Answers3

2

I think you may be assuming that if condition1 and condition2 == False is the same thing as if (condition1 and condition2) == False, when it's actually the same thing as if condition1 and (condition2 == False).

In which case you should be doing

if (userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit()) == False:

or

if not (userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit()):

or

if userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit():
    print 'Success'
    break
else:
    print 'Error'
    continue
Kevin
  • 74,910
  • 12
  • 133
  • 166
1

Your Boolean logic is wrong, this:

userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit() == False

boils down to:

False and True and True == False

and that is

False and True and False

which is False, not True.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
0

Probably you should change the statement of while True to something similar like while 1:pass. More information is found here