[英]Why won't my caesar shift work properly?
這是代碼:
text = input("What's your text: ")
shift = int(input("What's your shift: "))
def caesar_shift(text, shift):
cipher = ""
for i in text:
if i.isalpha():
stayIn = ord(i) + shift
if stayIn > ord('z'):
stayIn -= 26
lastLetter = chr(stayIn)
cipher += lastLetter
print("Your ciphertext is: ", cipher)
return cipher
caesar_shift(text, shift)
當我運行它時,例如,測試是“ hello world”,而移位是1,我得到:
What's your text: hello world
What's your shift: 1
Your ciphertext is: i
Your ciphertext is: if
Your ciphertext is: ifm
Your ciphertext is: ifmm
Your ciphertext is: ifmmp
Your ciphertext is: ifmmpp
Your ciphertext is: ifmmppx
Your ciphertext is: ifmmppxp
Your ciphertext is: ifmmppxps
Your ciphertext is: ifmmppxpsm
Your ciphertext is: ifmmppxpsme
為什么是這樣? 我做錯什么了嗎,謝謝!
你做
if i.isalpha():
但如果沒有,您別無他法。 這意味着您在最后一個字母不是字母時也要添加它。 因此,用ifmmpp
代替ifmmp
hello
。
該位應更改為:
if i.isalpha():
stayIn = ord(i) + shift
if stayIn > ord('z'):
stayIn -= 26
lastLetter = chr(stayIn)
cipher += lastLetter
else:
cipher += i
如果您不希望每個循環將結果打印一次,請將其移出循環。
要解決打印問題,您可以:
def caesar_shift(text, shift):
cipher = ""
for i in text:
...
print("Your ciphertext is: ", cipher)
return cipher
caesar_shift(text, shift)
但是你應該有
def caesar_shift(text, shift):
cipher = ""
for i in text:
...
print("Your ciphertext is: ", cipher)
return cipher
caesar_shift(text, shift)
還是更好
def caesar_shift(text, shift):
cipher = ""
for i in text:
...
return cipher
print("Your ciphertext is: ", caesar_shift(text, shift))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.