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
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
The statement
output.append(alphabet[pos])
should be inside the else block. In case of i == ' '
, the output.append
is run twice