Python - Caesar Cipher

前端 未结 2 1975
别跟我提以往
别跟我提以往 2021-01-23 05:36

I\'m new to Python and thought I\'d try to make a Caesar cipher and could use some help with my code. It looks like this:

def cipher(input):
    input = input.lo         


        
相关标签:
2条回答
  • 2021-01-23 05:54

    Your indentation is incorrect:

    for i in input:
        if i == ' ':  #for space
            output.append(' ')
        else:
            pos = alphabet.index(i) + steps
            if pos >= 25:  #for out-of-range
                pos -= 26
    
        output.append(alphabet[pos]) # note here
    

    You append to the output whether or not i is a space. This would break completely if the first character was a space (NameError, as pos is not yet assigned), but just causes repeats elsewhere in the string.

    Change to:

    for i in input:
        if i == ' ':  #for space
            output.append(' ')
        else:
            pos = alphabet.index(i) + steps
            if pos >= 25:  #for out-of-range
                pos -= 26
            output.append(alphabet[pos]) # now inside 'else'
    

    Note you can also simplify your out-of-range:

    pos = (alphabet.index(i) + steps) % 26
    
    0 讨论(0)
  • 2021-01-23 05:55

    The statement

    output.append(alphabet[pos])
    

    should be inside the else block. In case of i == ' ', the output.append is run twice

    0 讨论(0)
提交回复
热议问题