Search code examples
pythoncaesar-cipher

How do i fix this problem of caesar cipher in python?


wheel = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
wlen = len(wheel) - 1

c = input("Type a word: ").upper()
key = int(input("Key: "))

encrypted = ''


for x in c:
    f = wheel.find(x) + key 
    if x == " ":
        encrypted = encrypted + " "
    if f > wlen:
        f1 = f - wlen - 1
        encrypted = encrypted + wheel[f1] 
    if f < wlen:
        encrypted = encrypted + wheel[f]

print(encrypted)

This code isn't working and I can't find a reason why. I need help.

For example "I suck at coding" gives "M DWYGO DEX DGSHMRK" There is this extra D in all the words that come after space. "M DWYGO DEX DGSHMRK" Thank You.


Solution

  • You need to use elif

    if x == " ":
        encrypted = encrypted + " "
    elif f > wlen:
        f1 = f - wlen - 1
        encrypted = encrypted + wheel[f1]
    elif f < wlen:
        encrypted = encrypted + wheel[f]
    

    Why :

    When you have a space, the find returns -1, so adding the key you got 3, so you enters in the first if as it's a space BUT also in the last if as 3<25 so you add the wheel[f] which is a D, with the elif you'll go only on one condition