Basic Python calculator - python

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

Related

Why I'm getting out of the loop? [duplicate]

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

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

How to input string to function?

Here are the instructions I received for my assignment:
4) Add the following function into Mylib
scalc(p1)
p1 will be a string like this "N1, N2, operator"
examples
scalc("20,30,*")
the result will be 600
scalc("50,20,+")
the result will be 70
scalc("50,20,-")
the result will be 30
scalc("60,20,/")
the result will be 30
use string functions to parse the first number, the second number, and the operator from the input string.
use the prior functions (add, subtract, divide and multiply ) to do the calculations.
And here is my attempt that is not working. I have the add() sub() mult() div() functions, I'm just not showing them here.
I know it's something very simple that likely has to do with where I call the function scalc(p1). What is the proper way to do that?
def scalc(p1):
astring = p1.split(",")
num1 = float(astring[0])
num2 = float(astring[1])
if astring[3] == "+":
add()
elif astring[3] == "-":
sub()
elif astring[3] == "*":
mult()
elif astring[3] == "/":
div()
return num1, num2
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
EDIT: Here is the Answer. I did not have arguments being passed to my functions. By adding num1 and num2 to every instance of my arithmetic functions, they were able to receive the new variable values.
#Define the main program function
def main():
#Define input function
def float_input(msg):
while True:
try:
return float(input(msg))
except ValueError:
print("You must enter a number!")
else:
break
#Declare variables
rangeLower = float_input("Enter your Lower range: ")
rangeHigher = float_input("Enter your Higher range: ")
num1 = float_input("Enter your First number: ")
num2 = float_input("Enter your Second number: ")
#Define formula functions
def add(num1, num2):
sum = num1 + num2
print("The Result of",num1,"+",num2,"=", sum)
def sub(num1, num2):
diff = num1 - num2
print("The Result of",num1,"-",num2,"=", diff)
def mult(num1, num2):
product = num1 * num2
print("The Result of",num1,"*",num2,"=", product)
def div(num1, num2):
if num2 == 0:
print("The Result of",num1,"/",num2,"= You cannot divide by Zero")
else:
quotient = num1 / num2
print("The Result of",num1,"/",num2,"=", quotient)
#If-else
if num1 < rangeLower or num1 > rangeHigher or num2 < rangeLower or num2 > rangeHigher:
print("The input values are outside the input ranges.")
print("Please check the number and try again.")
print("Thanks for using our calculator")
else:
#Call functions
add(num1, num2)
sub(num1, num2)
mult(num1, num2)
div(num1, num2)
print("Thanks for using this calculator!")
def scalc(p1):
astring = p1.split(",")
num1 = float(astring[0])
num2 = float(astring[1])
if astring[2] == "+":
add(num1, num2)
elif astring[2] == "-":
sub(num1, num2)
elif astring[2] == "*":
mult(num1, num2)
elif astring[2] == "/":
div(num1, num2)
return num1, num2
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
This does it. There were a couple errors. First, in Python you start counting at 0, so you wanted to use astring[2] instead of astring[3]. Also you needed a value to be returned:
def scalc(p1):
astring = p1.split(",")
print(astring)
num1 = float(astring[0])
num2 = float(astring[1])
if astring[2] == "+":
add(num1,num2)
elif astring[2] == "-":
sub(num1,num2)
elif astring[2] == "*":
mult(num1,num2)
elif astring[2] == "/":
div(num1,num2)
return value
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
Example:
input: "20,30,+"
Out[2]: 50.0

NameError: name '' is not defined with multiple define functions

