I am building off of a simple Pythagorean Theorem calculator I wrote a while back to make a more advanced version as an introduction to classes and functions. I've successfully programmed it to solve for c, either a or b and to loop back the calculation function if the user needs to do another calculation.
I've recently tried to add a main menu function, so if the user needed to solve for c, and now needs to solve for b, he/she can go back to the main menu to select the option they need. With some difficulty, I've managed to code it to where it will
Go back to the main menu
The user selects another option
The user performs the calculation as needed
1-3 repeats successfully
But then if they try to go back and select another option, it just returns to the python prompt. It's very hard for me to describe this problem in words, as other things go wrong as well. Such as, if you preform less than 2 calculations and try to go back, the method you're currently on keeps looping. I have no idea why any of this is happening, and it seems I'm doing everything right. I've tried troubleshooting, but as said above, my particular situation is hard to describe. I'm convinced that I haven't done it right, and I would like to know how. My code and screenshots are attached below.
Code
' A Pythagoren Therom Calculator (v.2.0)
By: Anon_104'''
#imports
import time, math
#Welcome statement (Welcomes the user)
print("Welcome to the pythagorean theorem calculator!")
time.sleep(1)
#a class to organize and keep everything in order ;)
class pytha:
#custom function for solving for c
def cal():
global ques1
a = int(input('Please enter the "A" value: '))
b = int(input('Please enter the "B" value: '))
print("Calculating...")
time.sleep(1)
print('The "C" value is ')
c = math.sqrt(a*a + b*b)
print(c)
ques1 = str(input("Another Calculation? (y/n) Or return to main menu? (back)"))
#function for solving for a or b, given c
def cal2():
global ques2
var = input('Please input either the "A" or "B" value: ')
c = input('Please input the "C" value: ')
var2 = float(c)**2 - float(var)**2
ans = math.sqrt(var2)
print('The "A"/"B" value is {0}'.format(ans))
ques2 = str(input("Another Calculation? (y/n) Or return to main menu? (back)"))
def mainmenu():
global query1
query1 = input('Welcome to the main menu! Solve for "C" or "A"/"B"? (opt1/opt2)')
pytha.mainmenu()
#The loop and break code for function 1
if query1 == 'opt1':
pytha.cal()
while ques1 == 'y':
pytha.cal()
if ques1 == 'back':
pytha.mainmenu()
while query1 == 'opt1':
pytha.cal()
elif ques1 == 'n':
print("Quitting... ")
time.sleep(1.6)
quit
#The loop and break code for function 2
if query1 == 'opt2':
pytha.cal2()
while ques2 == 'y':
pytha.cal2()
if ques2 == 'back':
pytha.mainmenu()
while query1 == 'opt2':
pytha.opt2
elif ques2 == 'n':
print("Quitting... ")
time.sleep(1.6)
quit
Screenshot
It doesn't loop again
P.S This is my first question EVER on a help board for anything, so go easy on me if I haven't done something right.
You don’t need the query statements at the end. Include the calls to your methods in the methods or create a new one for the purpose of returning to the main menu. I would also suggest using float() instead of int() when dealing with possible decimals, but I did not change this.
class Pytha(object):
def __init__(self):
import time, math
self.math = math
self.time = time
print("Welcome to the pythagorean theorem calculator!\n")
self.time.sleep(1)
self.mainmenu()
#custom function for solving for c
def cal(self):
try:
a = int(input('\nPlease enter the "A" value: '))
b = int(input('Please enter the "B" value: '))
print("Calculating...")
self.time.sleep(1)
print('The "C" value is ')
c = self.math.sqrt(a*a + b*b)
print(c)
except ValueError:
print("\nError: Please enter a number\n")
self.cal()
self.rerun()
#function for solving for a or b, given c
def cal2(self):
try:
var = int(input('\nPlease input either the "A" or "B" value: '))
c = int(input('Please input the "C" value: '))
var2 = float(c)**2 - float(var)**2
ans = self.math.sqrt(var2)
print('The "A"/"B" value is {0}'.format(ans))
except ValueError:
print("\nError: Please enter a number\n")
self.cal2()
self.rerun()
def mainmenu(self):
query1 = str(input('Welcome to the main menu! Solve for "C" or "A"/"B" or quit program? (opt1/opt2/q)\n'))
if query1.lower() == "opt1":
self.cal()
elif query1.lower() == "opt2":
self.cal2()
elif query1.lower() == 'q':
quit()
else:
print("Error: Please type 'opt1' or 'opt2' or 'q'\n")
self.mainmenu()
def rerun(self):
query1 = str(input('\nAnother Calculation? Solve for "C" or "A"/"B" or quit program? (opt1/opt2/q)\n'))
if query1.lower() == "opt1":
self.cal()
elif query1.lower() == "opt2":
self.cal2()
elif query1.lower() == 'q':
quit()
else:
print("Error: Please type 'opt1' or 'opt2' or 'q'\n")
self.rerun()
app = Pytha()
There were more things you could do to clean this up. I put everything in the class and called everything as self.something().
I added .lower() for your responses in case a user does OPT1 or Opt1.
I created a single rerun function to call after each operation. It automatically goes to this after the first run.
I also used try/except for your inputs because you will get a ValueError by entering a non-numeric character when calling int(). Instead, it now will tell the user to enter a number and will try again.
For quit, you need to call it as quit().
The init loads as soon as you call the class, which allows you to do things to initiate it, such as including your imports, setting variables, printing messages, and running functions. This way it is all inclusive.
Finally, it is standard practice to begin you class name with a capital letter (though not a requirement).
Hope this helps you get a better idea of how to use classes.
EDIT:
If you want to build a custom import for your tool to use without direct user interaction, you can build it like this:
class Pythag(object):
#custom function for solving for c
def solve_C(a, b):
from math import sqrt
a = int(a)
b = int(b)
c = sqrt(a*a + b*b)
return (c)
#function for solving for a or b, given c
def solveAB(var, c):
from math import sqrt
var = int(var)
c = int(c)
var2 = float(c)**2 - float(var)**2
ans = sqrt(var2)
return(ans)
Then you can import it into another script. If your pythag script is named pythag.py, you would import it as
from pythag import Pythag
Then call the modules like this:
Pythag.solve_C(4,5)
Related
Python code to generate two random variables that can add up and give an answer
print("What is You Favorite Maths Operation \nAddition(a) \nSubstraction(s) \nMultiplication(M) \nDivision(d)")
#user input operator from the table given
class cooperators:
def choose(self):
return input("Choose One Of Them To Solve Some Interesting Problem:")
def operator(self,user):
#if you chose a then addition
if user =='a':
return True
#if you chose s then Substraction
elif user =='s':
return True
#if you chose m then multiplication
elif user =='m':
return True
#if you chose d then division
elif user =='d':
return False
def play(self,users):
randomNumber = random.randint(1, 10)
if users =='a':
print(f"Addition: {randomNumber} \n {randomNumber}")
print("Your answer: ")
print(f"Correct answer is: {randomNumber}+{randomNumber}")
t= caloperators()
t.choose()
t.operator()
t.play()
print(t.choose)
print(t.operator)
print(t.play)
I am not able to get an answer but getting errors and also if someone can complete the code it will really help to end this project and complete it.
t.operator()
You're not passing any arguments into this. hence the error.
You can do:
a = t.choose()
t.operator(a)
since choose() is returning the input.
You're then passing that input into a variable called a, which is then passed into operator(user).
in this case a == user.
You will then have the problem of not passing any arguments into play(users)
which you then can pass a into that too:
t.play(a)
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...
So, I'm just fooling around in python, and I have a little error. The script is supposed to ask for either a 1,2 or 3. My issue is that when the user puts in something other than 1,2 or 3, I get a crash. Like, if the user puts in 4, or ROTFLOLMFAO, it crashes.
EDIT: okay, switched it to int(input()). Still having issues
Here is the code
#IMPORTS
import time
#VARIABLES
current = 1
running = True
string = ""
next = 0
#FUNCTIONS
#MAIN GAME
print("THIS IS A GAME BY LIAM WALTERS. THE NAME OF THIS GAME IS BROTHER")
#while running == True:
if current == 1:
next = 0
time.sleep(0.5)
print("You wake up.")
time.sleep(0.5)
print("")
print("1) Go back to sleep")
print("2) Get out of bed")
print("3) Smash alarm clock")
while next == 0:
next = int(input())
if next == 1:
current = 2
elif next == 2:
current = 3
elif next == 3:
current = 4
else:
print("invalid input")
next = 0
Use raw_input() not input() the latter eval's the input as code.
Also maybe just build a ask function
def ask(question, choices):
print(question)
for k, v in choices.items():
print(str(k)+') '+str(v))
a = None
while a not in choices:
a = raw_input("Choose: ")
return a
untested though
since the input() gives you string value and next is an integer it may be the case that crash happened for you because of that conflict. Try next=int(input()) , i hope it will work for you :)
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