[英]I am using ROT13 python and I am getting an error when the number is greater than 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))
你没有提到具体的错误信息,我的猜测是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
所有值char_loc + rot_amt
在 0-25 范围内。
string_output += alphabet[new_loc]
再次与您的代码基本相同,我们获取新字符并将其附加到结果字符串中。
如果您有任何问题,请告诉我 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.