10.2 - String encryption

Problem

Write a function that will encrypt a given string using a Caesar cipher.

The program is only expected to handle lowercase letters.

All characters should be shifted +1 position.

The character ‘z’ should encrypt to ‘a’.

Example run

Enter string to encrypt: pizza
Encrypted string = qjaab

 

1 Encrypt a string IN string
OUT encrypted_string
1.1 set encrypted_string to empty string
1.2 for i from 0 to length of string -1
1.3         set ascii_val to ascii number for string[i]
1.4         add 1 to ascii_val
1.5         if ascii_val > 122 then
1.6                 subtract 26 from ascii_val
1.7         set new_char to character for ascii_val
1.8         Add new_char to encrypted_string
1.9 return encrypted_string

 

 

# Main
string = input("Enter string to encrypt: ")
encrypted_string = encrypt(string)
print(encrypted_string)
def encrypt(string):
    encrypted = ""
    for i in range(len(string)):
        ascii_val = ord(string[i])
        ascii_val = ascii_val + 1

        if ascii_val > 122:
            ascii_val = ascii_val - 26

        new_char = chr(ascii_val)
        encrypted = encrypted + new_char
    return encrypted

# Main
string = input("Enter string to encrypt: ")
encrypted_string = encrypt(string)
print(encrypted_string)
"""
This program encrypts a string using a Caesar shift of +1 
on lowercase letters (a–z).
Each character is changed into its ASCII code with ord(), 
shifted forward by 1, and then converted back to a character.
If the value goes past 'z' (ASCII 122), it wraps around to 'a'.
"""

def encrypt(string):
    # Start with an empty string to store the result
    encrypted = ""
    
    # Loop through each character in the input string
    for i in range(len(string)):
        # Get the ASCII code for the character
        ascii_val = ord(string[i])
        
        # Add 1 to shift the character forward
        ascii_val = ascii_val + 1

        # If the value goes past 'z' (122), wrap back to 'a'
        if ascii_val > 122:
            ascii_val = ascii_val - 26

        # Convert the new code back into a character
        new_char = chr(ascii_val)
        
        # Add the new character to the encrypted string
        encrypted = encrypted + new_char
    
    # Return the full encrypted string
    return encrypted


# Main program
# Ask the user for a string
string = input("Enter string to encrypt: ")

# Call the encrypt function
encrypted_string = encrypt(string)

# Print the encrypted result
print(encrypted_string)

Extension

Update the function so that it accepts a number for the Caesar cipher shift.

1 Encrypt a string IN string, shift
OUT encrypted_string

Target

Convert each character in a string to it's ASCII value

Convert ASCII values into their characters