HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Caesar Cypher in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
cyphercaesarpython

Problem

What do you think about this code? I'm learning Python and I made this tool to code a plain text or decode it!

inp = input('Input the text you want to code:\n')
inp = inp.lower()

key = int(input('Input the key you want to use from 2 to 25:\n'))
def rot13(input,key): #Function to code a text with caeser chyper.
    if key > 25:
        key = 25
    elif key  122: #If the final number is greater than 122..
                x = (num + key) - 122
                finaltext += chr(x + ord('a') - 1)
            elif((num + key <= 122)):
                finaltext += chr(num + key)
        else:
            finaltext += letter
    print(finaltext)

rot13(inp,key)

Solution

I'd say the code is not bad, just a few style issues and a couple of practical things.

-
You don't need two lines to lowercase the input string, you can do directly

inp = input('Input the text you want to code:\n').lower()

-
You're not checking user input, if the second input is not an integer, int() will generate a ValueError. You should put a try/catch around that.

-
Your input implies that numbers lower than 1 and higher than 25 are not acceptable, while actually you're accepting them and doing something different than what you told the user. Either you generate an error and refuse the input, or you say that the input will be modified accordingly. Either way the user should know what's going on.

-
You have quite a few hard-coded values, consider using constants .

-
The comment # If the final number is greater than 122.. is useless, the code is clear at that point.

-
The comment # Function to code a text with caeser chyper. should actually be a docstring . You should also specify what you expect as input and what kind of output you return.

-
I would rename the variable input to input_string , just so it's not the same name of the input() function.

-
elif((num + key

-
You're printing inside of the function. I'd return the value and let the caller decide what to do with it.

-
You may want to consider putting
if __name__ == "__main__":` in your code and call your function from there.

-
This is a simple function, so no need to dig too deep but if you want, you may have a look here about string concatenation .

Context

StackExchange Code Review Q#156916, answer score: 9

Revisions (0)

No revisions yet.