python - Why won't my caesar shift work properly? -
this code:
text = input("what's text: ") shift = int(input("what's shift: ")) def caesar_shift(text, shift): cipher = "" in text: if i.isalpha(): stayin = ord(i) + shift if stayin > ord('z'): stayin -= 26 lastletter = chr(stayin) cipher += lastletter print("your ciphertext is: ", cipher) return cipher caesar_shift(text, shift)
when run it, , example, test hello world, , shift 1, get:
what's text: hello world what's shift: 1 ciphertext is: ciphertext is: if ciphertext is: ifm ciphertext is: ifmm ciphertext is: ifmmp ciphertext is: ifmmpp ciphertext is: ifmmppx ciphertext is: ifmmppxp ciphertext is: ifmmppxps ciphertext is: ifmmppxpsm ciphertext is: ifmmppxpsme
why this? doing wrong, in advance!
you
if i.isalpha():
but have no else-clause if. means add last letter when not letter. hence ifmmpp
instead of ifmmp
hello
.
that bit should changed to:
if i.isalpha(): stayin = ord(i) + shift if stayin > ord('z'): stayin -= 26 lastletter = chr(stayin) cipher += lastletter else: cipher +=
if don't want result printed out once every loop, move outside loop.
Comments
Post a Comment