擅长:python、mysql、java
<p>这不是一种好的代码编写风格。很破旧,很难看。如果需要,您应该为各个部分创建方法,并创建一个单独的main()类的部分来与用户交互。发动机应该隐藏起来,车身应该抛光。把它们分开。是的,不要重复你自己</p>
<p>好吧,这是我重新编写的代码。重要部分包含注释。错误在后面解释。。在</p>
<pre><code>def encrypt(message, key, direction='E'):
# Look here. There are three arguments. Third one takes 'E' to encrypt
# and anything else to decrypt. You can modify to handle more cases
ciphered = "" # Initialize. You did it almost well
for i in range (len(message)):
char = message[i]
alphakeywordvalue = ord(key[i%len(key)]) - ord("A")+1 # Perfect. We took the key
if direction=='E': # To encrypt
value = ord(char) + alphakeywordvalue
else: # To decrypt
value = ord(char) - alphakeywordvalue
ciphered += chr(value) # chr is the inverse of ord. It gets the character back
# You missed this line
return ciphered
</code></pre>
<p>就这样。现在您可以编写与用户或其他模块交互的代码。这是一个样品测试:-在</p>
^{pr2}$
<p>输出如下:
<img src="https://i.stack.imgur.com/7cnvR.png" alt="enter image description here"/></p>
<p>现在您可以编辑这个方法来处理更多的情况,如超出ascii范围的字符等</p>