How to include square root in a basic calculator - python

So I wrote a basic calculator in python:
import math
import sys
num1 = float(input("Enter a number "))
operator = input("Enter a operator ")
num2 = float(input("Enter a second number "))
if operator == '+':
print (num1) + (num2)
elif operator == '-':
print(num1 - num2)
elif operator == '*':
print(num1 * num2)
elif operator == '/':
print(num1 / num2)
elif operator == "sqrt":
print(math.sqrt(num1))
else:
print("Unknown operator")
I want to make the square root command function so that when I choose num1 and the square root operator it skips the rest and gives me the results directly. Instead of needing to also write out num2.

Put it in a function so you can return before asking for num2 if appropriate:
import math
def calc():
num1 = float(input("Enter a number "))
operator = input("Enter a operator ")
if operator == "sqrt":
print(math.sqrt(num1))
return
num2 = float(input("Enter a second number "))
if operator == '+':
print (num1) + (num2)
elif operator == '-':
print(num1 - num2)
elif operator == '*':
print(num1 * num2)
elif operator == '/':
print(num1 / num2)
calc()
Other unary operations can simply be added as elifs under the one for sqrt.
Another approach might be to put your operators into dicts according to the number of operands:
import math
unary_ops = {
"sqrt": math.sqrt,
}
binary_ops = {
"*": float.__add__,
"-": float.__sub__,
"*": float.__mul__,
"/": float.__truediv__,
}
num1 = float(input("Enter a number "))
operator = input("Enter a operator ")
if operator in unary_ops:
print(unary_ops[operator](num1))
elif operator in binary_ops:
num2 = float(input("Enter a second number "))
print(binary_ops[operator](num1, num2))
else:
print(f"Sorry, I don't know how to '{operator}'.")

Related

How can I make my calculator code repeat without asking the user to input anything? - continuous calculation in Python

def calculation():
num1 = float(input())
num2 = float(input())
op = input()
if op == "+": #code for addition
print(num1 + num2)
elif op == "-": #code for subtraction
print(num1 - num2)
elif op == "/": #code for division
print(num1 / num2)
elif op == "*": #code for multiplication
print(num1 * num2)
#elif ZeroDivisionError:
#print("Divided by zero")
else: #code if invalid operator is entered
print("Invalid operator entered")
calculation() #calling the fucntion
Right now the code only runs when I call the function. Id like it to run non-stop, like a physical calculator. I am also trying to sort out how to not break the code if division by 0 occurs. Thank you for any help.
I believe the default way is to use while True:
while True:
# your code here
True is by default True, so your program will run until it is manually terminated.
As with the division by zero, you can do
...
elif op == "/": #code for division
if num2 == 0:
print('Cannot divide by zero!')
else:
print(num1 / num2)
A simple infinite loop will do:
while True:
calculation()
You can also shorten your calculation function, mapping your symbols to the appropriate operator functions and handling exceptions as they occur:
from operator import add, sub, mul, truediv
ops = {"+": add, "-": sub, "*": mul, "/": truediv}
def calculation():
num1 = float(input())
num2 = float(input())
op = input()
try:
print(ops[op](num1, num2))
except KeyError:
print("Invalid operator entered")
except ZeroDivisionError:
print("Divided by zero")

I build a calculator and I want to give error if they didn't type any number

Code works pretty well if you enter an actual number and operator and it actually gives u an error code if you enter an invalid operator but I want to give same error code with numbers but I dont know how I use python 3.9 help plz
num1 = float(input('Enter First Number:'))
op = input('Enter operator:')
num2 = float(input('Enter Second Number:'))
if op == '+':
print(num1 + num2)
elif op == '-':
print(num1 - num2)
elif op == '*':
print(num1 * num2)
elif op == '/':
print(num1 / num2)
else:
print('enter an operator plz')
You want to use try/catch statements and/or while loops around each step.
flag1,flag2,operator =True,True,True
while flag1:
try:
num1 = float(input('Enter first Number:'))
flag1 = False
except ValueError:
print("Enter a valid first number please")
while operator:
op = input('Enter operator:')
if not (op=='+' or op =='-' or op =='*' or op=='/'):
print('Enter a valid operator please')
else:
operator=False
while flag2:
try:
num2 = float(input('Enter second Number:'))
flag2 = False
except ValueError:
print("Enter a valid second number please")
if op == '+':
print(num1 + num2)
elif op == '-':
print(num1 - num2)
elif op == '*':
print(num1 * num2)
elif op == '/':
print(num1 / num2)
Maybe try something along the lines of this:
invalid = True
while invalid:
try:
num1 = float(input('Enter First Number:'))
op = input('Enter operator:')
num2 = float(input('Enter Second Number:'))
invalid = False
except ValueError:
print("Please enter a valid number")
if op == '+':
print(num1 + num2)
elif op == '-':
print(num1 - num2)
elif op == '*':
print(num1 * num2)
elif op == '/':
print(num1 / num2)
else:
print('enter an operator plz')

