I would like for the input to remember the first number given to it even if you type something silly on the second input. While right now obviously the loop starts again and asks for both of the inputs again. Is there an easy way to do this?
Calculator
Give a number: 124
Give a number: dwa
This input is invalid.
Give a number: 12
Give a number:
while I would like it to do this:
Calculator
Give first number: 124
Give second number: dwa
This input is invalid.
Give second number: 12
And this is the entire code:
import math
import sys
print("Calculator")
def main():
while True:
try:
kek1 = int(input('Give a number: '))
kek2 = int(input('Give a number: '))
while True:
print('(1) +')
print('(2) -')
print('(3) *')
print('(4) /')
print('(5) sin(number1/number2')
print('(6) cos(number1/number2)')
print('(7) Change numbers')
print('(8) Quit')
print(f'Current numbers are: {kek1} {kek2}')
kaka = input("Please select something (1-6):")
plus = kek1 + kek2
minus = kek1 - kek2
times = kek1 * kek2
divide = kek1 / kek2
sin = math.sin(kek1/kek2)
cos = math.cos(kek1/kek2)
if kaka == "1":
print(f'The result is: {plus}')
if kaka == "2":
print(f'The result is: {minus}')
if kaka == "3":
print(f'The result is: {times}')
if kaka == "4":
print(f'The result is: {divide}')
if kaka == "5":
print(f'The result is: {sin}')
if kaka == "6":
print(f'The result is: {cos}')
if kaka == "7":
kek1 = int(input('Give a number: '))
kek2 = int(input('Give a number: '))
if kaka == "8":
print("Thank you!")
sys.exit(0)
except SystemExit:
sys.exit(0)
except:
print("This input is invalid.")
if __name__=="__main__":
main()
If you have any ideas on how to do this it would be a great help.
Use separate try statements for each input with their own loops
while True:
try:
kek1 = input("First number")
kek1 = int(kek1)
break
except:
print("Invalid")
continue
while True:
try:
kek2 = input("Second number")
kek2 = int(kek2)
break
except:
print("Invalid")
continue
And then go into the rest of your loop.
Sorry for a brief answer but I'm on my phone :P
instead of using try catch, you may use .isnumeric() :
kek1 = input("First number")
while not kek1.isnumeric() :
print("This input is invalid.")
kek1 = input("First number")
kek1 =int(kek1)
kek2 = input("First number")
while not kek2.isnumeric() :
print("This input is invalid.")
kek2 = input("Second number")
kek2 =int(kek1)
Related
Ok so I am very new to Python and I recently took on the challenge of creating a very simple calculator.
It works completely fine but I want to add a option to restart and go back to the main menu area rather than restarting the program entirely. How could this be done?
here is the code that i have so far
from math import sqrt
import time
print("Welcome to Calculator")
print(" #1 Add \n #2 Subtract \n #3 Multiply \n #4 Divide \n #5 Square Root")
option = input("Select one #: ")
if option == "1":
print("Addition:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) + float(num2)
print("The answer is: ", result)
elif option == "2":
print("Subtraction:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) - float(num2)
print("The answer is: ", result)
elif option == "3":
print("Multiplication:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) * float(num2)
print("The answer is: ", result)
elif option == "4":
print("Division:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) / float(num2)
print("The answer is: ", result)
elif option == "5":
print("Square Root:")
num1 = input("Enter Number: ")
result = sqrt(float(num1))
print("The answer is: ", result)
I tried the adding While True to the program but I was not able to figure out how that works.
Wrapping your whole code in a while True loop would work but you need to write an if statement at the end in order to exit the infinite loop. Here's the working code:
from math import sqrt
import time
while True:
print("Welcome to Calculator")
print(" #1 Add \n #2 Subtract \n #3 Multiply \n #4 Divide \n #5 Square Root")
option = input("Select one #: ")
if option == "1":
print("Addition:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) + float(num2)
print("The answer is: ", result)
elif option == "2":
print("Subtraction:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) - float(num2)
print("The answer is: ", result)
elif option == "3":
print("Multiplication:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) * float(num2)
print("The answer is: ", result)
elif option == "4":
print("Division:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) / float(num2)
print("The answer is: ", result)
elif option == "5":
print("Square Root:")
num1 = input("Enter Number: ")
result = sqrt(float(num1))
print("The answer is: ", result)
restart = input("Do you want to restart the program? (yes/no) ")
if restart.lower() != "yes":
break
You can add while loop like this:
while True:
option = input("Select one #: ")
if option == "1":
print("Addition:")
...
elif option == "5":
print("Square Root:")
num1 = input("Enter Number: ")
result = sqrt(float(num1))
print("The answer is: ", result)
I have created a calculator in python that can calculate the addition, subtraction, multiplication, division or modulus of two integers. What equation is executed is based on which number is type in from the menu, and I would like the user to be able to go back to the menu after an equation after being asked whether or not to "continue?". Would appreciate any help
print("MENU")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulous")
menu = input("Enter your choice: ")
if int(menu) == 1:
def additon(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
return(number1 + number2)
answer1 = additon()
print("Result:", answer1)
if int(menu) == 2:
def subtraction(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
return(number1 - number2)
answer2 = subtraction()
print("Result: ", answer2)
if int(menu) == 3:
def multiplication(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
return(number1 * number2)
answer3 = multiplication()
print("Result: ", answer3)
if int(menu) == 4:
def division(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
return(number1 / number2)
answer4 = division()
print("Result: ", answer4)
if int(menu) == 5:
def modulus(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
return(number1 % number2)
answer5 = modulus()
print("Result: ", answer5)
if int(menu) != 1 or 2 or 3 or 4 or 5:
print("Not a valid option")
First define your functions once at the top of the program, you are
currently defining functions (eg. addition) inside if statements
put all your main code in a 'forever' (while True:) loop so that each time through the loop it prints out the menu, accepts input, and displays the results then returns to the top of the loop to do it all over again
when you read user input, before converting it to an integer, add code to check if the user typed something like 'q' (for quit) and if they did then use break to take you out of the 'forver' loop and end the program
here's a skeleton version:
def print_menu():
"""print the menu as show in your code"""
def addition():
"""your addition function"""
...
def subtraction():
"""your subtraction function"""
...
# etc
while True: # 'forever' loop
print_menu()
resp = input("your choice? ")
if resp == 'q': # user wants to quit
break # so break out of forever loop
resp = int(resp) # change your resp to an integer
if resp == 1:
answer = addition()
elif resp == 2:
answer = subtraction()
elif resp == 3:
answer = multiplication()
elif resp == 4:
answer = division()
else:
print("unknown choice, try again")
continue # go back to top of loop
print("The Answer Is", answer)
An answer has already been accepted for this but I'll throw this out there anyway.
This kind of exercise is ideally suited to a table-driven approach.
The operations are trivial so rather than define discrete functions a lambda will suffice
Define a dictionary where we look up and validate the user's option.
Get the user input and carry out sanity checks.
We end up with just 2 conditional checks - one of which is merely concerned with quitting the [potentially] infinite loop.
CONTROL = {'1': lambda x, y: x + y,
'2': lambda x, y: x - y,
'3': lambda x, y: x * y,
'4': lambda x, y: x / y,
'5': lambda x, y: x % y}
while True:
print("MENU")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
option = input('Select an option or q to quit: ')
if option and option in 'qQ':
break
if option in CONTROL:
x = input('Input X: ')
y = input('Input Y: ')
try:
result = CONTROL[option](int(x), int(y))
print(f'Result={result}')
except ValueError:
print('Integer values only please')
except ZeroDivisionError:
print("Can't divide by zero")
else:
print('Invalid option')
print()
Wrap your code in a while loop. The following code should work.
def additon(number1, number2):
return (number1 + number2)
def subtraction(number1, number2):
return(number1 - number2)
def multiplication(number1, number2):
return(number1 * number2)
def division(number1, number2):
return(number1 / number2)
def modulus(number1, number2):
return(number1 % number2)
x = True
while (x):
print("MENU")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulous")
menu = input("Enter your choice: ")
if int(menu) == 1:
answer1 = additon(number1=int(input("Enter first number: ")),
number2=int(input("Enter second number: ")))
print("Result:", answer1)
elif int(menu) == 2:
answer2 = subtraction(number1=int(input("Enter first number: ")),
number2=int(input("Enter second number: ")))
print("Result: ", answer2)
elif int(menu) == 3:
answer3 = multiplication(number1=int(input("Enter first number: ")),
number2=int(input("Enter second number: ")))
print("Result: ", answer3)
elif int(menu) == 4:
answer4 = division(number1=int(input("Enter first number: ")),
number2=int(input("Enter second number: ")))
print("Result: ", answer4)
elif int(menu) == 5:
answer5 = modulus(number1=int(input("Enter first number: ")),
number2=int(input("Enter second number: ")))
print("Result: ", answer5)
elif int(menu) < 1 or int(menu) > 5:
print("Not a valid option")
go_again = input("Would you like to go again (y/n): ")
if (go_again.lower()=="n"):
x = False
else:
continue
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
see this is my code
print("""1. ADD
2. SUBTRACT
3. MULTIPLY
4. DIVIDE
5. SQUARE
6. SQUARE ROOT
7. CUBE
8. CUBE ROOT
9. POWER OF A NUMBER
10. FACTORIAL
11. TRIANGLE'S PERIMETER
12. TRIANGLE'S AREA
13. QUADRILATERAL'S PERIMETER
14. PARALLELOGRAM'S AREA
15. RHOMBUS'S AREA
17. RECTANGLE'S AREA
18. SQUARE'S AREA
19. TRAPEZIUM'S AREA
20. CIRCLE'S CIRCUMFERENCE
21. CIRCLE'S AREA
22. QUADRATIC EQUATION
23. SIMPLE INTEREST
24. COMPOUND INTEREST""")
while True:
user = str(input("Enter GO to continue or Q to exit: "))
if user == 'GO':
user_input = str(input("Enter here the serial number or the name in capital for what you want to calculate: "))
if user_input == 'ADD' or 1 :
add()
elif user_input == 'SUBTRACT' or 2 :
sub()
elif user_input == 'MULTIPLY' or 3 :
mlt()
elif user_input == 'DIVIDE' or 4 :
div()
elif user_input == 'SQUARE' or 5 :
sqr()
elif user_input == 'SQUARE ROOT' or 6 :
sqrt()
elif user_input == 'CUBE' or 7 :
cube()
elif user_input == 'CUBE ROOT' or 8 :
cube_root()
elif user_input == 'POWER OF A NUMBER' or 9 :
power()
elif user_input == "TRIANGLE'S PERIMETER" or 11 :
triangle_perimeter()
elif user_input == "QUADRILATERAL'S PERIMETER" or 13 :
quadrilateral_perimeter()
elif user_input == "PARALLELOGRAM'S AREA" or 14 :
parallelogram_area()
elif user_input == 'FACTORIAL' or 10 :
factorial()
elif user_input == "RHOMBUS'S AREA" or 15 :
rhombus_area()
elif user_input == "RECTANGLE'S AREA" or 17 :
rectangle_area()
elif user_input == "SQUARE'S AREA" or 18 :
square_area()
elif user_input == "CIRCLE'S AREA" or 21 :
circle_area()
elif user_input == "CIRCLE'S CIRCUMFERENCE" or 20 :
circle_circumference()
elif user_input == "QUADRATIC EQUATION" or 22 :
qaudratic_solver()
elif user_input == "SIMPLE INTEREST" or 23 :
simple_interest()
elif user_input == "COMPOUND INTEREST" or 24 :
compound_interest()
elif user_input == "TRIANGLE'S AREA" or 12 :
triangle_area()
elif user_input == "TRAPEZIUM'S AREA" or 19 :
trapezium_area()
else:
print("Invalid input!!")
elif user == 'Q':
break
else:
print("Invalid input!!")
and when I run it when I put any number or name in the input line instead of calling out the function with respect to the number or name it calls out to the add() function which relates number 1 and and name "ADD"
Why is this happening? Please help me...
PS: I had done this in google colab so the actual functions are written in a separate "cell" if you know google colab you'll know :) but anyways here are functions too
import cmath
import functools
def add():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the first number: "))
val2 = float(input("Enter the second number: "))
print("The result is: ", val1 + val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def sub():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the first number: "))
val2 = float(input("Enter the second number: "))
print("The result is: ", val1 - val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def mlt():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the first number: "))
val2 = float(input("Enter the second number: "))
print("The result is: ", val1*val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def div():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the first number: "))
val2 = float(input("Enter the second number: "))
print("The result is: ", val1/val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def sqrt():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
print("The result is: ", cmath.sqrt(val1))
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def sqr():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
print("The result is: ", val1**2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def power():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
val2 = float(input("Enter the power of the number: "))
print("The result is: ", val1**val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def square_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the value of the side: "))
print("The area of the square is: ", val1**2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def rectangle_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the value of the length: "))
val2 = float(input("Enter the value of the breadth: "))
print("The area of the square is: ", val1*val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def circle_circumference():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the radius of the circle: "))
print("The circumference of the circle is: ", (val1*44)/7)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def circle_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the radius of the circle: "))
print("The area of the circle is: ", (val1*val1*22)/7)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def rhombus_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the value of first diagonal: "))
val2 = float(input("Enter the value of the second diagonal: "))
print("The area of the rhombus is: ", 0.5*val1*val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def parallelogram_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the value of height: "))
val2 = float(input("Enter the value of the correspondent base: "))
print("The area of the parallelogram is: ", 0.5*val1*val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def quadrilateral_perimeter():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
a = float(input("Enter the first side of the quadrilateral: "))
b = float(input("Enter the second side of the quadrilateral: "))
c = float(input("Enter the third side of the quadrilateral: "))
d = float(input("Enter the foruth side of the quadrilateral: "))
if ((a + b + c> d) and (a + b + d> c) and (b + c + d> a) and (a + d + c> b)) :
print("The perimeter of the qaudrilateral is : ", a+b+c+d)
else :
print("Quadrilateral is not valid.")
elif user_input == 'Q':
break
else:
print("invalid input")
def trapezium_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
par1 = float(input("Enter the value of the first parallel side: "))
par2 = float(input("Enter the value of the second parallel side: "))
hei1 = float(input("Enter the the value of the height: "))
print("The area of the trapezium is: ", 0.5*hei1*(par1+par2))
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def triangle_perimeter():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
a = float(input("Enter the first side of the triangle: "))
b = float(input("Enter the second side of the triangle: "))
c = float(input("Enter the third side of the triangle: "))
if ((a + b > c) and (a + c > b) and (b + c > a)) :
print("The perimeter of the traingle is: ", a+b+c)
else :
print("Triangle is not valid.")
elif user_input == 'Q':
break
else:
print("invalid input")
def triangle_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
area_method = str(input("Enter Heron or Traditional(0.5*height*base): "))
if area_method == 'Heron':
a = float(input("Enter the first side of the triangle: "))
b = float(input("Enter the second side of the triangle: "))
c = float(input("Enter the third side of the triangle: "))
if ((a + b > c) and (a + c > b) and (b + c > a)) :
s = (a+b+c)*0.5
print("The area of the triangle is ", cmath.sqrt((s-a)*(s-b)*(s-c)*(s)))
else:
print("Triangle is not valid!!")
elif user_input == 'Traditional':
a = float(input("Enter the value of the height: "))
b = float(input("Enter the value of the correspondent base: "))
print("The area of the triangle is ", 0.5*a*b)
else:
print("Invalid input!!")
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def qaudratic_solver():
while True:
user_input = str(input("Enter the GO to continue or Q to exit: "))
if user_input == 'GO':
a = float(input("Enter the coeffiecient of x^2: "))
b = float(input("Enter the coeffiecient of x: "))
c = float(input("Enter the constant: "))
D = cmath.sqrt(b*b - 4*a*c)
F = 2*a
X1 = (-b + D)/(F)
X2 = (-b - D)/(F)
print("The values of x are: ", X1, ", ", X2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def cube():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
print("The result is: ", val1**3)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def cube_root():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
print("The result is: ", val**1/3)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def compound_interest():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
P = float(input("Enter the principal amount: "))
IR = float(input("Enter the interest rate: "))
T = float(input("Enter the time period: "))
N = float(input("Enter the number of times interest is compunded per unit time 't': "))
A = P*((1+((IR/100)/N))**(N*T))
CI = A-P
print("The final amount will be ", A, " and the compund interest will total up to ", CI)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def simple_interest():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
P = float(input("Enter the principal amount: "))
R = float(input("Enter the interest rate: "))
T = float(input("Enter the time period: "))
SI = (P*R*T)/100
A = P + SI
print("The final amount will be ", A, " and the simple interest will total up to ", SI)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def factorial():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
a = int(input("Enter the number: "))
print(functools.reduce(lambda x,y : x * y, range(1,a+1)))
elif user_input == 'Q':
break
else:
print("Invalid input!!")
The condition in:
if user_input == 'ADD' or 1:
doesn't quite do what you think it does.
Each side of an or is usually a separate sub-expression that is evaluated independently, then the results are or'ed together. The proper expression for your case would be:
if user_input == 'ADD' or user_input == '1':
Note the quoted '1' in my version, the string '1' is not the same as the integer 1, and you are working with strings here.
However, a more Pythonic way would be:
if user_input in ['ADD', '1']:
which would allow you to keep code much shorter for things like:
if number in [2, 3, 5, 7, 11, 13, 17, 19]:
print(f"{number} is a prime under twenty")
Interestingly enough, the result of an expression False or something is not necessarily True or False, it's actually something. You can see this with the following transcript:
>>> True or 'hello'
True
>>> False or 'hello'
'hello'
More detail can be found here:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value.
When the something is an expression like a == b, it is a boolean value that comes out. But that's not the or doing that, it's the comparison.
That means the result of the expression you've used, user_input == 'ADD' or 1, will be True if the input was ADD, or 1 if not.
And it's not until you evaluate that 1 in a truthy context that it gets forced to True. Python's truthiness rules are basically everything is truthy except for:
empty strings.
empty collections (lists, tuples, dictionaries, sets, frozensets, and ranges).
zero of any numeric type (integer, floating point, or complex).
None.
user defined classed that implement the __bool__ method and decide to return a falsey value.
and, of course, False itself.
And, just as an aside, you should probably be aware that input() already gives you a string, there's no need to call str() on it.
In other words, the expression str(input("What? ")) is about as useful as int(42), harmless but unnecessary :-)
The or statement is to check for another condition. Here with your or 1 you are checking if 1 != 0 (because in boolean is 0 is false and everything else is true).
So what you need in the end is to check if user_input is 1.
You need to change your conditions line to if user_input == 'ADD' or user_input == '1' :
EDIT: as paxdiablo said if user_input in ['ADD', '1'] would be a more pythonic way to do it.
Hope this helps and you understood your mistake.
if user_input == 'ADD' or 1 :
The above condition is evaluates to true due to 1.
I'm having trouble breaking out of the nested while loop in my code completely. How do I break out of two loops? Here's my attempt:
while continue_enter == True:
while True:
try:
enter_result_selection = int(input("What test would you like to enter results for? Please enter a number - Reading Test: 1 Writing Test: 2 Numeracy Test: 3 Digital Literacy Test: 4 All Tests: 5 - "))
if enter_result_selection == 1:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_reading = int(input("Enter {}'s percentile for the reading test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
elif enter_result_selection == 2:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_writing = int(input("Enter {}'s percentile for the writing test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
elif enter_result_selection == 3:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_numeracy = int(input("Enter {}'s percentile for the numeracy test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
elif enter_result_selection == 4:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_digtialliteracy = int(input("Enter {}'s percentile for the digtial literacy test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
elif enter_result_selection == 5:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_reading = int(input("Enter {}'s percentile for the reading test (%): ".format(name)))
student_result_writing = int(input("Enter {}'s percentile for the writing test (%): ".format(name)))
student_result_numeracy = int(input("Enter {}'s percentile for the numeracy test (%): ".format(name)))
student_result_digtialliteracy = int(input("Enter {}'s percentile for the digtial literacy test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
else:
print("Sorry, this is an invalid number. Please only enter numbers ranging from the values 1 - 5.")
break
except ValueError:
print("Sorry, your input was invalid. Please enter a number and try again.")
while continue_enter == True or continue_enter == False:
ask_continue_enter = input("Would you like to enter results for another student? ")
if ask_continue_enter.lower() == "yes" or ask_continue_enter.lower() == "y":
continue_enter == True
break
elif ask_continue_enter.lower() == "no" or ask_continue_enter.lower() == "n":
continue_enter == False
break
else:
print("Sorry, this is an invalid input. Please enter with 'Yes' or 'No'")
if continue_enter == True:
continue
elif continue_enter == False:
break
Here is an example of how to break out of nested loops using exceptions:
class MyException(Exception):
pass
x=1
y=1
try:
while x<10:
y=1
while y<10:
if x==5 and y==5:
raise MyException
y=y+1
x=x+1
except MyException:
print x
print y
Output:
$ python prog.py
5
5
You don't HAVE to define an own exception. You can just use the standard ones, or even just use raise Exception('Something happened'). However, I would STRONGLY advice not to do that. See this link for more info: https://stackoverflow.com/a/24065533/6699433
EDIT:
I just read that you can use the builtin exception StopIteration. That seems suitable.
Okay, this is my code, it is in python 3.4.3 and I do not know how I would go about allowing user inputs to be floats. Any help would be greatly appreciated.
It is a calculator and works perfectly but it does not allow user inputs to be floats(have decimal places) and a lot of calculations take place with inputs of decimal numbers so it kinda needs it. Thanks if you take the time to read that!
import time
def cls(): print ("\n"*100)
def add():
cls()
print("you have selected addition")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("Enter a numberical interger")
b = input ("enter your second number: ")
if b.isdigit() == True:
b = int(b)
print ("\n")
print ("ANSWER:",a,"+",b,"=",a+b)
print ("\n")
def sub():
cls()
print("you have selected subtraction")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
print("\n")
print ("ANSWER:",a,"-",b,"=",a-b)
print("\n")
def multi():
cls()
print ("you have selected multiplication")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
print("\n")
print("ANSWER:",a,"*",b,"=",a*b)
print("\n")
def divide():
cls()
print ("you have selected division")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
c = (a/b)
if a%b ==0 :
print("\n")
print ("ANSWER:",a,"/",b,"=",int(c))
print("\n")
else :
print("\n")
print ("ANSWER:",a,"/",b,"=",float(c))
print("\n")
def indice():
cls()
print ("you have selected indice multiplication")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
while (int(a)) >=1000000000000:
print("value too high, enter a lower value")
time.sleep(1)
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
while (int(b)) >=1000:
print("value too high, enter a lower value")
time.sleep(1)
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
print("\n")
print("ANSWER:",a,"To the power of",b,"=",a**b)
print("\n")
def Tconv():
cls()
print("You have selected unit conversion")
print("\n")
print("Enter 1 for conversion from celcius")
print("Enter 2 for conversion from kelvin")
print("\n")
a = input("Enter your choice: ")
if a == "1":
cls()
Tcelc()
elif a == "2":
cls()
Tkelv()
else:
print("Not a valid entry, try again")
time.sleep(1)
cls()
Tconv()
def Tcelc():
print("You have selected conversion from celcius")
print("\n")
a = input("Enter your celcius value: ")
if a.isdigit() == False:
print("Not a valid entry")
time.sleep(1)
cls()
Tcelc()
elif a.isdigit() == True:
print("\n")
print("AWNSER = ",(int(a))+273,"Kelvin")
print("\n")
def Tkelv():
print("You have selected conversion from kelvin")
print("\n")
a = input("Enter your kelvin value: ")
if a.isdigit() == False:
print("Not a valid entry")
time.sleep(1)
Tkelv()
elif a.isdigit() == True:
print("ANSWER = ",(int(a))-273,"Celcius")
print("\n")
def OpEx():
cls()
print("what operation would you like to preform?")
print("\n")
print("Enter 1 for addition")
print("Enter 2 for subtraction")
print("Enter 3 for multliplication")
print("Enter 4 for division")
print("Enter 5 for indice multiplication")
print("Enter 6 for unit conversion")
print("\n")
print("Or type 'close' to exit the program")
print("\n")
task = input("enter your choice: ")
print("\n")
if task == "1":
add()
menu()
elif task == "2":
sub()
menu()
elif task == "3":
multi()
menu()
elif task == "4":
divide()
menu()
elif task == "5":
indice()
menu()
elif task == "6":
Tconv()
menu()
elif task == "close":
exit()
else:
print ("not a valid entry")
time.sleep(2)
OpEx()
def menu():
Q1 = input("Type 'yes' to preform a calculation type 'no' to exit: ")
if Q1 == "yes":
OpEx()
if Q1 == "no":
print("sorry I could not be of futher service")
time.sleep(1)
exit()
else:
print("\n")
print("Not a valid entry, try again")
print("\n")
time.sleep(1)
cls()
menu()
cls()
menu()
You're converting user input to integers, which don't handle floating point all that well. Try converting to float instead, e.g.:
a = float(a)
I would be cautious taking the input as a float because python and many other languages floats are not represented as they may seem. I would recommend pulling the input as a string and then casting it later.