This is my code below and I cant seem to make my while loop run continuosly.
#alphabet list
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# user input message
text = input("Type your message:\n")
# user input shift amount
shift = int(input("Type the shift number:\n"))
# def function
def encode(plain_text, shift_amount):
cipher_text = ''
for letter in plain_text:
position = alphabet.index(letter)
new_position = position shift_amount
new_letter = alphabet[new_position]
cipher_text = new_letter
print(f'The encoded string is: {cipher_text}')
encode(plain_text = text, shift_amount = shift)
while True:
if text != 'q':
continue
I am not sure if I set this up correctly.
CodePudding user response:
Executed like this, your prompt will ask for two inputs (your message and the shift number), then execute encode. Then it'll enter the while True loop and loop forever. Why?
Two reasons:
- If you didn't input
qat the first step, you will never meet the condition - Even though you did set
text = "q", your loop will never stop. You need to use thebreakstatement to make an infinite loop stop:
while True:
if text == 'q':
break
I think what you want is:
while True:
text = input("Type your message (or q to quit):\n")
shift = int(input("Type the shift number:\n"))
if text == 'q':
break
encode(text, shift_amount=shift)
Thus, your code will loop and ask & encode an input until to type "q"
CodePudding user response:
You need to put the following lines inside the while loop for it to continuously run (as I think you want):
# user input message
text = input("Type your message:\n")
# user input shift amount
shift = int(input("Type the shift number:\n"))
encode(plain_text = text, shift_amount = shift)
CodePudding user response:
As suggested in other answers, you should call input and encode inside the while loop. However, I think only the first input should be before the if clause like so:
while True:
# user input message
text = input("Type your message:\n")
if text != 'q':
break
# user input shift amount
shift = int(input("Type the shift number:\n"))
encode(plain_text=text, shift_amount=shift)
Also, you don't need to define alphabet as a list of characters, you can simply define it as a string:
alphabet = 'abcdefghifklmnopqrstuvwxyz'
or, even better, just import it from string:
import string
alphabet = string.ascii_lowercase
