简体   繁体   中英

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.

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.

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 . 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.

new_loc is the index of the new character. char_loc + rot_amt does the same thing as location_of_character + 13 in your code. % is the [modulo operator](location_of_character + 13), which brings all values of char_loc + rot_amt within the range 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.

Let me know if you have any questions :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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