Write a program that will implement a “shift right by 5” Caesar Cipher Machine. The letters will be entered one character at a time. The program will terminate when an empty input is encountered.
My code
alphabet = "abcdefghijklmnopqrstuvwxyz"
key = "fghijklmnopqrstuvwxyzabcde"
n=input("Enter a letter: ")
message=""
for letter in n:
if letter.lower() in alphabet:
message = key[alphabet.find(letter.lower())]
else:
message = letter
print(message)
I'm fairly new to python and I am having trouble with my code. I want if the user entered nothing when prompt, it will print everything he entered as encrypted key. Also as stated in the question, it should ask for the user multiple inputs and it will only end once the user did not input anything when asked.
Cheers to everyone!
Example
Enter a letter: a
Enter a letter: b
Enter a letter: c
Enter a letter: (empty, enter)
f g h
CodePudding user response:
I'm assuming that if the user answers something not in the alphabet, you just want that to stay the same (periods, etc.)
Your problem can be solved quite simply with while loops. All you need is to keep going until n is not a blank space:
while n != "":
for letter in n:
if letter.lower() in alphabet:
message = key[alphabet.find(letter.lower())]
else:
message = letter
The loop will run until the user has entered a blank space.
CodePudding user response:
You can do something like this. The program below asks you for a letter at each loop cycle. The letter you enter is assigned to the 'letter' variable and its value is also tested so if it is empty, the loop ends. The ":=" operator is called "the walrus operator" and it helps you avoid repetition. I also used the string standard module to avoid hardcoding the alphabet. The code is certainly not the most optimal and you should probably make further improvements.
It also requires you to only enter single letters, otherwise it will not work correctly, and if you enter an uppercase letter it is converted to lowercase, so there are a few things you need to consider.
from string import ascii_lowercase
key = ascii_lowercase[5:] ascii_lowercase[:5]
letters = []
while letter := input('Enter a letter: '):
if (idx := ascii_lowercase.find(letter.lower())) != -1:
letters.append(key[idx])
message = ''.join(letters)
print(message)