So I'm building my first calculator.
import math
# Adding two numbers
def add(num1, num2):
return num1 + num2
#Substract two numbers
def subst(num1, num2):
return num1 - num2
#Multiply two numbers
def multi(num1, num2):
return num1 * num2
#Divide two numbers
def divide(num1, num2):
return num1 / num2
#Exponentiation of number
def expont(num1, num2):
return pow(num1, num2)
#Square root
def sqrt(num1):
return math.sqrt(num1)
#Sin
def sin(num1):
return math.sin(num1)
#Cosinus
def cos(num1):
return math.cos(num1)
#Tangent
def tan(num1):
return math.tg(num1)
print("Select your operation: \n"
"1.Add\n"
"2.Substract\n"
"3.Multiply\n"
"4.Divide\n"
"5.Exponentiation\n"
"6.Square root\n"
"7.Sine\n"
"8.Cosine\n"
"9.Tangent")
operation = input("Select your operation 1, 2, 3, 4, 5, 6, 7, 8 ,9: ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if operation == "1":
print(add(num1,num2))
elif operation == "2":
print(subst(num1,num2))
elif operation == "3":
print(multi(num1,num2))
elif operation == "4":
print(divide(num1, num2))
elif operation == "5":
print(expont(num1,num2))
elif operation == "6":
print(sqrt(num1))
elif operation == "7":
print(sin(num1))
elif operation == "8":
print(cos(num1))
else:
print(tan(num1))
But I have a problem when I try to sine, cosine and tanget. As you see I want to take only one value, which is num1, but program is asking me to enter num2.
How can I prevent or maybe disable/delete the num2 for operation >= 7
I've tried using if, while statements, as well as del. But it doesn't work.
What should I do to disable num2 variable for operations that are bigger or equal to 7?
Related
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "*":
print(num1*num2)
elif op == "/":
print(num1/num2)
elif op == "-":
print(num1-num2)
elif op == "+":
print(num1+num2)
else:
print("Error 404")
print(cal(num1, num2))
this code runs right but says "none" at the end why?
Your code actually works. The problem with your code is that when you call calc() inside the print function, it tries to look for value that might be provided within the calc function (via the return statement). Since you did not return any value within your function, the interpreter cannot find the correct "value" to print. Note that none is a data type in Python. To solve the problem you can just change the print statements inside the if...else statement to a return statement. This way, when the operator is provided by the user, it will compute the result and return the result to the calc()'s function caller.
Here is the complete version of what you are trying to achieve:
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "":
input("Nothing entered. Please enter an operator. ")
elif op == "/":
return num1/num2
elif op == "-":
return num1-num2
elif op == "+":
return num1+num2
else:
return "Error 404")
print(cal(num1, num2))
As you have not provided a value for your function to return the Python interpreter returns a value for you. So when your print() calls your function cal the function returns nothing or put another way returns a value of None and that's what your print() statement prints.
Compare your code with the following where a value is returned to the print() statement,
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2, op):
if op == "*":
cal_val = num1 * num2
elif op == "/":
cal_val = num1 / num2
elif op == "-":
cal_val = num1-num2
elif op == "+":
cal_val = num1 + num2
else:
cal_val = "Error 404"
return cal_val
print(cal(num1, num2, op))
Alternatively you could leave your code as it is and just call your cal() function without the print() wrapped around it. As below,
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "*":
print(num1*num2)
elif op == "/":
print(num1/num2)
elif op == "-":
print(num1-num2)
elif op == "+":
print(num1+num2)
else:
print("Error 404")
cal(num1, num2)
Change your print statements in function to return statements, otherwise the function will be implemented, and it will print the result in console, but at your print statement you will get none.
because - when you use "Print" - you simply print a value in the console.
When you use "Return" - you get a value from a function.
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "*":
return(num1*num2)
elif op == "/":
return(num1/num2)
elif op == "-":
return(num1-num2)
elif op == "+":
return(num1+num2)
else:
return("Error 404")
print(cal(num1, num2))
Try this instead
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "*":
return num1*num2
elif op == "/":
return num1/num2
elif op == "-":
return num1-num2
elif op == "+":
return num1+num2
else:
return "Error 404"
print(cal(num1, num2))
I have been working on this calculator and have been trying to modify it so that it can take in user inputs that contain decimals and if the output were to have a decimal in it, to round it to the nearest whole number but I am not sure exactly where I should input the code. I have tried using the round() function but I end up getting a syntax error when I put it towards the bottom. Here is what I have so far.
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:
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, "=", 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))
cont = input("Continue?y/n:")
if cont == "n":
break
If you want to keep your code pretty much the way it is, but allow the user to optionally enter a floating point number that is rounded to the closest integer value then you only need to change this:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
to this:
num1 = round(float(input("Enter first number: ")))
num2 = round(float(input("Enter second number: ")))
I am currently taking a course to learn Python and I am currently stuck. The task I am trying to accomplish is to be able to have the user input 2 numbers and an operator and to have the program make the appropriate calculation. for example:
if the user inputs: "2,3,+"
the output should be: 5
Instead, I am getting the output of: "['2', '3', '+']
Here is the code that I am currently using:
def Add(num1, num2):
return num1 + num2
def Subtract(num1, num2):
return num1 - num2
def Multiply(num1, num2):
return num1 * num2
def Divide(num1, num2):
try:
return num1 / num2
except ZeroDivisionError:
print("Sorry, A number can't be divided by 0")
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] == "-":
Subtract(num1, num2)
elif astring[2] == "*":
Multiply(num1, num2)
elif astring[2] == "/":
Divide(num1, num2)
p1 = input("Enter two numbers and an operator with each separated by a comma: ")
scalc(p1)
I am very new to programming and taking this course online has been challenging since I cant have an instructor present to look over my shoulder as I am trying to work through a problem. This is also my first time posting on this website so I hope I got the formatting correct and that this isn't too difficult to read. Any help here would be greatly appreciated.
Your code works perfectly. You've received your results after calling the functions but have never printed them.
if astring[2] == "+":
print(Add(num1, num2))
elif astring[2] == "-":
print(Subtract(num1, num2))
You could also return those values, and print(scale(p1)).
I tried doing this:
def scalc(p1):
astring = p1.split(",")
print(astring)
num1 = float(astring[0])
num2 = float(astring[1])
if astring[2] == "+":
return Add(num1, num2)
elif astring[2] == "-":
return Subtract(num1, num2)
elif astring[2] == "*":
return Multiply(num1, num2)
elif astring[2] == "/":
return Divide(num1, num2)
p1 = input("Enter two numbers and an operator with each separated by a comma: ")
scalc(p1)
but the result is still the same, where the output is a list instead of the desired function being run.
I have made a calculator in python3.
class simple_oper:
def __init__(self):
pass
#staticmethod
def add(num1, num2):
return num1 + num2
#staticmethod
def subtract(num1, num2):
return num1 - num2
#staticmethod
def mul(num1, num2):
return num1 * num2
#staticmethod
def div(num1, num2):
return num1 / num2
def get_int(input_message, tm):
num = input(input_message)
try:
return int(num)
except:
return get_int(tm, tm)
if __name__ == '__main__':
num1 = get_int("Please enter the first number : ", "Please enter the correct number : ")
l = ["+", "-", "*", "/"]
#c = simple_oper
while True:
oper = str(input("Please enter the operand to do : "))
if oper == "=":
print("You typed = printing result")
break
elif oper not in l:
print("Ypu typed incorrect operand. aborting and printing result")
break
num2 = get_int("please enter the number : ", "please enter the correct number")
if oper == "+":
num1 = simple_oper.add(num1, num2)
if oper == "-":
num1 = simple_oper.subtract(num1, num2)
if oper == "*":
num1 = simple_oper.mul(num1, num2)
if oper == "/":
num1 = simple_oper.div(num1, num2)
print(num1)
Now I want to write unit test for it. But the problem here is that my code takes many user inputs. So how do I write such a unit test that it can give inputs to my code.
In general, when you write classes in any language, you would generally leave the user input outside of the class, in a separate file. For unit testing, you wouldn't test input, you'd test the logic of the class itself. Your unit test would look something like this:
import unittest
from simple_oper import simple_oper
class Test_Simple_oper(unittest.TestCase):
def test_add(self):
self.assertEqual(simple_oper.add(3,3), 9)
self.assertEqual(simple_oper.add(-10,4), 6)
if __name__ == '__main__':
unittest.main()
You get it, something like that. You'd add more methods until you test all your methods in simple_oper. The unit test tests the program's logic, where you test many possibilities that the user can put, not user input.
I decided to program a Calculator, but my Problem is if i made a choice and entered 6 it still ask's me for num1 and num2 before saying "Invalid Input, PLease check the Select Operation and Try Again!". What i want is for it to go directly to saying "Invalid Input, PLease check the Select Operation and Try Again!" without requesting num1 and num2. I hope it's clear.
def calculator():
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y
print(""" -- Select Operation --
1. Addition
2. Subtraction
3. Multiplication
4. Division
""")
choice = input("Enter 1 or 2 or 3 or 4 from the Select Operation >> ")
print("\n")
print("Calculating...")
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, "=", add(num1, num2))
elif choice == '3':
print(num1, "-", num2, "=", add(num1, num2))
elif choice == '4':
print(num1, "-", num2, "=", add(num1, num2))
else:
print("Invalid Input, PLease check the *Select Operation* and Try Again!")
calculator()
Corrected your code please read python syntax
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y
print(""" -- Select Operation --
1. Addition
2. Subtraction
3. Multiplication
4. Division
""")
choice = input("Enter 1 or 2 or 3 or 4 from the Select Operation >> ")
while(choice not in ('1','2','3','4')):
choice = input("Invalid Input Please Enter 1 or 2 or 3 or 4 from the Select Operation >> ")
print("\n")
print("Calculating...")
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, "=", sub(num1, num2))
elif choice == '3':
print(num1, "-", num2, "=", mul(num1, num2))
elif choice == '4':
print(num1, "-", num2, "=", div(num1, num2))