Python - Reset button calculator and other issues - python

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 !")

Related

How to fix SyntaxError: 'break' outside loop in Python app

def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def mul(num1, num2):
return num1 * num2
def div(num1, num2):
return num1 / num2
print(f"Select Operation")
print(f"1) Addition")
print(f"2) Subtraction")
print(f"3) Multiplication")
print(f"4) Divition")
while True:
choice = input("Enter choice (1, 2, 3, or 4): ")
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if choice == '1':
print(f" {num1} + {num2} = ", add(num1, num2))
elif choice == '2':
print(f" {num1} - {num2} = ", subtract(num1, num2))
elif choice == '3':
print(f" {num1} * {num2} = ", multiply(num1, num2))
elif choice == '4':
print(f" {num1} / {num2} = ", divide(num1, num2))
next_calculation = input("Let's do another calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
I need help understanding why the break after if next_calculation == "no": always spits out SyntaxError: 'break' outside loop. Please help me fix it so the simple app will run.
Python blocks are designated by indentation, and your break command is not inside the while loop.
To fix this, you need to indent the entire if/else block so it is inside the while loop.
while True:
choice = input("Enter choice (1, 2, 3, or 4): ")
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if choice == '1':
print(f" {num1} + {num2} = ", add(num1, num2))
elif choice == '2':
print(f" {num1} - {num2} = ", subtract(num1, num2))
elif choice == '3':
print(f" {num1} * {num2} = ", multiply(num1, num2))
elif choice == '4':
print(f" {num1} / {num2} = ", divide(num1, num2))
next_calculation = input("Let's do another calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")

How can i add a function to show me history of calculations and results?

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

If user input is not part of string values asked, default output

Here is a code I made a while ago, I want to make it so that by default it calls the add function, so if I just input enter (or anything) it will ask me what two numbers I wish to add.
I have tried putting,
else:
num1 = float(input("Enter First Number: "))
num2 = float(input("Enter Second Number: "))
print(num1, "+", num2, "=", add(num1, num2))
but that is not working, any help would be greatly appreciated! Here is the entire code below
import math as m
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
def power(x, y):
return x ** y
def nroot(x, y):
return x ** (1/y)
def sin(D):
R = D / 180 * m.pi
return(m.sin(R))
def cos(D):
R = D / 180 * m.pi
return(m.cos(R))
print("Select Operation.")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exponent")
print("6. sin(Degrees)")
print("7. cos(Degrees)")
while True:
# Take input from user
choice = input("Enter Choice[1-7]: ")
#check if choice is one of the four
if choice in ('1', '2', '3', '4', '5'):
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))
if choice in('6','7'):
angle = float(input('Enter Angle in degrees: '))
if choice =='6':
print('sin(',angle,') = ',sin(angle))
elif choice =='7':
print('cos(',angle,') = ',cos(angle))
break
This works fine for me-
import math as m
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
def power(x, y):
return x ** y
def nroot(x, y):
return x ** (1/y)
def sin(D):
R = D / 180 * m.pi
return(m.sin(R))
def cos(D):
R = D / 180 * m.pi
return(m.cos(R))
print("Select Operation.")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exponent")
print("6. sin(Degrees)")
print("7. cos(Degrees)")
while True:
# Take input from user
choice = input("Enter Choice[1-7]: ")
#check if choice is one of the four
if choice in ('1', '2', '3', '4', '5'):
num1 = float(input("Enter First Number: "))
num2 = float(input("Enter Second Number: "))
# Update:
else:
num1 = float(input("Enter First Number: "))
num2 = float(input("Enter Second Number: "))
print(num1, "+", num2, "=", add(num1, num2))
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))
if choice in('6','7'):
angle = float(input('Enter Angle in degrees: '))
if choice =='6':
print('sin(',angle,') = ',sin(angle))
elif choice =='7':
print('cos(',angle,') = ',cos(angle))
break

stuck with a simple python program "elif"

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")

how to add restart command in python? [duplicate]

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

Categories