[英]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.