Python:凯撒密码,If 语句和 else 语句同时为真?

标签 python if-statement encryption

我几乎已经解决了这个问题,但出于某种原因,第一个 If 语句和 else 语句都对任何大写字母输入表示正确。因此,如果 ASCII 值介于 65 和 90 之间,则 if 语句声明为真并打印出该值,但随后 else 语句也声明为真并打印出一条语句。如果我把“继续”放在第一个 if 语句的底部,这个程序就可以完美运行。但是我不知道为什么它会那样工作。你能帮我纠正我的逻辑错误吗,我不明白为什么要这样做。这是我的代码和输出:

k = int(raw_input("Please enter a value for k: ")) #Shifter number
original = raw_input("plaintext:  ") #Message user wants ciphered
original_as_array = list(original) ##I am turning the input into an array

for i in range(0,len(original)): ##Now seperating each character to add k
    char = original_as_array[i]
    charint = ord(char)

    if charint >= 65 and charint <=90:
        cipher_int = ((charint-65 + k) % 26)+65
        code_char = chr(cipher_int)
        print code_char,

    if charint >= 97 and charint <=122:
        cipher_int = ((charint-97 + k) % 26)+97
        code_char = chr(cipher_int)
        print code_char,


    else:
        print char,

只有大写的示例输出:

Please enter a value for k: 13
plaintext:  PLEASE HELP
C P Y L R E N A F S R E   U H R E Y L C P

最佳答案

您的第一个 if 语句与 else 语句无关。你要

if charint >= 65 and charint <=90:
        cipher_int = ((charint-65 + k) % 26)+65
        code_char = chr(cipher_int)
        print code_char,

elif charint >= 97 and charint <=122:
    cipher_int = ((charint-97 + k) % 26)+97
    code_char = chr(cipher_int)
    print code_char,


else:
    print char,

否则(对于大写字母)第一个条件解析为真,第二个条件解析为假,并且因为语句解析为假,所以执行 else 语句。

关于Python:凯撒密码,If 语句和 else 语句同时为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5772516/

相关文章:

python - 我如何将数据发送到另一个程序并得到它的答案?

python - 如何将千位分隔符添加到 Pandas 中的数字

.net - 解密字符串 : System. Security.Cryptography.CryptographicException 时偶尔出现错误数据错误

css - Selenium WD |尝试将 'If' 语句与逻辑 'or' 一起使用

javascript - 运行 if 语句后的 jQuery 停止事件

java - 在Java中隐藏数学公式/算法以防止反编译

iOS AES加密错误结果

python - ImageMagick: OSError:/lib/libc.so.6: 找不到版本 `GLIBC_2.XX'

python - 搜索文件python

java - 如何向日期添加数字