Search code examples
pythonif-statementindentation

Got a problem with Python conditional structure


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")

Solution

  • 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