This question already has answers here:
How do I restart a program based on user input?
(6 answers)
Closed 4 years ago.
This is a simple calculator i wrote but after finishing it won't restart the application
this is my code:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select from the list bellow which oporation you want the calculator to do.")
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
choice = input("Enter choice(a/s/m/d):")
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd':
print (" the letter you intered is not in our lists!")
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 's':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == 'm':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == 'd':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
input("press enter to close")
when its finished i want it to ask the user if they want to restart or not . i used different while looping its not working.
Just loop until the user wants to quit:
def main():
print('Select from the list below which operation you want the calculator to do.')
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
while True:
choice = input("Enter choice(a/s/m/d) or q to quit:")
if choice not in {"a", "s", "m", "d","q"}:
print (" the letter you entered is not in our lists!")
continue # if invalid input, ask for input again
elif choice == "q":
print("Goodbye.")
break
num1 = int(input("Enter an integer as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print("{} + {} = {}".format(num1, num2, add(num1, num2)))
elif choice == 's':
print("{} - {} = {}".format(num1, num2, subtract(num1, num2)))
I used str.format to print your output, if choice not in {"a", "s", "m", "d","q"} uses in to test for membership replacing the long if statement.
You might want to wrap the int input inside a try/except to avoid your program crashing if the user does not enter the correct input.
try:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
except ValueError:
continue
If you want to do it like the example in your comment:
def main():
print('Select from the list below which operation you want the calculator to do.')
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
while True:
choice = raw_input("Enter choice(a/s/m/d)")
if choice not in {"a", "s", "m", "d","q"}:
print (" the letter you entered is not in our lists!")
continue
num1 = int(input("Enter an integer as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print("{} + {} = {}".format(num1, num2, add(num1, num2)))
elif choice == 's':
print("{} - {} = {}".format(num1, num2, subtract(num1, num2)))
inp = input("Enter 1 to play again or 2 to exit")
if inp == "1":
main()
else:
print("thanks for playing")
break
Instead of this:
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
Use this:
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
elif choice==e:
print("goodbye")
break
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
You'll need to wrap the part that's processing user input in a while loop. You'll also need an option to break that while loop in your selection process. I added an input value of e that handles exiting the loop. Your first if statement and the else statement at the end were redundant, so I switched them around a little as well.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
while True:
print("Select from the list bellow which oporation you want the calculator to do.")
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
print("E.Exit")
choice = input("Enter choice(a/s/m/d/e):")
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 's':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == 'm':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == 'd':
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == 'e':
print("Goodbye")
break
Related
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 am making a python calculator program that asks a user after completing one calculation whether they want to continue or not. If the user says Yes the loop should run or else it should stop. I am Facing a problem where a user says yes or no the loop still executes anyhow. Why is it so ???
print("This is a Calculator In Python. !!!")
print("I Can Do Addition, Subtraction, Multiplication and Division.!!")
def addition():
print("Please Don't Enter Float Values Here.")
num1 = int(input("Enter First Number.!!"))
num2 = int(input("Enter Second Number. !!"))
result = num1 + num2
return result
def subtraction():
print("Please Don't Enter Float Values Here.")
num1 = int(input("Enter First Number.!!"))
num2 = int(input("Enter Second Number.!!"))
result = num1 - num2
return result
def multiplication():
print("You Can Enter Float Values Here.")
num1 = float(input("Enter First Number.!!"))
num2 = float(input("Enter Second Number.!!"))
result = num1 * num2
return result
def division():
print("You Can Enter Float Values Here.")
num1 = float(input("Enter First Number.!!"))
num2 = float(input("Enter Second Number.!!"))
result = num1 / num2
return result
print("""1. a for Addition
2. s for subtraction
3. m for multiplication
4. d for Division""")
select = "Yes"
while select:
choice = str(input("You Choose The Operation."))
if choice == "a":
print(addition())
elif choice == "s":
print(subtraction())
elif choice == "m":
print(multiplication())
elif choice == "d":
print(division())
else:
print("Invalid Input")
select=str(input('Continue Yes or No '))
print("Thank you..!")
You've defined your loop as while select, which means as long as select is considered to not be None, it will continue looping
In your loop, you assign the user input to select, which means as long as the user inputs anything, it will always keep looping.
To fix this, you should have the while loop check if select is "yes":
while select.lower().strip() == "yes":
choice = input("You Choose The Operation. ")
if choice == "a":
print(addition())
elif choice == "s":
print(subtraction())
elif choice == "m":
print(multiplication())
elif choice == "d":
print(division())
else:
print("Invalid Input")
select = input("Continue Yes or No ")
print("Thank you..!")
Also, input() returns a string so you don't need to wrap it in a str() call.
Hello I am having a trouble while doing my simple calculator code :D
def cal():
while True:
print ("welcome to my calculator!")
print("choose an operation")
op = input(" +, - ,/ ,*")
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2)
elif op == "/":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 / num2)
else:
break
cal()
When ever I run the code it says invalid syntax at the elif
what is wrong here?
You never closed the bracket on the print function. Same goes for the other if statement. You should use indentation of 4 spaces in the future, too.
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2))
You missed a bunch of brackets. If you want to take your program further use this as a model:
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
Need to add a loop to my calculator by giving the user an option to restart the calculator by putting the code in a while loop with the condition that the input from user should be, 'y' or 'Y'.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
Just add somethings to Alex's post
cont = "y"
while cont.lower() == "y":
print("Select operation\n1.Add\n2.Subtract\n3.Multiply\n4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", (num1 + num2))
elif choice == '2':
print(num1,"-",num2,"=", (num1 - num2))
elif choice == '3':
print(num1,"*",num2,"=", (num1 * num2))
elif choice == '4':
print(num1,"/",num2,"=", (num1 / num2))
else:
print("Invalid input")
cont = input("Continue?y/n:")
if cont == "n":
break
Don't really see what the problem is, you can just use another input statement and check the value in the while loop condition...
cont = "y"
while cont == "y" or cont == "Y":
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", (num1 + num2))
elif choice == '2':
print(num1,"-",num2,"=", (num1 - num2))
elif choice == '3':
print(num1,"*",num2,"=", (num1 * num2))
elif choice == '4':
print(num1,"/",num2,"=", (num1 / num2))
else:
print("Invalid input")
cont = raw_input("Continue?y/n:")
you can simply modify your code like this
def continue():
resp = input("Continue ? Y/N ")
if resp == "n" or resp == "N":
return False
return True
while True:
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", (num1 + num2))
elif choice == '2':
print(num1,"-",num2,"=", (num1 - num2))
elif choice == '3':
print(num1,"*",num2,"=", (num1 * num2))
elif choice == '4':
print(num1,"/",num2,"=", (num1 / num2))
else:
print("Invalid input")
if not continue() :
break
you can change the continue function as you like
Here's a while loop example :
Changed
again = "y"
while again:
# ...
#enter your code here
# ...
a = input("do you want to do again (y/Y): ")
if a not in ("y","Y"):
a=""
enter code here
while True:
b = int(input('first num: '))
c = input('operator: ')
d = int(input('second num: '))
if c == '+':
print(b + d)
elif c == '-':
print(b - d)
elif c == '*':
print(b * d)
elif c == '/':
print(b / d)
q = input('do you want to continue?: ')
if q == 'y':
continue
else:
break
Here's another while loop example
menu ="""
0. chose 0 to quit
1. chose 1 to add
2. chose 2 to sub
3. chose 3 to multi
4. chose 4 to div
"""
chose= None
while(chose != 0):
print(menu)
num1 =int(input('first num is: '))
num2 =int(input('second num is: '))
chose= int(input("plz enter your chose: "))
if(chose == 1):
print(num1, " + ",num2," = ",num1+num2)
elif(chose == 2):
print(num1, " - ",num2," = ",num1+num2)
elif(chose == 3):
print(num1, " * ",num2," = ",num1+num2)
elif(chose == 4):
if(num2 == 0):
print("You can not divide by zero")
else:
print(num1, " / ",num2," = ",num1+num2)
else:
print('plz enter a correct option')