mikal
mikal

Reputation: 75

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.

Upvotes: 1

Views: 54

Answers (2)

Abhinav Kinagi
Abhinav Kinagi

Reputation: 3801

The problem lies in your condition checks, as multiple conditions evaluate to True at the same time which is not intended.

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

Upvotes: 1

azro
azro

Reputation: 54148

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

Upvotes: 1

Related Questions