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")
Related
How can i add a function to show me history of calculations and results? Either in the console or create a .txt file. This is code I got from the internet BTW. I am a beginner to python also.
Program make a simple calculator
# 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")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(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))
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
Modification of your text to write to a file (e.g. 'log.txt')
Opens file in append mode
Using Python string interpolation to compose string to write
Code
# 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")
with open('log.txt', 'a') as history: # open file 'log.txt' in append mode for logging
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
history.write(f'{num1} + {num2} = {add(num1, num2)}\n') # append to history file
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
history.write(f'{num1} - {num2} = {subtract(num1, num2)}\n') # append to history file
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
history.write(f'{num1} * {num2} = {multiply(num1, num2)}\n') # append to history file
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
history.write(f'{num1} / {num2} = {divide(num1, num2)}\n') # append to history file
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
you can add a print statement inside each of your functions.
i.e:
def add(x, y):
result = x + y
print('add', x, y, 'result =', result)
return result
Here is a possible solution:
# 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")
print("5.History")
history = []
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4/5): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4', '5'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = add(num1, num2)
history.append(f'{num1} + {num2} = {result}')
print(history[-1])
elif choice == '2':
result = subtract(num1, num2)
history.append(f'{num1} - {num2} = {result}')
print(history[-1])
elif choice == '3':
result = multiply(num1, num2)
history.append(f'{num1} * {num2} = {result}')
print(history[-1])
elif choice == '4':
result = divide(num1, num2)
history.append(f'{num1} / {num2} = {result}')
print(history[-1])
elif choice == '5':
print(*history, sep='\n')
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
Basically you keep a list with all previous printed messages, and you print them all whenever the user chooses option '5'.
One really neat way to do it is with decorators. With this approach you only have to write the logic once and can apply it to all the functions. This logic is specific for binary operations but could obviously be extended and also modified to write to a log file:
# `log_op` is the decorator
def log_op(f_name, f_op):
def wrapper(f):
def inner(*args, **kwargs):
result = f(*args, **kwargs)
print(f"{f_name}: {args[0]} {f_op} {args[1]} = {result}")
return result
return inner
return wrapper
#log_op('add', '+')
def add(x, y):
return x + y
#log_op('subtract', '-')
def subtract(x, y):
return x - y
add(1,2) # add: 1 + 2 = 3
subtract(1,2) # subtract: 1 - 2 = -1
Python - Reset button calculator and other issues
This is a python calculator. I developed a part here. but, In this calculator, when the user enters two wrong numbers or one wrong operator, the reset function is given by $ + enter. How to add reset capability to code?
How to fix it?
Program make a simple calculator
# 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
# This function uses to power
def power(x, y):
return x**y
# This function uses for the remainder
def remainder (x, y):
return x % y
print("Please select the operation.")
print("1:Add")
print("2:Subtract")
print("3:Multiply")
print("4:Divide")
print("5:Power")
print("6:remainder")
print("7.Terminate")
print("8.Reset")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4/5/6): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4','5' ,'6'):
num1 = float(input("Enter first number: "))
num2 = float(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))
elif choice == '5':
print(num1, "**", num2, "=", power(num1, num2))
elif choice == '6':
print(num1, "%", num2, "=", remainder(num1, num2))
elif choice == '7':
print(num1 , "#", num2, "=", terminate(num1,num2))
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
print("Thank you")
#this funtion uses to optimize the code [ select_op(choice) funtion also used here ]
def find(choice):
if reset_operand == "yes":
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
select_op(choice)
elif reset_operand == "no":
select_op(choice)
# take input from the user
choice = input("Enter choice(1/2/3/4/5/6): ")
if choice in ('1', '2', '3', '4', '5', '6'):
reset_operation = input("Do you need to change the operation? (yes/no): ")
if reset_operation == "yes":
choice = input("Enter again choice(1/2/3/4/5/6): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
reset_operand = input("Do you need to change the reset_operand? (yes/no): ")
if reset_operation == "no":
if choice in ('1', '2', '3', '4', '5', '6'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
reset_operand = input("Do you need to change the reset_operand? (yes/no): ")
find(choice)
else:
print("Unrecongnized operation !")
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 1 year ago.
Hello all genius fellows, please find below code. code is running excellent till end but in the end while it ask for Y/N after 1st iteration no matter what I press its breaking the statement and exiting the loop.
class simpleCalculator:
def addition(self, num1, num2):
return num1+num2
def sub(self, num1, num2):
return num1-num2
def multiplication(self, num1, num2):
return num1*num2
def division(self, num1, num2):
return num1/num2
a = simpleCalculator()
print("Enter your choice: ")
print(''' 1.Addition
2.Subtraction
3.Multiplication
4.Division''')
while True:
choice = int(input("Enter your choice(1/2/3/4): "))
if choice in (1, 2, 3, 4):
num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))
if choice == 1:
print(f"Addition of {num1} & {num2} is {a.addition(num1,num2)}")
elif choice == 2:
print(f"Subtraction of {num1} & {num2} is {a.sub(num1,num2)}")
elif choice == 3:
print(
f"Multiplication of {num1} & {num2} is {a.multiplication(num1,num2)}")
elif choice == 4:
print(f"Division of {num1} & {num2} is {a.division(num1,num2)}")
next_cal = input("You want more calculation(Y/N): ")
if next_cal == "N" or "n":
print("****** Thank you for using world's best calculator ******")
break
else:
print("Invalid Choice")
class simpleCalculator:
def addition(self, num1, num2):
return num1+num2
def sub(self, num1, num2):
return num1-num2
def multiplication(self, num1, num2):
return num1*num2
def division(self, num1, num2):
return num1/num2
a = simpleCalculator()
print("Enter your choice: ")
print("1.Addition \n 2.Subtraction \n 3.Multiplication \n 4.Division")
while True:
choice = int(input("Enter your choice(1/2/3/4): "))
if choice in (1, 2, 3, 4):
num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))
if choice == 1:
print(f"Addition of {num1} & {num2} is {a.addition(num1,num2)}")
elif choice == 2:
print(f"Subtraction of {num1} & {num2} is {a.sub(num1,num2)}")
elif choice == 3:
print(
f"Multiplication of {num1} & {num2} is {a.multiplication(num1,num2)}")
elif choice == 4:
print(f"Division of {num1} & {num2} is {a.division(num1,num2)}")
next_cal = input("You want more calculation(Y/N): ")
if next_cal == "N" or "n":
print("****** Thank you for using world's best calculator ******")
else:
print("Invalid Choice")
Hello I'm trying to add two natural numbers and I wanted the program to continue and have an option to break.
This is my code:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
You can do this using a while loop. So for example:
while True:
play = input("Do you want to play (type no to stop)?")
if play == 'no':
break
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
Put all of this code in a loop and add option to continue/ break before taking input from the user.
while(True):
option = int(input("Enter 0 to break. Else, continue")
if option == 0:
break
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
print('entry "quit" when you want toe terminate the program')
# infinite loop
while 1:
# input validation
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
except ValueError:
print('Please entry a number')
print()
# continue would restart the while loop
continue
if(num1 == 'quit' or num2 == 'quit'):
# break will terminate the while loop
break
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
You can always nest these statements in a while loop and break on some condition.
def process_results():
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum,"is Odd")
def get_choice():
print("Enter R to run program or Q to quit:")
choice = input()
return choice
def main():
while(True):
choice = get_choice()
if choice == 'R' or choice == 'r':
process_results()
elif choice == 'Q' or choice == 'q':
print("This program has quit")
else:
print("You must enter R to run program or Q to quit")
main()
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