Text encryptor and decryptor (Julius Cesar)

orgin_message = input("Enter a message to encrypt : ") key = int(input("Numbers to shift by : ")) def code(message, shift): encrypted = "" for i in range(0, len(message)): code = ord(message[i]) if (code >= 65 and code <= 90) or (code >= 97 and code <= 122): code += shift; if(message[i].isupper()): if code > 90: code -= 26 elif code < 65: code += 26 else: if code > 122: code -= 26 elif code < 97: code += 26 encrypted += chr(code) return encrypted orgin_message = code(orgin_message, key) print("Encrypted text : ", orgin_message) print("Decrypted text : ", code(orgin_message, -key))
This is my version of Julius Cesar styled decryptor/encryptor. The note must be taken, that I am currently learning python, so this, by all means, may not be a perfect example.
Learning material: https://www.youtube.com/watch?v=nwjAHQERL08&index=1&list=PLGLfVvz_LVvTn3cK5e6LjhgGiSeVlIRwt

3 Responses

Welcome to the world of python! Happy learning!

On this example when you think that is a time you can learn few things.
What will happen when user for key type none number? The script will break.
So solution can be to read input as string and then try to parse number from string or just ask if input can be number and if it can you can safely cast to number.

This can be some easy solution:

orgin_message = input("Enter a message to encrypt : ")
key = input("Numbers to shift by : ") #get user input as string

if key.isdigit(): #check if user input is digit
key = int(key) #cast key to int
else:
print("Bad input for number to shift by. You shoud use numbers...") #print error message
raise SystemExit() #safely exit script
@Milos Kamenovic Thanks :D I didn't think of inputting non-digit character into "key" variable, so I skipped the possible error :) Thanks a lot again, should I edit the snippet to include your
code-fix?
@Justas It's not necessary i just want you to understand what's going on :)

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.