Earlier we created a function that receives and rotates a single character by "rot" amount:
def rotate(letter, rot):
shift = 97 if letter.islower() else 65
return chr((ord(letter) + rot - shift) % 26 + shift)
letter = input('Enter a letter: ')
rot = int(input('Enter a number: '))
print(rotate(letter, rot))
Now I need to create a function that rotates all characters in a string by "rot" amount (to the right). So for example
encrypt(text, rot)
with an input of
(Hello World, 1)
would return:
Ifmmp Xpsme
And this is what I have so far:
def rotate(letter, rot):
shift = 97 if letter.islower() else 65
return chr((ord(letter) + rot - shift) % 26 + shift)
def encrypt(text, rot):
encrypted = []
for letter in text:
#use previous rotate function to rotate characters
encrypted.append(rotate(letter,rot))
return ''.join(encrypted)
text = input("Enter some text")
rot = int(input("Enter a number"))
print(encrypt(text,rot))
But I'm getting a ParseError on line 20: print(encrypt(text,rot))
. I don't know if I'm using the two functions together correctly - should the rotate function be inside of the encrypt function? Is there another reason why I'm getting the ParseError? Please let me know if I'm on the right track / help if you can. Thank you.
EDIT: Indenting print(encrypt(text,rot))
got rid of the "ParseError: bad input on line 21", but it also gave me a "ParseError: bad input on line 17": return ''.join(encrypted):
I've tried moving indentation forwards and backwards.
EDIT 2: solution looks like this (after fixed indentation):
def rotate(letter, rot):
shift = 97 if letter.islower() else 65
return chr((ord(letter) + rot - shift) % 26 + shift)
#letter = input('Enter a letter: ')
#rot = int(input('Enter a number: '))
#print(rotate(letter, rot))
def encrypt(text, rot):
encrypted = []
for letter in text:
#use previous rotate function to rotate characters
encrypted.append(rotate(letter,rot))
return ''.join(encrypted)
text = input("Enter some text")
rot = int(input("Enter a number"))
print(encrypt(text,rot))
EDIT 3: If you want to maintain spaces and special characters during rotation, you need to specify that the rotate function only runs if the letter is alphabetical, like this:
def rotate(letter, rot):
shift = 97 if letter.islower() else 65
return chr((ord(letter) + rot - shift) % 26 + shift)
def encrypt(text, rot):
encrypted = []
for letter in text:
#if it's a space, keep it a space
#if it's a special character, keep it a special character
if letter.isalpha():
#use previous rotate function to rotate characters
encrypted.append(rotate(letter,rot))
else:
encrypted.append(letter)
return ''.join(encrypted)
text = input("Enter some text")
rot = int(input("Enter a number"))
print(encrypt(text,rot))
You have a dangling colon:
return ''.join(encrypted):
^
Delete it.
And by the way, your return
is inside your for-loop, which will cause the function to exit on the first iteration.