0

I have an if conditional structure in my python code and i got a problem with how its executing... I expect the first nested if to print The input choice you entered is out of range") when false is returned but its executing the code in the else which is you entered 4 in the second nested if, i expect it to execute the false counterpart of the first nested if which is print("nThe input choice you entered is out of range"), Am i indenting the wrong way or?Please help me

message=input("Enter the message you want encrypted")
if(message.isalpha()& message.__len__()!=0):
    options=("1. Substitution Cypher","2.Playfair Cypher","3. Transposition Cypher", "4. Product Cypher","RSA Cypher")
    print("Choose an encryption Cypher you would like to use?")
    print(options[0])
    print(options[1])
    print(options[2])
    print(options[3])


    choice=int(input("Please reply with a number for choice of Cypher"))
    ##USER NEEDS CHOICE OF encryption algorithm to use
    if(choice>=1&choice<=4):
        if(choice==1):
            print("You chose 1")
        elif(choice==2):
            print("You chose 2")
        elif(choice==3):
          print("You chose 3")
        else:
         print("You chose 4")
    else:
        print("nThe input choice you entered is out of rage")
else:
    print("User input is required in form of alphabet format")
  • 1
    It works if you replace bitwise comparison `&` with standard `and`, but I can't explain why though. – crusher083 Mar 24 '21 at 08:57
  • Maybe `&` doesn't work with python, is it in the official documentation? –  Mar 24 '21 at 08:59
  • 1
    I found the answer https://stackoverflow.com/questions/3845018/boolean-operators-vs-bitwise-operators. This states, that after first statement is `False` with bitwise `&`, the second one is not evaluated. – crusher083 Mar 24 '21 at 09:06

1 Answers1

0
if(choice>=1&choice<=4):

This does not do what you think. Due to operator precedence & is more sticky than comparison therefore above is equivalent to

if(choice>=(1&choice)<=4):

If you want to keep & you need to add brackets as follows

if((choice>=1)&(choice<=4)):

However note that thanks to one of python's feature you might write

if(1<=choice<=4):

to get same result

Daweo
  • 31,313
  • 3
  • 12
  • 25