Why does the last if statement print when the condition is false

Why does "Invalid Operator" print when the if statement is false? Could I use an elif statement to make it work?
num1 = float(input("Enter the first number: "))
operator = input("Enter your operator here: ")
num2 = float(input("Enter your second number here: "))
if operator == "+":
print(num1 + num2)
if operator == "-":
print(num1 - num2)
if operator == "*":
print(num1 * num2)
if operator == "/":
print(num1 / num2)
if operator != ("+", "-", "*", "/"):
print("Invalid Operator.")
You are compairing an operator to a tuple. Instead, you can check if operator in tuple, like this:
if operator not in ("+", "-", "*", "/"):
print("Invalid Operator.")
The alternative is elifs:
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
elif operator == "/":
print(num1 / num2)
else:
print("Invalid Operator.")
With this, when you add a new operator you don't need to modify the not in (...) condition.
The last if-statement is not correct. Now it checks if it is equal to the entire tuple. You could check if the operator is not in the list.
num1 = float(input("Enter the first number: "))
operator = input("Enter your operator here: ")
num2 = float(input("Enter your second number here: "))
if operator == "+":
print(num1 + num2)
if operator == "-":
print(num1 - num2)
if operator == "*":
print(num1 * num2)
if operator == "/":
print(num1 / num2)
if operator not in ("+", "-", "*", "/"):
print("Invalid Operator.")
Another option is indeed using elif and else. If it’s not one of the first for options, then in will be an Invalid Operator (else).
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
elif operator == "/":
print(num1 / num2)
else:
print("Invalid Operator.")
Edit: Changed if not in ... from list to tuple. Tuples are more efficient in this context.
operator != ("+", "-", "*", "/") # condition_1
where operator is a string object, where as ("+", "-", "*", "/") is a tuple so both are not equal so above condition_1 result into True and last if block will get executed.
Either use if/elif/else statement or change last condition correctly like this
operator not in ("+", "-", "*", "/") # itemwise ckech takeplace
operator not in "+-*/" # string is also a iterable object

How to store result of simple python calculator in variable

