Function 在Python3.4中创建Caesar密码程序,但函数不起作用
目前,我正在创建一个凯撒密码,但它不能正常工作,有人能帮忙吗?代码如下。目前,如果程序第一次运行(如中所示),则无需重新运行任何函数—它工作正常,但当重新运行getKey函数时,它会返回一个错误。代码后,错误显示为:Function 在Python3.4中创建Caesar密码程序,但函数不起作用,function,python-3.x,encryption,typeerror,Function,Python 3.x,Encryption,Typeerror,目前,我正在创建一个凯撒密码,但它不能正常工作,有人能帮忙吗?代码如下。目前,如果程序第一次运行(如中所示),则无需重新运行任何函数—它工作正常,但当重新运行getKey函数时,它会返回一个错误。代码后,错误显示为: def runProgram(): def choice(): userChoice = input("Do you wish to Encrypt of Decrypt? Enter E or D: ").lower() if userCh
def runProgram():
def choice():
userChoice = input("Do you wish to Encrypt of Decrypt? Enter E or D: ").lower()
if userChoice == "e":
return userChoice
elif userChoice == "d":
return userChoice
else:
print("Invalid Response. Please try again.")
choice()
def getMessage():
userMessage = input("Enter your message: ")
return userMessage
def getKey():
try:
userKey = int(input("Enter a key number (1-26): "))
except:
print("Invalid Option. Please try again.")
getKey()
else:
if userKey < 1 or userKey > 26:
print("Invalid Option. Please try again.")
getKey()
else:
return userKey
def getTranslated(userChoice, message, key):
translated = ""
if userChoice == "e":
for character in message:
num = ord(character)
num += key
translated += chr(num)
savedFile = open('Encrypted.txt', 'w')
savedFile.write(translated)
savedFile.close()
return translated
else:
for character in message:
num = ord(character)
num -= key
translated += chr(num)
return translated
userChoice = choice() #Runs function for encrypt/decrypt selection. Saves choice made.
message = getMessage() #Run function for user to enter message. Saves message.
key = getKey() #Runs function for user to select key. Saves key choice.
translatedMessage = getTranslated(userChoice, message, key) #Runs function to translate message, using the choice, message and key variables)
print("\nTranslation complete: " + translatedMessage)
runProgram()
我尝试在使用try、except和else命令的getKey函数期间创建它的防错功能。它将“尝试”查看输入是否为int,如果是,则转到else,但如果不是int,则将重新运行该函数。如果重新运行函数并输入int,则会出现以下错误:
这是it工作的一个例子:
Do you wish to Encrypt of Decrypt? Enter E or D: E
Enter your message: Hello
Enter a key number (1-26): 5
Translation complete: Mjqqt
这是由于未输入int而必须重新运行getKey函数的示例:
Do you wish to Encrypt of Decrypt? Enter E or D: E
Enter your message: Hello
Enter a key number (1-26): H
Invalid Option. Please try again.
Enter a key number (1-26): 5
Traceback (most recent call last):
File "C:\Python34\Encryptor2.py", line 54, in
runProgram()
File "C:\Python34\Encryptor2.py", line 52, in runProgram
translatedMessage = getTranslated(userChoice, message, key) #Runs function to translate message, using the choice, message and key variables)
File "C:\Python34\Encryptor2.py", line 35, in getTranslated
num += key
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
如您所见,它也会按照我的要求重新运行函数,但在将键添加到字符的ord时会出现错误。第一次调用getKey时,请给出您的注释:
key = getKey() #Runs function for user to select key. Saves key choice.
另一个你称之为的地方:
if userKey < 1 or userKey > 26:
print("Invalid Option. Please try again.")
getKey()
用户输入的内容来自getKey。。。你没有跟踪它,所以它消失了。那你就去吧
return userKey
userKey仍然是您试图转换为int的H,即失败的H。你没有把它扔掉,所以它还在那里
更好的解决方案是修改代码的形状,这样getKey就不会在其内部调用getKey。在外部执行错误检查,例如这种形状:
def getKey():
prompt user for key
try to convert to int and return the int
if it fails, return None as an indication that getting the key went wrong.
key = None #set some wrong placeholder
while (key is None) or (key < 1) or (key > 26):
key = getKey()
这段代码真的不需要这么复杂,如果你只使用正则表达式,代码会短得多,但在我看来更好 下面是我为Caesar cipher创建的一段代码,它可以加密、解密和使用用户选择的使用正则表达式的移位
import re
def caesar(plain_text, shift):
cipherText = ''
for ch in plain_text:
stayInAlphabet = ord(ch) + shift
if ch.islower():
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
elif stayInAlphabet < ord('a'):
stayInAlphabet += 26
elif ch.isupper():
if stayInAlphabet > ord('Z'):
stayInAlphabet -= 26
elif stayInAlphabet < ord('A'):
stayInAlphabet += 26
finalLetter = chr(stayInAlphabet)
cipherText += finalLetter
print(cipherText)
return cipherText
selection = input ("encrypt/decrypt ")
if selection == 'encrypt':
plainText = input("What is your plaintext? ")
shift = (int(input("What is your shift? ")))%26
caesar(plainText, shift)
else:
plainText = input("What is your plaintext? ")
shift = ((int(input("What is your shift? ")))%26)*-1
caesar(plainText, shift)
将您的输入更改为原始输入只需使用maketrans和translate函数,这些函数基本上可以为您加密或解密消息。它们可以为问题提供非常简短而有效的解决方案
message = input('enter message').lower()
offset = int(input('enter offset (enter a negative number to decrypt)'))
alphabet = 'abcdefghijklmnopqrstuvwxyz'
enc_alphabet = (alphabet[alphabet.index(alphabet[offset]):len(alphabet)])+ alphabet[0:offset]
data = str.maketrans(alphabet,enc_alphabet)
final_message = str.translate(message, data)
print(final_message)
我以前从未使用过return命令,因此从未意识到会发生这种情况。谢谢,它真的很有帮助,现在工作得很好!
message = input('enter message').lower()
offset = int(input('enter offset (enter a negative number to decrypt)'))
alphabet = 'abcdefghijklmnopqrstuvwxyz'
enc_alphabet = (alphabet[alphabet.index(alphabet[offset]):len(alphabet)])+ alphabet[0:offset]
data = str.maketrans(alphabet,enc_alphabet)
final_message = str.translate(message, data)
print(final_message)