Your code is mostly fine but there are a few issues that I've pointed out:
- Your indenting is off. The line
cipher += chr(c)
should be indented to match the things in the for loop
- The function encypt1() shouldn't take a parameter; you are setting plain1 in the method itself so you can declare it there
- If you want to deal with just lowercase letters, you should be doing % 123 (value of 'z') and the if clause should check if
c < 97
. If you want to wrap around printable ascii what you're doing is fine.
This gives:
def encrypt1():
plain1 = input('Enter plain text message: ')
cipher = ''
for each in plain1:
c = (ord(each)+3) % 126
if c < 32:
c+=31
cipher += chr(c)
print ("Your encrypted message is:" + cipher)
Because you want to be able to test this on multiple strings, you would want to pass plain1 as a parameter to the function. But you also want the user to be able to input plain1 if a parameter isn't passed in to the function. For that I would suggest a default parameter. Look at the commented code below:
def encrypt1(plain1=""): # if no argument is passed in, plain1 will be ""
if not plain1: # check if plain1 == "" and if so, read input from user
plain1 = input('Enter plain text message: ')
cipher = ''
for each in plain1:
c = (ord(each)+3) % 126
if c < 32:
c+=31
cipher += chr(c)
return cipher # rather than printing the string, return it instead
So to test this you could do:
test_strings = ['hello world', 'harambe', 'Name', 'InputString']
for phrase in test_strings:
print ("Your encrypted message is:" + encrypt1(phrase))
Which gives the output:
Your encrypted message is:khoor#zruog
Your encrypted message is:kdudpeh
Your encrypted message is:Qdph
Your encrypted message is:LqsxwVwulqj