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
Related
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? 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 !")
I coded calculator using Python like just add the choice, add two numbers and get the output. Also I input reset and terminate option also here.
Here is the code that I tried. But it is not get the output it shows an error.
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
def power(num1, num2):
return num1 ** num2
def rem(num1, num2):
return num1 % num2
def select_op(choice):
return choice
while True:
print("Select 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 : $ ")
choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
print(choice)
if (select_op(choice) == -1):
print("Done. Terminating")
exit()
else:
num1 = float(input("Enter First Number : "))
num2 = float(input("Enter Second Number : "))
if(select_op(choice) == "+"):
print(num1, "+", num2, "=", add(num1,num2))
elif(select_op(choice) == "-"):
print(num1, "-", num2, "=", sub(num1,num2))
elif(select_op(choice) == "*"):
print(num1, "*", num2, "=", mul(num1,num2))
elif(select_op(choice) == "/"):
print(num1, "/", num2, "=", div(num1,num2))
elif(select_op(choice) == "^"):
print(num1, "^", num2, "=", power(num1,num2))
elif(select_op(choice) == "%"):
print(num1, "+", num2, "=", rem(num1,num2))
elif(select_op(choice) == "$"):
return True
else:
print("Something Went Worng")
The error message tell every thing. if(select_op(choice) == "+"): IndentationError: unexpected indent
Because your indent is wrong, it should be like this.
And your code has more problem than that.
while True:
print("Select 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 : $ ")
choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
print(choice)
if (select_op(choice) == -1): #<- choice is String type, you can't compare it to int.
print("Done. Terminating")
exit()
else:
num1 = float(input("Enter First Number : "))
num2 = float(input("Enter Second Number : "))
if(select_op(choice) == "+"):
print(num1, "+", num2, "=", add(num1,num2))
elif(select_op(choice) == "-"):
print(num1, "-", num2, "=", sub(num1,num2))
elif(select_op(choice) == "*"):
print(num1, "*", num2, "=", mul(num1,num2))
elif(select_op(choice) == "/"):
print(num1, "/", num2, "=", div(num1,num2))
elif(select_op(choice) == "^"):
print(num1, "^", num2, "=", power(num1,num2))
elif(select_op(choice) == "%"):
print(num1, "+", num2, "=", rem(num1,num2))
elif(select_op(choice) == "$"):
return True #<- Also you can't return outside function
else:
print("Something Went Worng")
elif(select_op(choice) == "$"):
return True
According to the return command in your code.
You must copy the if statement from a function.
Please use break instead of return.
Please check following clip for the unexpected indent issue.
else:
num1 = float(input("Enter First Number : "))
num2 = float(input("Enter Second Number : "))
## dedented following lines
if(select_op(choice) == "+"):
print(num1, "+", num2, "=", add(num1,num2))
elif(select_op(choice) == "-"):
print(num1, "-", num2, "=", sub(num1,num2))
BTW, this would be better for a calculator.
t = ('+','-','*','/','^','%') # ,'#','$')
while True:
print("Select 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 : $ ")
choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
print(choice)
if (select_op(choice) == -1):
print("Done. Terminating")
exit()
elif choice == '$': break
elif choice in t:
num1 = input("Enter First Number : ")
num2 = input("Enter Second Number : ")
print('{} {} {} = {}'.format(num1, choice, num2, eval(num1+choice+num2)) )
else:
print("Something Went Worng")
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')