I just want to start off by saying I know this code is wrong, I'm just testing
this is meant to be a calculator, as you may be able to see from the code I am trying to make the number they end with e.g.
10 + 10 = 20, they will keep the number 20 and can carry on with 20, I want to keep repeating that option
Code:
def add(num1, num2):
return num1 + num2
def mul(num1, num2):
return num1 * num2
def sub(num1, num2):
return num1 - num2
def div(num1, num2):
return num1 / num2
def main():
operation = input("Do you want to(+,-,*,/): ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("That is an invalid operation")
else:
num1 = float(input("choose a number: "))
num2 = float(input("Choose another number: "))
if(operation == "+"):
answer = (add(num1, num2))
print(answer)
elif(operation == "-"):
answer = (sub(num1, num2))
print(answer)
elif(operation == "*"):
answer = (mul(num1, num2))
print(answer)
elif(operation == "/"):
answer = (div(num1, num2))
print(answer)
else:
print("Syntax error!")
def multiple(multiple):
multiple = input("would you like to carry the number(Y or N): ")
if(multiple == "Y" or multiple == "y"):
carry = input("(+,-,*,/): ")
num3 = int(input("choose a number: "))
if(carry == "+"):
print(answer + num3)
elif(carry == "-"):
print(answer - num3)
elif(carry == "*"):
print(answer * num3)
elif(carry == "/"):
print(answer / num3)
else:
print("Syntax Error!")
multiple = True
while multiple == True:
multiple()
choice = input("would you like multiple calculations? (Y or N): ")
while(choice == "y" or choice == "Y"):
main()
multiple()
multiple()
main()
error message:
line 56, in <module>
multiple()
NameError: name 'multiple' is not defined
p.s There may be some indentation errors in this as it pasted strange
You're trying to call the function multiple outside of the scope of the main function while it is only defined in it. Assuming that your indentation is as presented here, you need to move the definition of multiple outside of main so that it can be called.
Additionally, you're defining a variable named multiple which might create some problems. You should change it to something else.
I optimized your code a little and fixed it. It works fine so take a look at it.
def add(num1, num2):
return num1 + num2
def mul(num1, num2):
return num1 * num2
def sub(num1, num2):
return num1 - num2
def div(num1, num2):
return num1 / num2
def main(carry):
operation = input("Do you want to (+,-,*,/): ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("That is an invalid operation")
else:
num1 = float(input("choose a number: "))
if carry == None:
num2 = float(input("Choose another number: "))
else:
num2 = carry
if(operation == "+"):
answer = add(num1, num2)
elif(operation == "-"):
answer = sub(num1, num2)
elif(operation == "*"):
answer = mul(num1, num2)
elif(operation == "/"):
answer = div(num1, num2)
print(answer)
return answer
if input("would you like multiple calculations? (Y or N): ") in ("y", "Y"):
domultiple = True
else:
domultiple = False
carry = None
while 1:
carry = main(carry)
if domultiple:
if input("would you like to carry the number (Y or N): ") in ("n", "N"):
break
else:
break

Python - looping

I am trying to build a simple calculator. I just want the user to enter two numbers and an operation, then for the calculation to be shown, then to loop back to entering two numbers again. If the user enters an operation that is not recognized I want to loop back to 'enter operation'.
Why is this not working:
def add (a,b):
return a + b
def minus (a,b):
return a - b
def multi (a,b):
return a * b
def div (a,b):
return a / b
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
def opPic():
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
opPic ()
print ("Hello User")
numPic()
opPic()
You have a few bugs. First, num1 and num2 are local to numPic--not
global. So you need to return them to the caller, and the caller has to pass
them to opPic():
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
return num1, num2
def opPic(num1, num2):
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
opPic (num1, num2)
num1, num2 = numPic()
opPic (num1, num2)
To make it loop-based, you could do something like:
def opPic(num1, num2):
while True:
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
continue
break
Hopefully, you can figure out the other bit on your own, as this looks like a school assignment.
The num1 and num2 you define in numPic are local to that function. You need to return them and pass them to the opPic function for them to be used.
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
return num1, num2
def opPic(num1, num2):
#the same code as before
#except changing opPic() to opPic(num1, num2)
print ("Hello User")
num1, num2 = numPic()
opPic(num1, num2)
There are better ways of doing what you seem to be aiming for though. You haven't actually used a loop and have used recursion instead.

Categories