简体   繁体   English

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

[英]I am using ROT13 python and I am getting an error when the number is greater than 26

I am in my first year of undergrad and one of my assignment with ROT 13. I dont know how to use the if else statment to stop it from going bust when the value is more 26.我在读本科的第一年,我的一个任务是 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))

You don't mention the specific error message, my guess is that new_location is sometimes larger than alphabets , which leads to an indexing error.你没有提到具体的错误信息,我的猜测是new_location有时比alphabets ,这会导致索引错误。

Hope you don't mind, I made a few tweaks to your code.希望你不介意,我对你的代码做了一些调整。 I could go further, but I wanted to keep it relatively similar to the original program.我可以走得更远,但我想让它与原始程序相对相似。

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)

Some explanations:一些解释:

char_loc fulfills the same purpose as location_of_character . char_loc实现与location_of_character相同的目的。 The difference is that, as MarkMeyer pointed out in their comment, .index() will throw an error if the value isn't found, whereas .find() returns -1.不同之处在于,正如 MarkMeyer 在他们的评论中指出的那样,如果找不到值, .index()将抛出错误,而.find()返回 -1。

new_loc is the index of the new character. new_loc是新字符的索引。 char_loc + rot_amt does the same thing as location_of_character + 13 in your code. char_loc + rot_amt在你的代码中与location_of_character + 13做同样的事情。 % is the [modulo operator](location_of_character + 13), which brings all values of char_loc + rot_amt within the range 0-25. %是 [模运算符](location_of_character + 13),它使char_loc + rot_amt所有值char_loc + rot_amt在 0-25 范围内。

string_output += alphabet[new_loc] is again basically identical to your code, we grab the new character and append it to the result string. string_output += alphabet[new_loc]再次与您的代码基本相同,我们获取新字符并将其附加到结果字符串中。

Let me know if you have any questions :)如果您有任何问题,请告诉我 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM