我正在使用ROT13 python,并且数字大于26时出现错误

时间:2019-11-23 23:52:10

标签: python

我是本科生的第一年,也是我在ROT 13的任务之一。我不知道如何使用if else陈述来阻止它在价值大于26时破产。

alphabets= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

string_input= input("Enter a string")

input_length= len(string_input)

print(string_input)

string_output=""

for i in range(input_length):
     character=string_input[i]
     location_of_character= alphabets.find(character)
     new_location=location_of_character + 13;
     string_output= string_output+alphabets[new_location]
     if(string_output>78):print(alphabets(string_output -13))

1 个答案:

答案 0 :(得分:1)

您没有提到具体的错误消息,我的猜测是new_location有时比alphabets大,这会导致索引错误。

希望您不介意,我对您的代码做了一些调整。我可以走得更远,但我想使其与原始程序保持相对相似。

alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num_chars = len(alphabet)
rot_amt = 13

string_input = input('Enter a string: ')
string_output = ''

for curr_char in string_input:
    char_loc = alphabet.index(curr_char)
    new_loc = (char_loc + rot_amt) % num_chars
    string_output += alphabet[new_loc]

print(string_output)

一些解释:

char_loc实现与location_of_character相同的目的。区别在于,正如MarkMeyer在其评论中指出的那样,如果找不到该值,.index()将引发错误,而.find()返回-1。

new_loc是新字符的索引。 char_loc + rot_amt在代码中的作用与location_of_character + 13相同。 %是[取模运算符](location_of_character + 13),它使char_loc + rot_amt的所有值都在0-25范围内。

string_output += alphabet[new_loc]基本上与您的代码相同,我们获取新字符并将其附加到结果字符串中。

让我知道您是否有任何问题:)