我应该在我的python函数中创建字符串,以表明我的代码的加密和解密工作正常。以下是我的代码。
def encrypt1():
plain1 = input('Enter plain text message: ')
cipher = ''
for each in plain1:
c = (ord(each)+3) % 126
if c < 32:
c+=31
cipher += chr(c)
print ("Your encrypted message is:" + cipher)
encrypt1()
1。)我得到了&#34;不一致地使用标签和空格&#34;错误
2。)如果我的代码有效,我应该如何输入set,constant字符串以获取所需的输入检查(例如,输入meet并获得正确的输入等)
答案 0 :(得分:1)
您的代码大部分都很好,但我指出了一些问题:
cipher += chr(c)
行应缩进以匹配for循环中的内容c < 97
。如果你想包装可打印的ascii你正在做什么就好了。这给出了:
def encrypt1():
plain1 = input('Enter plain text message: ')
cipher = ''
for each in plain1:
c = (ord(each)+3) % 126
if c < 32:
c+=31
cipher += chr(c)
print ("Your encrypted message is:" + cipher)
因为您希望能够在多个字符串上测试它,所以您需要将plain1作为参数传递给函数。但是,如果参数未传递给函数,您还希望用户能够输入plain1。为此,我建议一个默认参数。请看下面的注释代码:
def encrypt1(plain1=""): # if no argument is passed in, plain1 will be ""
if not plain1: # check if plain1 == "" and if so, read input from user
plain1 = input('Enter plain text message: ')
cipher = ''
for each in plain1:
c = (ord(each)+3) % 126
if c < 32:
c+=31
cipher += chr(c)
return cipher # rather than printing the string, return it instead
所以要测试一下,你可以这样做:
test_strings = ['hello world', 'harambe', 'Name', 'InputString']
for phrase in test_strings:
print ("Your encrypted message is:" + encrypt1(phrase))
给出了输出:
Your encrypted message is:khoor#zruog
Your encrypted message is:kdudpeh
Your encrypted message is:Qdph
Your encrypted message is:LqsxwVwulqj