Make calculator using python - python

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

Related

Can someone help me with this simple calculator program in python? I am having problem in finding error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
Program got a Syntax error as follow:
elif choice == "3":
^^^^
SyntaxError: invalid syntax
print("1 Addition\n2 Subtraction\n3 Multiplication\n4 Division ")
choice= input ("WHat is you choice? : ")
num1 = float (input("Please enter a number: "))
num2 = float( input("please enter another number: "))
if choice == "1":
print(Num1,"+", Num2, "=", (Num1 + Num2))
elif choice == "2":
print(Num1,"-", Num2, "=", (Num1 - Num2))
elif choice == "3":
print(Num1,"x", Num2, "=", (Num1 * Num2))
elif choice == "4":
if Num2 == 0.0
print("0 error LOL")
else:
print(Num1, "/", Num2, "=", (Num1 / Num2) )
else:
print("your choice is bad...")
Variable names are case sensitive ("num1" cannot be referenced as "Num1")
Indentation on elif should be inline with the original "if"
Missing colon on if statement on line 13.
Here is an altered version that worked for me:
print("1 Addition\n2 Subtraction\n3 Multiplication\n4 Division ")
choice= input ("WHat is you choice? : ")
num1 = float (input("Please enter a number: "))
num2 = float( input("please enter another number: "))
if choice == "1":
print(num1,"+", num2, "=", (num1 + num2))
elif choice == "2":
print(num1,"-", num2, "=", (num1 - num2))
elif choice == "3":
print(num1,"x", num2, "=", (num1 * num2))
elif choice == "4":
if num2 == 0.0:
print("0 error LOL")
else:
print(num1, "/", num2, "=", (num1 / num2) )
else:
print("your choice is bad...")
You need to unindent the elif statements like:
print("1 Addition\n2 Subtraction\n3 Multiplication\n4 Division ")
choice= input("What is you choice? : ")
num1 = float(input("Please enter a number: "))
num2 = float(input("please enter another number: "))
if choice == "1":
print(f"{Num1}+{Num2}={Num1 + Num2}")
elif choice == "2":
print(f"{Num1}-{Num2}={Num1 - Num2}")
elif choice == "3":
print(f"{Num1}*{Num2}={Num1 * Num2}")
elif choice == "4":
if Num2 == 0.0
print("0 error LOL")
else:
print(f"{Num1}/{Num2}={Num1 / Num2}")
else:
print("your choice is bad...")
I changed your code slightly and used f-strings to make it slightly neater (in my opinion)

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

Basic Python calculator

I am new to Python. I tried to make a simple calculator, but what is the problem?
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def div(num1, num2):
return num1/num2
def multi(num1,num2):
return num1*num2
def main():
operation = input("What do you want to do?(+, -, *, or /):")
if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("Your input is invalid. Please enter a valid input.")
else:
num1 = float(input("Enter value for num1: "))
num2 = float(input("Enter value for num2: "))
if (operation == "+"):
print(add(num1, num2))
elif (operation == "-"):
print(subtract(num1, num2))
elif (operation == "*"):
print(multi(num1,num2))
elif (operation == "/"):
print(div(num1,num2))
main()
You call main from inside itself. Set this outside the function like this:
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def div(num1, num2):
return num1/num2
def multi(num1,num2):
return num1*num2
def main():
operation = input("What do you want to do?(+, -, *, or /):")
if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("Your input is invalid. Please enter a valid input.")
else:
num1 = float(input("Enter value for num1: "))
num2 = float(input("Enter value for num2: "))
if (operation == "+"):
print(add(num1, num2))
elif (operation == "-"):
print(subtract(num1, num2))
elif (operation == "*"):
print(multi(num1,num2))
elif (operation == "/"):
print(div(num1,num2))
main() # Added main outside the function
Your main() has a Tab behind (before) it.
It didn't run for me at first.
The other things seem fine to me.
You could also have it in a loop if you want to make it nicer.
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def div(num1, num2):
return num1/num2
def multi(num1,num2):
return num1*num2
def main():
operation = input("What do you want to do?(+, -, *, or /):")
if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("Your input is invalid. Please enter a valid input.")
else:
num1 = float(input("Enter value for num1: "))
num2 = float(input("Enter value for num2: "))
if (operation == "+"):
print(add(num1, num2))
elif (operation == "-"):
print(subtract(num1, num2))
elif (operation == "*"):
print(multi(num1,num2))
elif (operation == "/"):
print(div(num1,num2))
if __name__ == '__main__':
while(True):
main()
if input('If you are done with calculating, type q: ') == 'q':
break

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

I wonder if there's a way to skip a specific line so it just doesn't get executed

I am building a calculator and I want to know if i can make num2 input be skipped when "root" option is chosen.
This is my code:
num1 = float(input("Enter a number: "))
op = input("Enter a operator: ")
if op not in operators:
print("Invalid operator")
start()
num2 = float(input("Enter a number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "^":
print(pow(num1, num2))
elif op == "root":
print(math.sqrt(num1))
restart = input("Continue?: ")
if restart == "yes":
start()
else:
sys.exit(0)
I want this to get ignored:
num2 = float(input("Enter a number: "))
When this is the case:
elif op == "root":
print(math.sqrt(num1))
Put the second number input statement behind an if:
op = input("Enter a operator: ")
if op != "root":
num2 = float(input("Enter a number: "))
To do this, you could do:
if op != "root":
num2 = float(input("Enter a number: "))
This would skip the num2 input if op == "root"
There can be many different ways. One suggestion would be as below.
num1 = float(input("Enter a number: "))
op = input("Enter a operator: ")
# HERE
if op != "root" and op in operators:
num2 = float(input("Enter a number: "))
elif op not in operators:
print("Invalid operator")
start()
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "^":
print(pow(num1, num2))
elif op == "root":
print(math.sqrt(num1))
restart = input("Continue?: ")
if restart == "yes":
start()
else:
sys.exit(0)
or
# HERE
if op in operators:
if op != "root":
num2 = float(input("Enter a number: "))
else:
print("Invalid operator")
start()

Categories