Jim Derkin
Jim Derkin

Reputation: 69

Creating a Caeser program: Converting ASCII to characters

I'm working on python attempting to make a Caeser Cipher program. So I've made a GUI platform and have been able to make the cipher part work, but it spits out the message only in ASCII.

When you run my program, it takes the info, you say the amount of letters you want the alphabet to shift by, and then says the message in ASCII, how can i get this part to come out in letters?

I tried storing the for loop into a variable then just adding that variable into a common ascii --> character converter, but that doesn't work.

Here's my code:

def encode(userPhrase):
    msg = input('Enter your message: ')
    key = eval(input("enter a number"))
    finalmsg = msg.upper()
    for ch in finalmsg:
        print( str( ord(ch)+key ), end=' ')

Upvotes: 0

Views: 100

Answers (2)

Sci Prog
Sci Prog

Reputation: 2691

You need to allow the letters at the end of the alphabet to wrap around to A,B,C... You can do it with modulo arithmetic (complicated), or see the example below

Use chr instead of str. You pass a parameter userPhrase and you ask to enter a message. Also, I suggest using int instead of eval.

def encode(userPhrase):
  msg = input('Enter your message: ')
  key = int(input("enter a number"))
  finalmsg = msg.upper()
  for ch in finalmsg:
    new_ch = ord(ch)+key
    if new_ch > ord('Z'):
      new_ch -= 26
    print( chr(new_ch), end=' ')

The last problem you have is for non letters (e.g. spaces, etc.)

Upvotes: 0

idjaw
idjaw

Reputation: 26600

Change your str to chr:

print( chr( ord(ch)+key ), end=' ')

Per the documentation on chr:

Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(957) returns the string 'ν'. This is the inverse of ord().

Upvotes: 1

Related Questions