[英]Why is my program shifting s and c by the wrong amount if I enter 5 into my program but not with any other letters or number?
該程序旨在詢問您一個句子和一個數字,然后將所有字母都按字母向下移動所輸入的數字,然后通過將其減去輸入的內容來將其撤消。 出於某種原因,當您輸入5
作為班次時,字母s會轉換為不同的隨機字母,而當您嘗試向后移時並不能為您提供正確的單詞,我也不知道為什么。
import sys
import time
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
(a, b, c, d, e, f, g, h, i, j, k, l, m,
n, o, p, q, r, s, t, u, v, w, x, y, z) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26)
def program():
def encryption():
def encryption1():
global message
global shift
message = list ((input ("Please enter the sentence you would like to be %s\n>" % (EnDe1))).lower())
print ("To %s your message please %s your private key number (from 1 - 10)" % (EnDe2, EnDe3))
shift = int (input (">"))
if EnDe == "b":
shift = - (shift)
if shift < 11 or shift > 0:
for x in range(len(message)):
if message[x] != " ":
if eval(message[x]) > 26 - shift:
message[x] = letters[eval(message[x]) + shift - 27]
else:
message[x] = letters[eval(message[x]) + shift - 1]
else:
shift = int (input ("only numbers from 1 to 10 are accepted, try again\n>"))
encryption1()
def choice():
global EnDe
global EnDe1
global EnDe2
global EnDe3
EnDe = (input ("would you like to A)encrypt or B)decrypt\n>")).lower()
if EnDe == "a":
EnDe1 = "encrypted"
EnDe2 = "encrypt"
EnDe3 = "pick"
encryption1()
elif EnDe == "b":
EnDe1 = "decrypted"
EnDe2 = "decrypt"
EnDe3 = "enter"
encryption1()
else:
print ("please pick either 'A' or 'B' , ONLY!")
time.sleep(2)
choice()
choice()
output = ''.join(message)
print (output)
retry = input ("would you like to Decrypt/Encrypt another message? (Y/N)\n>")
retry = retry.lower()
while retry != ("y" or "n"):
retry = input ("please select either y or n\n>")
retry = retry.lower()
while retry == "y":
program()
else:
sys.exit()
encryption()
問題是您定義了一個全局x
變量,也定義了一個局部變量。 局部變量遮蓋了全局變量,因此eval("x")
的結果不再是您期望的。
解決方案:為for
循環使用其他變量。
您的代碼有很多可以改進的地方。 您可以利用模運算符和ord
函數,而無需使用所有這26個字母名稱。
沒有所有這些,這就是for
循環的樣子:
if 0 < shift < 11:
for i, ch in enumerate(message):
if ch != " ":
message[i] = chr((ord(ch)-ord('a')+shift)%26+ord('a'))
無關:請注意, retry != ("y" or "n")
不能那樣工作。 您應該不要retry not in "yn"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.