The while loops controlled by either the x variable won't stop after its relevant variable is set to False by the code contained within the if/elif statement. Instead of stopping the while loop, when the x variable is set to False it allows the loop to occur one more time before causing the loop to stop. What is causing this?
def GameIntro():
# Declaration of outer while loop variable
x = True
# Outer while loop that I want to keep running until the player enters the 'yes' branch of the if statement
while x:
# Declaration of inner while loop variable
j = True
playerName = input("Please enter your name:")
print("\nWelcome " + playerName)
print("At any time, type 'Help' to bring up the list of possible actions." + "\n")
while j:
beginGame = input(playerName + ", are you ready to begin? [Y] or [N]")
beginGame = beginGame.upper()
if beginGame == "Y" or beginGame == "YES":
# At this point I want this function to end and for it to return a True value. The # print is purely for testing purposes.
print("Yes Test")
x = False
j = False
return True
elif beginGame == "N" or beginGame == "NO":
# At this point, I want the inner loop to stop and for the outer loop to occur again. # This works.
print("No Test")
j = False
else:
print("Please enter either [Y] or [N]")
GameIntro()
Here is the output I am getting.
Please enter your name:Bob
Welcome Bob
At any time, type 'Help' to bring up the list of possible actions.
Bob, are you ready to begin? [Y] or [N]
Y
Yes Test
Please enter your name:Bob2
Welcome Bob2
At any time, type 'Help' to bring up the list of possible actions.
Bob2, are you ready to begin? [Y] or [N]
Y Yes Test
Run game
Process finished with exit code 0
The "Run game" comes from another function that is receiving the returned True from the yes branch of the if/elif statement.
I don't think you really need a separate variable, you can use the beginGame, for example as your sentinal value
I would also recommend placing a break at every point within the loops rather than rely on return unless you cannot posssible break to a safe return state
def validInput(x):
return x in {'YES', 'Y'}
def intro():
playerName = input("Please enter your name:")
print("\nWelcome " + playerName)
print("At any time, type 'Help' to bring up the list of possible actions." + "\n")
beginGame = 'N'
while not validInput(beginGame):
beginGame = input(playerName + ", are you ready to begin? [Y] or [N]").upper()
if beginGame == "HELP":
print('[Y] or [N]?')
elif validInput(beginGame):
print('Starting Game!')
print(f'Getting {playerName} ready to play...')
return (playerName, True)
playerName, ready_intro = intro()
if ready_intro:
main_game(playerName)
Related
I am writing a python program that requests a name and age. Store that data in a List. After the user has entered data, request that the user enters 'y' or 'n' to continue. If they enter 'n', print the list of names and ages figures to the screen. If they enter 'y', repeat the first step.
This is what I have done.
keepAsking = True
# Keep looping for as long as keepAsking is equal to true
while(keepAsking == True):
stdName = input(" Name: ")
ageRecord = int(input("Age: "))
name_array = list()
age_array = list()
name_array.append(stdName)
age_array.append(ageRecord)
# Create and set checkContinue
checkContinue = True
# Keep looping for as long as checkContinue is equal to true
while (checkContinue == True):
# Ask the user if they wish to continue, and store it in doContinue
doContinue = input("Continue? ")
# Did they enter yes?
if (doContinue.lower() == "yes") :
# If so, stop asking if they want to continue, but keep asking
# everything else. Thus checkContinue is made false, but keepAsking
# remains true
checkContinue = False
# Did they enter no?
elif (doContinue.lower() == "no") :
# If so, stop asking if they want to continue ...
checkContinue = False
print (name_array)
print (age_array)
This is what its meant to show
Name: Faith Wisdom
Age: 28
Continue? [y/n] y
Name: Mitchell Train
Sales: 15
Continue? [y/n] n
Faith Wisdom 28
Mitchell Train 15
but with what I wrote, it's showing
Name: Faith Wisdom
Age: 28
Continue? [y/n] y
Name: Mitchell Train
Sales: 15
Continue? [y/n] n
Mitchell Train 15
The first entry is not saving in the list
You initialize your arrays in each step here:
while(keepAsking == True):
name_array = list()
age_array = list()
This will write over everything you saved at each step. Try taking the definitions out of your while loop:
name_array = list()
age_array = list()
while(keepAsking == True):
# do other stuff as usual
Some issues in your code.
You are redefining name_array and end_array for every while loop, but you want to define the list outside the loop, and update it inside the while loop
You have two while true loops, but you can just have one while loop and update keepAsking accordingly
keepAsking = True
name_array = list()
age_array = list()
while(keepAsking):
#Get nane and input
stdName = input("Name: ")
ageRecord = int(input("Age: "))
#Update name and age array
name_array.append(stdName)
age_array.append(ageRecord)
#Get input from user
doContinue = input("Continue? [y/n] ")
#Based on user input, keep asking or stop
if (doContinue.lower() == "y") :
keepAsking = True
elif (doContinue.lower() == "n") :
keepAsking = False
So the output now will look like.
Name: Faith Wisdom
Age: 28
Continue? [y/n] y
Name: Mitchell Train
Age: 15
Continue? [y/n] n
['Faith Wisdom', 'Mitchell Train']
[28, 15]
As pointed by Hoog's answer name_array and age_array should be defined before and outside the while loop.
Disclaimer: I've modified the names of the variables according to the PEP8 style guide.
Option 1: keeping 2 lists
If you refactor check_option into a function you can call it recursively when the option selected by the user is not among the correct. Also, as the name and age lists have always the same length, you can zip them just before iterating over them and printing its contents together every iteration in the for loop.
name_array = list()
age_array = list()
def check_continue():
response = input('Continue? [y/n] ')
if response == 'n':
return False
elif response == 'y':
return True
else:
print('Please select a correct answer [y/n]')
return check_continue()
while(True):
std_name = input('Name: ')
age_record = input('age: ')
name_array.append(std_name)
age_array.append(age_record)
if not check_continue():
break
else:
continue
for name, age in zip(name_array, age_array):
print(name, '\t', age)
Option 2: merging the lists
By using a tuple to pack both std_name and age_record variables, you suppress the need of ziping two lists by keeping all the n th iteration data in the n th index of a single list.
users = list()
def check_continue():
response = input('Continue? [y/n] ')
if response == 'n':
return False
elif response == 'y':
return True
else:
print('Please select a correct answer [y/n]')
return check_continue()
while(True):
std_name = input('Name: ')
age_record = input('age: ')
user = (std_name, age_record)
users.append(user)
if not check_continue():
break
else:
continue
for name, age in users:
print(name, '\t', user)
Note: In Python there is a built-in module called array which provides the array object type. Because you might not want to include 'array' in the list's names. You might better want to think on a plural name describing the elements inside the list as the list are aimed to contain the same type of elements in contrast with tuples (although you are not forced to).
Initialize your arrays outside the while loop because every time you will loop you will rewrite your array and you will save only the last answers.
name_array = list()
age_array = list()
# now you write your loop
I think you are over thinking this problem. Also, you need to append to your list properly, which is your main issue.
name_age = []
while 1:
stdName = input(" Name: ")
ageRecord = int(input("Age: "))
name_age.append([stdName,ageRecord])
doContinue = input("Continue? ")
if doContinue[0].lower() == "n":
for name, age in name_age:
print(name, age)
break
I am very inexperienced with any programming language. I decided for my first for-fun/leaning project to be creating a calculator to add different durations of time (ex. add the length of several songs to find how long an album is).
So far the user input method is pretty basic, and I'll work to fix that once the basics work, so bear with me on that. The calculator is currently capable of adding two times together and printing the correct answer.
My main problem is creating a functional Continue/Clear user prompt. I have a loop asking if the user wants to continue, clear, or exit. User input works correctly, but I don't know how to actually "continue or clear".
My idea: Upon hitting continue, the previous total will become firstNumber, and the user will only be prompted for the second number (nextNumber) and will be given a new sum and receive the same continue/clear/exit prompt. If the user hits clear, it will start at the very beginning and the user will be prompted for a new firstNumber.
Any help is greatly appreciated.
Below is the code:
import datetime
# holds first entry
print("Enter the first number")
seconds_1 = int(input("Seconds: "))
minutes_1 = int(input("Minutes: "))
hours_1 = int(input("Hours: "))
# holds second entry
print("Enter another number")
seconds_2 = int(input("Seconds: "))
minutes_2 = int(input("Minutes: "))
hours_2 = int(input("Hours: "))
# calculation
duration_1 = datetime.timedelta(hours=hours_1, minutes=minutes_1, seconds=seconds_1)
duration_2 = datetime.timedelta(hours=hours_2, minutes=minutes_2, seconds=seconds_2)
total = duration_1 + duration_2
print(total)
# continue, clear, or exit
contClear = input("Continue: Y | Clear: N | Exit: X: ")
cont = False
while cont == False:
if contClear.upper() == "Y" or contClear.upper() == "YES":
print("Next")
cont = True
elif contClear.upper() == "N" or contClear.upper() == "NO":
print("Cleared")
cont = True
elif contClear.upper() =="X" or contClear.upper() == "EXIT":
print("Exiting")
cont = True
else:
print("Invalid Entry")
contClear = input("Continue: Y | Clear: N | Exit: X: ")
print("DONE")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I'm trying to figure out how to make Python go back to the top of the code. In SmallBasic, you do
start:
textwindow.writeline("Poo")
goto start
But I can't figure out how you do that in Python :/ Any ideas anyone?
The code I'm trying to loop is this
#Alan's Toolkit for conversions
def start() :
print ("Welcome to the converter toolkit made by Alan.")
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
f1 = input ("Please enter your fahrenheit temperature: ")
f1 = int(f1)
a1 = (f1 - 32) / 1.8
a1 = str(a1)
print (a1+" celsius")
elif op == "2":
m1 = input ("Please input your the amount of meters you wish to convert: ")
m1 = int(m1)
m2 = (m1 * 100)
m2 = str(m2)
print (m2+" m")
if op == "3":
mb1 = input ("Please input the amount of megabytes you want to convert")
mb1 = int(mb1)
mb2 = (mb1 / 1024)
mb3 = (mb2 / 1024)
mb3 = str(mb3)
print (mb3+" GB")
else:
print ("Sorry, that was an invalid command!")
start()
So basically, when the user finishes their conversion, I want it to loop back to the top. I still can't put your loop examples into practise with this, as each time I use the def function to loop, it says that "op" is not defined.
Use an infinite loop:
while True:
print('Hello world!')
This certainly can apply to your start() function as well; you can exit the loop with either break, or use return to exit the function altogether, which also terminates the loop:
def start():
print ("Welcome to the converter toolkit made by Alan.")
while True:
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
f1 = input ("Please enter your fahrenheit temperature: ")
f1 = int(f1)
a1 = (f1 - 32) / 1.8
a1 = str(a1)
print (a1+" celsius")
elif op == "2":
m1 = input ("Please input your the amount of meters you wish to convert: ")
m1 = int(m1)
m2 = (m1 * 100)
m2 = str(m2)
print (m2+" m")
if op == "3":
mb1 = input ("Please input the amount of megabytes you want to convert")
mb1 = int(mb1)
mb2 = (mb1 / 1024)
mb3 = (mb2 / 1024)
mb3 = str(mb3)
print (mb3+" GB")
else:
print ("Sorry, that was an invalid command!")
If you were to add an option to quit as well, that could be:
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
return
for example.
Python, like most modern programming languages, does not support "goto". Instead, you must use control functions. There are essentially two ways to do this.
1. Loops
An example of how you could do exactly what your SmallBasic example does is as follows:
while True :
print "Poo"
It's that simple.
2. Recursion
def the_func() :
print "Poo"
the_func()
the_func()
Note on Recursion: Only do this if you have a specific number of times you want to go back to the beginning (in which case add a case when the recursion should stop). It is a bad idea to do an infinite recursion like I define above, because you will eventually run out of memory!
Edited to Answer Question More Specifically
#Alan's Toolkit for conversions
invalid_input = True
def start() :
print ("Welcome to the converter toolkit made by Alan.")
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
#stuff
invalid_input = False # Set to False because input was valid
elif op == "2":
#stuff
invalid_input = False # Set to False because input was valid
elif op == "3": # you still have this as "if"; I would recommend keeping it as elif
#stuff
invalid_input = False # Set to False because input was valid
else:
print ("Sorry, that was an invalid command!")
while invalid_input: # this will loop until invalid_input is set to be False
start()
You can easily do it with loops, there are two types of loops
For Loops:
for i in range(0,5):
print 'Hello World'
While Loops:
count = 1
while count <= 5:
print 'Hello World'
count += 1
Each of these loops print "Hello World" five times
Python has control flow statements instead of goto statements. One implementation of control flow is Python's while loop. You can give it a boolean condition (boolean values are either True or False in Python), and the loop will execute repeatedly until that condition becomes false. If you want to loop forever, all you have to do is start an infinite loop.
Be careful if you decide to run the following example code. Press Control+C in your shell while it is running if you ever want to kill the process. Note that the process must be in the foreground for this to work.
while True:
# do stuff here
pass
The line # do stuff here is just a comment. It doesn't execute anything. pass is just a placeholder in python that basically says "Hi, I'm a line of code, but skip me because I don't do anything."
Now let's say you want to repeatedly ask the user for input forever and ever, and only exit the program if the user inputs the character 'q' for quit.
You could do something like this:
while True:
cmd = raw_input('Do you want to quit? Enter \'q\'!')
if cmd == 'q':
break
cmd will just store whatever the user inputs (the user will be prompted to type something and hit enter). If cmd stores just the letter 'q', the code will forcefully break out of its enclosing loop. The break statement lets you escape any kind of loop. Even an infinite one! It is extremely useful to learn if you ever want to program user applications which often run on infinite loops. If the user does not type exactly the letter 'q', the user will just be prompted repeatedly and infinitely until the process is forcefully killed or the user decides that he's had enough of this annoying program and just wants to quit.
write a for or while loop and put all of your code inside of it? Goto type programming is a thing of the past.
https://wiki.python.org/moin/ForLoop
You need to use a while loop. If you make a while loop, and there's no instruction after the loop, it'll become an infinite loop,and won't stop until you manually stop it.
def start():
Offset = 5
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Please be sensible try just the lower case')
def getMessage():
print('Enter your message wanted to :')
return input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (Offset))
key = int(input())
if (key >= 1 and key <= Offset):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
return
I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I'm trying to figure out how to make Python go back to the top of the code. In SmallBasic, you do
start:
textwindow.writeline("Poo")
goto start
But I can't figure out how you do that in Python :/ Any ideas anyone?
The code I'm trying to loop is this
#Alan's Toolkit for conversions
def start() :
print ("Welcome to the converter toolkit made by Alan.")
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
f1 = input ("Please enter your fahrenheit temperature: ")
f1 = int(f1)
a1 = (f1 - 32) / 1.8
a1 = str(a1)
print (a1+" celsius")
elif op == "2":
m1 = input ("Please input your the amount of meters you wish to convert: ")
m1 = int(m1)
m2 = (m1 * 100)
m2 = str(m2)
print (m2+" m")
if op == "3":
mb1 = input ("Please input the amount of megabytes you want to convert")
mb1 = int(mb1)
mb2 = (mb1 / 1024)
mb3 = (mb2 / 1024)
mb3 = str(mb3)
print (mb3+" GB")
else:
print ("Sorry, that was an invalid command!")
start()
So basically, when the user finishes their conversion, I want it to loop back to the top. I still can't put your loop examples into practise with this, as each time I use the def function to loop, it says that "op" is not defined.
Use an infinite loop:
while True:
print('Hello world!')
This certainly can apply to your start() function as well; you can exit the loop with either break, or use return to exit the function altogether, which also terminates the loop:
def start():
print ("Welcome to the converter toolkit made by Alan.")
while True:
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
f1 = input ("Please enter your fahrenheit temperature: ")
f1 = int(f1)
a1 = (f1 - 32) / 1.8
a1 = str(a1)
print (a1+" celsius")
elif op == "2":
m1 = input ("Please input your the amount of meters you wish to convert: ")
m1 = int(m1)
m2 = (m1 * 100)
m2 = str(m2)
print (m2+" m")
if op == "3":
mb1 = input ("Please input the amount of megabytes you want to convert")
mb1 = int(mb1)
mb2 = (mb1 / 1024)
mb3 = (mb2 / 1024)
mb3 = str(mb3)
print (mb3+" GB")
else:
print ("Sorry, that was an invalid command!")
If you were to add an option to quit as well, that could be:
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
return
for example.
Python, like most modern programming languages, does not support "goto". Instead, you must use control functions. There are essentially two ways to do this.
1. Loops
An example of how you could do exactly what your SmallBasic example does is as follows:
while True :
print "Poo"
It's that simple.
2. Recursion
def the_func() :
print "Poo"
the_func()
the_func()
Note on Recursion: Only do this if you have a specific number of times you want to go back to the beginning (in which case add a case when the recursion should stop). It is a bad idea to do an infinite recursion like I define above, because you will eventually run out of memory!
Edited to Answer Question More Specifically
#Alan's Toolkit for conversions
invalid_input = True
def start() :
print ("Welcome to the converter toolkit made by Alan.")
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
#stuff
invalid_input = False # Set to False because input was valid
elif op == "2":
#stuff
invalid_input = False # Set to False because input was valid
elif op == "3": # you still have this as "if"; I would recommend keeping it as elif
#stuff
invalid_input = False # Set to False because input was valid
else:
print ("Sorry, that was an invalid command!")
while invalid_input: # this will loop until invalid_input is set to be False
start()
You can easily do it with loops, there are two types of loops
For Loops:
for i in range(0,5):
print 'Hello World'
While Loops:
count = 1
while count <= 5:
print 'Hello World'
count += 1
Each of these loops print "Hello World" five times
Python has control flow statements instead of goto statements. One implementation of control flow is Python's while loop. You can give it a boolean condition (boolean values are either True or False in Python), and the loop will execute repeatedly until that condition becomes false. If you want to loop forever, all you have to do is start an infinite loop.
Be careful if you decide to run the following example code. Press Control+C in your shell while it is running if you ever want to kill the process. Note that the process must be in the foreground for this to work.
while True:
# do stuff here
pass
The line # do stuff here is just a comment. It doesn't execute anything. pass is just a placeholder in python that basically says "Hi, I'm a line of code, but skip me because I don't do anything."
Now let's say you want to repeatedly ask the user for input forever and ever, and only exit the program if the user inputs the character 'q' for quit.
You could do something like this:
while True:
cmd = raw_input('Do you want to quit? Enter \'q\'!')
if cmd == 'q':
break
cmd will just store whatever the user inputs (the user will be prompted to type something and hit enter). If cmd stores just the letter 'q', the code will forcefully break out of its enclosing loop. The break statement lets you escape any kind of loop. Even an infinite one! It is extremely useful to learn if you ever want to program user applications which often run on infinite loops. If the user does not type exactly the letter 'q', the user will just be prompted repeatedly and infinitely until the process is forcefully killed or the user decides that he's had enough of this annoying program and just wants to quit.
write a for or while loop and put all of your code inside of it? Goto type programming is a thing of the past.
https://wiki.python.org/moin/ForLoop
You need to use a while loop. If you make a while loop, and there's no instruction after the loop, it'll become an infinite loop,and won't stop until you manually stop it.
def start():
Offset = 5
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Please be sensible try just the lower case')
def getMessage():
print('Enter your message wanted to :')
return input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (Offset))
key = int(input())
if (key >= 1 and key <= Offset):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
return