I am a beginner to Python and have just started learning recently.
After learning about if, elif and else statements I decided to try and make a simple calculator.
Now, a few hours later I was wondering how I could improve it and make it more complex.
I am trying to store the result of the addition, subtraction, divison or multiplication of the first two numbers in a variable. After doing this I want to Re-create the calculator only I already have the first number.
I am also running into problems with my continue1 if statement, for some reason even if the user inputs "no" the script continues instead of displaying a message.
I'd really appreciate any help at all, Thank you!
Python code:
num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")
if operator == "/":
print(num1 / num2)
elif operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
else:
print("FATAL ERROR")
num3 = num1 / num2
num3 = num1 - num2
num3 = num1 + num2
num3 = num1 * num2
continue1 = input ("Would you like too continue? [Yes/No]")
if continue1 == "yes" or "Yes":
operator1 = num4 = float(input("Please enter second number: "))
else:
print("Fatal error")
input("please enter operator")
if operator == "/":
print(num3 / num4)
elif operator == "+":
print(num3 + num4)
elif operator == "-":
print(num3 - num4)
elif operator == "*":
print(num3 * num4)
else:
print("Please press enter to close.")
input("Press Enter to Exit")
In the first part, just assign to a variable (and then print it if you want):
if operator == "/":
num3 = num1 / num2
elif operator == "+":
num3 = num1 + num2
elif operator == "-":
num3 = num1 - num2
elif operator == "*":
num3 = num1 * num2
else:
print("FATAL ERROR")
print(num3)
Regarding the second part of your question, in your statement:
if continue1 == "yes" or "Yes":
this is wrong because or is an operator which will combine the two things on either side of it (typically used where each of these two things is something that evaluates to True or False), so you could have for example:
if continue1 == "yes" or continue1 == "Yes":
You can also add brackets to control the order of execution, as shown below. In this case they do not affect the result, because it is already the case that the == operators are evaluated before the or, but they may make it clearer to read.
if (continue1 == "yes") or (continue1 == "Yes"):
You can also do this instead:
if continue1 in ("yes", "Yes"):
The details of what is going wrong with your original form of the conditional statement are perhaps not important at this stage, but I mention them for sake of completeness. If you enter "No" then the whole expression will actually evaluate to "Yes" (the continue1 == "yes" evaluates to False, and then False or "Yes" evalues to "Yes"). The if statement then treats the value "Yes" (a non-empty string) as a true value and so executes the code which depends on the condition.
num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
keepCalculate=True
while keepCalculate:
operator = input("Please enter operator: ")
if operator == "/":
print(num1 / num2)
elif operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
else:
print("FATAL ERROR")
continue1 = input ("Would you like too continue? [Yes/No]")
if continue1== "yes" or "Yes":
keepCalculate=True
else:
keepCalculate=False
The most simple way todo what you want
simply use
num3 = num1 + num2
to store the codes
"or" in programming doesn't work like or in rel life, it is ussed to separate 2 different conditions, hence use:
if continue1 == "yes" or continue1 == "Yes":
I recreated your code now it's working:
def op(operator,num1,num2):
global num3
if operator == "/":
num3 = num1 / num2
elif operator == "+":
num3 = num1 + num2
elif operator == "-":
num3 = num1 - num2
elif operator == "*":
num3 = num1 * num2
else:
print("FATAL ERROR")
num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")
op(operator,num1,num2)
print(num3)
continue1 = input ("Would you like too continue? [Yes/No]").lower()
if continue1 in ["yes", "y"]:
num4 = float(input("Please enter second number: "))
operator = input("please enter operator")
op(operator,num3,num4)
print(num3)
else:
print("Fatal error")
input("Press Enter to Exit")
Whatever you do, this code will keep as result, the value of num3 = num1 * num2. You should put these lines in each if, elif

Operator as parameter to IF returns SyntaxError: invalid syntax

This is a simple calculator, but for some reason, it returns a syntax error in the "if":
a = int(input("First number: "))
b = int(input("Second number: "))
operator = input("Type operation '+', '-','*' ou '/' ")
if operator == "+":
print("The sum is "(a+b)
elif operator == "-":
print("The subtraction is "(a-b))
elif operator == "*":
print("A product is "(a*b))
elif operator == "/":
print("O quotient "(a/b))
You have indeed some sintax errors, your function should look like this:
a = int(input("First number: "))
b = int(input("Second number: "))
operator = input("Type operation '+', '-','*' ou '/' ")
if operator == "+":
print("The sum is %s"%(a+b))
elif operator == "-":
print("The subtraction is %s"%(a-b))
elif operator == "*":
print("A product is %s"%(a*b))
elif operator == "/":
print("O quotient %s"%(a/b))
else:
print("something here")
Also as suggested by #khelwood:
a = int(input("First number: "))
b = int(input("Second number: "))
operator = input("Type operation '+', '-','*' ou '/' ")
if operator == "+":
print("The sum is ",(a+b))
elif operator == "-":
print("The subtraction is ",(a-b))
elif operator == "*":
print("A product is ",(a*b))
elif operator == "/":
print("O quotient ",(a/b))
else:
print("something here")
Also in Python3, we have a new way to format string that you could use:
a = int(input("First number: "))
b = int(input("Second number: "))
operator = input("Type operation '+', '-','*' ou '/' ")
if operator == "+":
print(f"The sum is {a+b}")
elif operator == "-":
print(f"The subtraction is {a-b}")
elif operator == "*":
print(f"A product is {a*b}")
elif operator == "/":
print(f"O quotient {a/b}")
else:
print("something here")
Let me know if this helps

Categories

Resources