How can I add decimal inputs and round off outputs? - python-3.x

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

Related

how i can fix this problem in python code

I'm new programmer and I am begginer, this my first time use stack overflow, I trying now to calcul a calculator calcul numbers like normal calculator, I want write something such as (" 7 - 2 * 3") and the code give the result.
The code is chaos im just begginer so please just try understand that and help me.
when you try the code input numbers and operators with space like this 5 + 5.
This the code :
from functools import reduce
question = input("Enter your calcul : ")
nums = question.split()
numbers = nums[0::2]
def calcul(num1, num2):
for x in variation:
if x == '+':
return num1 + num2
elif x == '-':
return num1 - num2
elif x == '*':
return num1 * num2
elif x == '/':
return num1 / num2
def wayy(lt):
for x in lt:
if '+' == x :
yield'+'
if '-' == x :
yield'-'
if '*' == x :
yield'*'
if '/' == x :
yield'/'
variations = [] # [ + , - , * , / ]
variation = wayy(nums)
for x in variation:
variations.append(x)
print(variations)
nm = []
for n in numbers:
n = int(n)
nm.append(n)
calcule = reduce(calcul, nm)
print(calcule)
I try coding a calculator and i have a problem i think it is in calcul function when i input the numbers the result is "None" I know the problem in function (calcul) but I dont know how I can fix it.
Only change "variation" to "variations" in the "calcul" function.
def calcul(num1, num2):
for x in variations:
if x == '+':
return num1 + num2
elif x == '-':
return num1 - num2
elif x == '*':
return num1 * num2
elif x == '/':
return num1 / num2
Since "variation" is a "Generator" object, but "variations" is a list of Strings (what you need).

return statement | Python 3 beginner

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

Problem with a simple calculator program where an error always seems to occur when entering the number zero

I'm new to the stack overflow website, python, and programming as a whole. So pardon me if the title or body of this question isn't apt.
I'm trying to create a simple calculator program in python, which performs only four operations, namely, addition, subtraction (difference), multiplication and division.
Here's my code:
print("Welcome to the calculator \n")
num1 = int(input("Enter the first number \n"))
num2 = int(input("Enter the second number \n"))
operation = (input("""Enter the symbol of the operation to be performed. Your choices are:
+
- (Difference)
*
/
\n """))
add = num1+num2
sub1 = num1-num2
sub2 = num2 - num1
product = num1*num2
quotient = num1 / num2
if operation == "-" :
if num1 > num2:
print(sub1)
else:
print(sub2)
elif operation == "+" :
print(add)
elif operation == "*" :
print(product)
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
print(quotient)
else:
print("Please enter a valid operator from among the ones provided above")
Everything runs fine, except, when I enter zero as num2, and no matter what operator I select, the output
is this:
Traceback (most recent call last):
File "test4.py.txt", line 19, in <module>
quotient = num1 / num2
ZeroDivisionError: division by zero
Help would be greatly appreciated.Thanks!
Find the quotient inside the if condition, not before checking num==0, otherwise the division by zero is already done, causing the error.:
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
quotient = num1 / num2
print(quotient)
quotient = num1 / num2
That's the line that is giving you the error. You should be checking if num2 is zero before calculating num1 / num2. You can do it as follows and your program would work fine.
quotient
if num2 == 0:
quotient = None
else :
quotient = num1 / num2
Else you could just declare quotient and calculate the quotient when user inputs the operator. If user enters /, then you can check if num2==0 and if it is you can give error message.
Working code -
print("Welcome to the calculator \n")
num1 = int(input("Enter the first number \n"))
num2 = int(input("Enter the second number \n"))
operation = (input("""Enter the symbol of the operation to be performed. Your choices are:
+
- (Difference)
*
/
\n """))
add = num1+num2
sub1 = num1-num2
sub2 = num2 - num1
product = num1*num2
quotient = None # Don't divide by num2 here or you will get error of divisionbyzero
if operation == "-" :
if num1 > num2:
print(sub1)
else:
print(sub2)
elif operation == "+" :
print(add)
elif operation == "*" :
print(product)
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
quotient = num1 / num2
print(quotient)
else:
print("Please enter a valid operator from among the ones provided above")
Since you are new, I will explain this in more detail so you actually know what you are doing wrong
Pay attention to these lines
add = num1+num2
sub1 = num1-num2
sub2 = num2 - num1
product = num1*num2
quotient = num1 / num2
When you do this it is actually performing the calculation and assigning it to the respective value (i.e. quotient = num1 / num2 will actually do the calculation and store the result in the quotient variable). So, you are doing every calculation every time regardless of your choice of operator. It would be better to assign the values only if that operator has been chosen like below.
print("Welcome to the calculator \n")
num1 = int(input("Enter the first number \n"))
num2 = int(input("Enter the second number \n"))
operation = (input("""Enter the symbol of the operation to be performed. Your choices are:
+
- (Difference)
*
/
\n """))
if operation == "-" :
sub1 = num1-num2
sub2 = num2 - num1
if num1 > num2:
print(sub1)
else:
print(sub2)
elif operation == "+" :
add = num1+num2
print(add)
elif operation == "*" :
product = num1*num2
print(product)
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
quotient = num1 / num2
print(quotient)
else:
print("Please enter a valid operator from among the ones provided above")
This part is just a suggestion. You could also make your Difference operation easier by using the following.
if operation == "-" :
sub1 = num1-num2
print(abs(sub1))
abs gets the absolute value, basically removes the negative.
You should calculate the results only after checking the operators (thus avoiding any errors caused by trying to divide by zero), this way you will also avoid unnecessary calculations:
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
quotient = num1 / num2
print(quotient)

Deleting variable to not get print it out

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?

Issues on Calculator Program of repeated num1 and num2 for else in Python 3

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

Resources