简体   繁体   中英

Why does my elif go back to my if?

I have written a very basic encryption program, and whilst writing the decrypting algorithm for it, I have encountered some problems with a loop I have.

from re import *

cipher = open('cipher.txt')
ciphertext = cipher.read()
keyfile = open('key.txt')
key = keyfile.read()
decoded = []
chardec = ''
inval = 1

print("Decoder for encrypt1.py")
while inval == 1:
    useManKey = input("Use a manual key? Y or N\n> ")
    if useManKey == 'Y' or 'y':
        key = input("Please enter the key you wish to use to decrypt\n> ")
        inval = 0
    elif useManKey == 'N' or 'n':
        inval = 0
        print("OK, decrypting")
    else:
        print("That wasn't a valid option/nPlease re-enter")

When I run this, and declare useManKey as N or n it seems to run the if part of the loop as if I had declared it as Y or y. I am probably being stupid here, but any help would be much appreciated thanks.

useManKey == 'Y' or 'y' does not work how you think it does. What you want is useManKey in ('Y', 'y') . What you have first evaluates useManKey == 'Y' , then, if that check fails, tests the string 'y' for truishness. Since non-empty strings are always truish, your if statement always evaluates to True . As is pointed out in the comments, you could also use upper() or lower() to first convert the input to a fixed case if you want.

useManKey == 'Y' or 'y'

Doesn't actually check whether useManKey value being 'Y' or 'y', Use sr2222's answer for what you need to do. ie.

useManKey in ('Y', 'y')

The earlier expression evaluates to

(useManKey == 'Y') or 'y'

Which is always True irrespective of the value of useManKey as 'y' being non-Falsy (non-None) the 'or' of these always evaluates to True,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM