我不明白为什么要搬家
if cipher_direction == "decode":
shift_amount *= -1在end_text下工作,但它不能在下面所示的位置工作?

完整的代码:
alphabet = ['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']
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
#TODO-1: Combine the encrypt() and decrypt() functions into a single function
# called caesar().
def caesar(start_text, shift_amount, cipher_direction):
end_text = ""
if cipher_direction == "decode":
shift_amount *= -1
for letter in start_text:
position = alphabet.index(letter)
new_position = position + shift_amount
end_text += alphabet[new_position]
print(f"Here's the {direction}d result: {end_text}")
#TODO-2: Call the caesar() function, passing over the 'text', 'shift' and
# 'direction' values.
caesar(start_text=text, shift_amount=shift, cipher_direction=direction)发布于 2021-12-30 08:04:00
因为变量赋值(*=)经常在循环中被覆盖。要在循环中使用它,需要分配一次。
例如:
def caesar(start_text, shift_amount, cipher_direction):
end_text = ""
#if cipher_direction == "decode":
# shift_amount *= -1
for letter in start_text:
if cipher_direction == "decode" and shift_amount > 0:
shift_amount *= -1
position = alphabet.index(letter)
new_position = position + shift_amount
end_text += alphabet[new_position]
print(f"Here's the {direction}d result: {end_text}")注意:程序在带有空格的单词中抛出一个错误。
https://stackoverflow.com/questions/70528660
复制相似问题