[英]Why does my elif go back to my if?
我已經編寫了一個非常基本的加密程序,並且在為其編寫解密算法時,遇到了一些循環問題。
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")
當我運行它,並將useManKey聲明為N或n時,似乎在循環的if部分運行,就好像我已將其聲明為Y或y一樣。 我在這里可能很愚蠢,但是任何幫助將不勝感激,謝謝。
useManKey == 'Y' or 'y'
不起作用。 您想要的是useManKey in ('Y', 'y')
。 首先,您需要對useManKey == 'Y'
求值,然后,如果該檢查失敗,則對字符串'y'
進行隱性測試。 由於非空字符串始終為實,因此您的if
語句始終求值為True
。 如注釋中所指出的,如果需要,還可以使用upper()
或lower()
首先將輸入轉換為固定的大小寫。
useManKey == 'Y' or 'y'
實際不檢查useManKey
值是'Y'還是'y',請使用sr2222的答案進行操作。 即。
useManKey in ('Y', 'y')
較早的表達式的計算結果為
(useManKey == 'Y') or 'y'
不管useManKey
的值是什么,始終為True,因為“ y”為非useManKey
(non- useManKey
)(非無),其中的“或”始終為True,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.