Is this an efficient calculator in Python?
def calculator():
print("\nBasic Calculator.\n")
num_1 = input("Enter your first number: ")
operation = input("Enter your operation: ")
num_2 = input("Enter your second number: ")
if operation == ("+"):
sum = float(num_1) + float(num_2)
print ("The answer is:",(sum))
elif operation == ("-"):
sum = float(num_1) - float(num_2)
print ("The answer is:",(sum))
elif operation == ("*"):
sum = float(num_1) * float(num_2)
print ("The answer is:",(sum))
elif operation == ("/") and num_2 == ("0"):
print ("\nYou cannot divide by zero.")
elif operation == ("/"):
sum = float(num_1) / float(num_2)
print ("The answer is:",(sum))
else:
print("Invalid Operation.")
restart = input("\nDo you want to enter another equation? Yes or No?").lower()
if restart == ("yes"):
calculator()
else:
print ("\nEnding Program.")
quit()
calculator()
You can use eval()
a = 1
b = 2
operation = '/'
print(eval(f'{a} {operation} {b}'))
0.5
Handle shenanigans by users:
a = 1
b = 0
operation = '/'
try:
print(eval(f'{a} {operation} {b}'))
except Exception as exp:
print(exp)
Here is another basic example:
operations = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y,
}
try:
x, sign, y = input("Enter expression separated by whitespace(ex: 2 + 3): ").split()
if sign == '0':
break
else:
print(operations[sign](int(x), int(y)))
except (ValueError, KeyError, ZeroDivisionError):
print("Something went wrong, check your input")
It's decent, but reviews of working code belong on CodeReview.SE, not here.
Call the result variable result instead of sum, that obviously only is meaningful for addition.
As per AlexanderLekontsev's answer, you don't need a huge big if...else ladder that always computes result and prints the output. A dispatch dictionary to (binary or unary) lambda function is better. You could have all the functions be binary, and default arg2=None, that way you can handle unary functions.
You're assuming the user types in valid floats in response to num_1, num_2. But what if they press return? or type pi or e? or 'help' or :-D etc. You should catch the exception ValueError: could not convert string to floatand display the user's invalid input back to them, "expected a number"(/"operator").
You only need num_2 if operation is a binary not a unary operation, but future stuff like sqrt, log, log10, trigonometrics (sin, cos, tan), hyperbolics and their inverses (arc-fns) are all unary operations. Just something to keep in mind for the future. Don't hardwire your parser to one expected input sequence.
Inputting numbers could get more complicated in future. What if you wanted to support both hexadecimal 7e8 and float/general/exponential notation 7e8? You might need multiple try...except clauses. You might add a HEX mode in future. But then you'll need to generalize from num1 to say arg1, and if arg1 == HEX then enable(/toggle) hex mode, and recurse/loop.
Suggest printing print("Invalid Operation: must be +,-,*,/,..."), this actually tells the user which operations are legal. So: % isn't, neither is ^, neither is log, cos, sqrt etc.
So if you implement the above, you can support things like e^x
Supporting parentheses would require recursion.
Try this:
def calculate(num1, num2, operator):
operator = operator.strip()
if operator.strip() in ['+', '-', '*', '/']:
if operator == '/' and eval(num2) == 0:
return None
try:
result = eval(f'float({num1.strip()}) {operator} float({num2.strip()})')
except:
return ""
return result
num1 = '3'
num2 = '5'
operator = '+'
result = calculate(num1, num2, operator)
if result == '':
print('Wrong expression !')
elif result == None:
print('Dive bye zero !')
else:
print(f'The answe is {result} !')
Your code is alright but we can improvise by using eval()
print(" Basic Calculator ")
i = ""
while i != 'exit':
i = input(" Enter the expression to evaluate or type 'exit' to exit : ")
print(eval(i))
Here is a very clean and short calculator script:
num1 = float(input("Enter a number: "))
op = (input("Enter an operation: "))
num2 = float(input("Enter another number: "))
if op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "^":
print(num1 ** num2)
else:
print("error, you did not enter a supported operation")
Also if you were wondering ** means ^ or to the power of.
Try this:
this calculator will take several inputs, and you can choose to clear the values or to delete it before computing the result.
values_collector = [] #empty list for all values
multi = 1
total = 0
index = 0
print('''For addition press the +,
For Subtraction press the -
For division press the /
For Multiplication press the *''')
entries = int(input('Enter the number of the values you want to compute: '))
signs = input('Enter the sign: ')
while index < entries:
my_input = int(input('Enter your values: '))
values_collector.append(my_input)
index +=1
to_remove = input('Do you want to remove any values, enter Y for yes and N for no ').upper()
if to_remove == 'Y':
values_re=[]
x = 0
no_to_remove = int(input('How many variables do you want to remove: '))
while x < no_to_remove:
my_removed = int(input('Enter your values: '))
values_re.append(my_removed)
x +=1
for y in values_re:
values_collector.remove(y)
my_clear = input("Do you want to clear all the values press Y for yes and N for No ").upper()
if my_clear == 'Y':
values_collector.clear()
print('There is no values to compute because its cleared')
elif my_clear == 'N':
if signs == '+':
for x in range(len(values_collector)):
total +=values_collector[x]
elif signs == '-':
for x in range(len(values_collector)):
total -=values_collector[x]
elif signs == '*':
for x in range(len(values_collector)):
multi *=values_collector[x]
total = multi
elif signs == '/':
for x in range(len(values_collector)):
multi /=values_collector[x]
total = multi
print('The computation of all the values {} is {}'.format(values_collector, total))
enter code here
Related
I started learning python last week. I have very weak background in programming as I did C++ before but poorly. I started python and wanted to make a complex calculator. I am trying to learn restrictions and if statements better so I decided to make the calculator for positive values only.
However, upon making this statement. The message appears, but the calculated value also appears.
Here is the code:
op = ""
while op != "#":
num1 = float(input("Enter your first number:"))
op = input("Enter an operator: ")
num2 = float(input("Enter your second number: "))
if num1 < 0 or num2 < 0:
print("Calculator accepts positive values only")
if op == "+":
print(num1+num2)
elif op=="-":
print(num1-num2)
elif op=="*":
print(num1*num2)
elif op=="/":
print(num1/num2)
else:
print("end of program")
How to remove the out put of the calculated number? I want the program to restart the loop when I enter negative numbers
Is there a way to "break" the loop then re-do it again?
I humbly apologize if this is a very trivial question, I recently started, and would love to learn from experienced users here on stackoverflow.
All you really need to do is wrap the if statements in an else loop.
op = ""
while op != "#":
num1 = float(input("Enter your first number:"))
op = input("Enter an operator: ")
num2 = float(input("Enter your second number: "))
if num1 < 0 or num2 < 0:
print("Calculator accepts positive values only")
else:
if op == "+":
print(num1+num2)
elif op=="-":
print(num1-num2)
elif op=="*":
print(num1*num2)
elif op=="/":
print(num1/num2)
else:
print("end of program")
The first if statement checks if the number is positive or not. If it is negative, the loop restarts, however, if it is positive, it tests what the operators are equal to.
Your code is displaying the message along with the ans when you enter a negative value because the condition if op == '+' should be elif op == '+'. Its because it checks the first condition which is true so it prints the message but since the 2nd condition has if as well, it comes out to be true if your operator is + and thus the ans is being displayed. Here's how the correct code would look like:
op = ""
while op != "#":
num1 = float(input("Enter your first number:"))
op = input("Enter an operator: ")
num2 = float(input("Enter your second number: "))
if num1 < 0 or num2 < 0:
print("Calculator accepts positive values only")
elif op == "+":
print(num1+num2)
elif op=="-":
print(num1-num2)
elif op=="*":
print(num1*num2)
elif op=="/":
print(num1/num2)
else:
print("end of program")
break and continue are the operators you are looking for
https://www.programiz.com/python-programming/break-continue
break will stop a loop entirely, continue will stop the current iteration of the loop and go onto the next one.
op = ""
while op != "#":
num1 = float(input("Enter your first number:"))
op = input("Enter an operator: ")
num2 = float(input("Enter your second number: "))
if num1 < 0 or num2 < 0:
print("Calculator accepts positive values only")
continue #start again
if op == "STOP":
break #quit
if op == "+":
print(num1+num2)
I've just started coding and I'm slowly understanding it. For my class we have to make a children's program to practice their math and ask them if they would like to try again if it is correct. I cannot understand how to get my while True loop to restart if they input Y. Any tips? Here is my code:
#Addition
A = int(input("What is %i + %i =" %(N1, N2)))
while add != N1 + N2:
add = int(input("Incorrect, what is %i + %i = " %(N1,N2)))
while add == N1 + N2:
repeat =(input("Correct! would you like to try again? Y/N "))
if repeat == 'n':
break
if repeat == 'y':
continue
if op == "-":
#Subrtraction
s = int(input("What is %i - %i =" %(N1, N2)))
while s != N1 - N2:
s = int(input("Incorrect, what is %i - %i = " %(N1,N2)))
while s == N1 - N2:
repeat =(input("Correct! would you like to try again? Y/N "))
if op == "*":
#Multiply
m = int(input("What is %i - %i =" %(N1, N2)))
while m != N1 * N2:
m = int(input("Incorrect, what is %i - %i = " %(N1,N2)))
while m == N1 * N2:
repeat =(input("Correct! would you like to try again? Y/N "))
This program structure does not make sense.
You can do:
while True:
num1 = int(input("num1 "))
num2 = int(input("num2 "))
op = '+'
calc = -1
if op == "+":
while calc != num1 + num2:
calc = int( input(f"Whats {num1} {op} {num2}?"))
elif op == "-":
pass # code the others
elif op == "*":
pass # code the others
elif op == "/":
pass # code the others - use float where needed instead of int
# comparing floats is difficult due to float math rounding imperfection
print("Correct!" , num1, op, num2,"=",calc)
again = input("Again? Y to do it again: ").lower()
if again != "y":
break # leaves the while True
for doing it you can define a function. Maybe it's little more complicated than what you do in class, but still it's pretty basic, so you can learn it easly :)
when using a function, remember to call it in the first time so it'll work.
here's an example:
def function_name():
while True:
'''your code'''
repeat =(input("Correct! would you like to try again? Y/N "))
if repeat == "y":
function_name() # wach time the user say "y" the code calls the function again.
break # the break will finish the while loop and will close the program.
function_name() # that's where I call the function the first time.
by the way, you don't actually have to use the while loop if you are using the function. but I assume it was your work in class so I'll leave it that way :)
I think it is better to enter a while loop first and then take input from the user or determining whether the answer is correct or not and other questions...
# coding: utf-8
# Start of the 1st Question
redo="y"
A1=-1 # can be any integer but not the correct answer
n1, n2 = 2, 3
while (A1 != n1 + n2) or redo.lower()=="y":
# ask the question
A1 = int(input("What is the sum of %i and %i : " % (n1, n2)))
# if answer is correct
if A1 == n1 + n2:
redo = input("Correct ! Would you like to try again? (Y/[N]) : ")
if redo.lower() == "y":
continue
else:
break
else:
print("Your Answer : %d is Incorrect!" % A1)
The code uses operator that was chosen in the previous play even after choosing a different operator after opting to play again.
I've checked the functions again and still can't find where exactly the problem is.
import random
print "Welcome!"
def get_choice():
print "What are we practicing? \n1. Addition (+) \n2. Subtraction (-) \n3. Multiplication (*) \n4. Division (/)"
option = raw_input('> ')
while option != '+' and option != '-' and option != '*' and option != '/':
print "You typed %r which is not valid. Please enter \'+, -, *,or /\'" %(option)
option = raw_input('>')
return option
operation = get_choice()
def ask_question (operation):
numbers = []
for y in range(0,2):
x = random.randint(1,100)
numbers.append(x)
num1 = numbers[0]
num2 = numbers[1]
print num1, operation, num2
response = int(raw_input('>'))
return num1, num2, response
num1, num2, response = ask_question(operation)
def check_response(response):
if operation == '+':
answer = num1 + num2
elif operation == '-':
answer = num1 - num2
elif operation == '*':
answer = num1 * num2
else:
answer = num1 / num2
i = 0
if response == answer:
print "Correct!"
elif response != answer:
while i < 2:
print "Wrong! Try again: \n%r + %r" %(num1, num2)
i += 1
response = raw_input()
if response != answer and i >= 2:
print "Sorry. You run out of chances."
check_response(response)
def repeat():
while True:
print "Do you want to play again?"
again = raw_input('>')
if again == 'y' or again == 'Y':
get_choice()
ask_question(operation)
check_response(response)
else:
break
repeat()
Welcome! What are we practicing?
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
*
18 * 4
72 Correct! Do you want to play again?
y
What are we practicing?
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
+
94 * 83
The reason it gets stuck on one operation is you are not catching any return value from get_choice() when you call it within repeat(). I adjusted the raw_input() to input() so I could get it to work (I'm on python 3.X, and you should upgrade also since 2.X will be discontinued this year!), and it seems to work fine for me now:
def repeat():
while True:
print("Do you want to play again?")
again = input('>')
if again == 'y' or again == 'Y':
operation = get_choice() # you need to assign "operator" to the return value
ask_question(operation)
check_response(response)
else:
break
repeat()
Sample output:
Welcome!
What are we practicing?
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
> +
82 + 72
>154
Correct!
Do you want to play again?
>y
What are we practicing?
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
> -
57 - 28 # the sign did in fact change to -
>
I'm new to programming/coding and I'm using Python in my course. I have been asked to create a calculator that can add, subtract, divide and multiply. I'm trying to get the program to receive the numbers through input, then ask for what to do with it (eg. plus or minus) through a number entered and then give a result. I have the input stages of the code working but when I get to the last part I cant get it to work. This is the code
FirstNumber = "blank1"
SecondNumber = "blank2"
Device = "blank3"
FirstNumber = input("First number?")
SecondNumber = input("Second number?")
Device = input("Select a Number. Options are; 1.Plus, 2.Minus, 3.Times, 4.Divide.")
if "Device" == 1:
print("FirstNumber"+"SecondNumber")
When it gets the the end it does nothing, help please.
The condition "Device" == 1 will always be False because no string is equal to an integer. You probably want to change it to Device == 1, but this will (likely) still fail because on python3.x, input returns a string. You probably want something like:
Device = int(input("Select a Number. Options are; 1.Plus, 2.Minus, 3.Times, 4.Divide."))
if Device == 1:
print(FirstNumber + SecondNumber)
Of course, for the same reason, you'll probably also want to convert FirstNumber and SecondNumber into some numeric type ...
ops = {
"+": lambda a,b: a+b,
"-": lambda a,b: a-b,
"*": lambda a,b: a*b,
"/": lambda a,b: a/b
}
a = int(input("Please enter the first number: "))
op = input("Please enter an operator: ")
b = int(input("Please enter the second number: "))
print("{} {} {} == {}".format(a, op, b, ops[op](a,b)))
I am trying to create a simple python calculator for an assignment. The basic idea of it is simple and documented all over online, but I am trying to create one where the user actually inputs the operators. So instead of printing 1: addition, 2: subtraction, etc, the user would select + for addition, - for subtraction, etc. I am also trying to make Q or q quit the program.
Any ideas for how to allow the user to type operators to represent the operation?
Note: I know I still need to define my remainder operation.
import math
loop = 1
choice = 0
while loop == 1:
print("your options are:")
print("+ Addition")
print("- Subtraction")
print("* Multiplication")
print("/ Division")
print("% Remainder")
print("Q Quit")
print("***************************")
choice = str(input("Choose your option: "))
if choice == +:
ad1 = float(input("Add this: "))
ad2 = float(input("to this: "))
print(ad1, "+", ad2, "=", ad1 + ad2)
elif choice == -:
su2 = float(input("Subtract this: "))
su1 = float(input("from this: "))
print(su1, "-", su2, "=", su1 - su2)
elif choice == *:
mu1 = float(input("Multiply this: "))
mu2 = float(input("with this: "))
print(mu1, "*", mu2, "=", mu1 * mu2)
elif choice == /:
di1 = float(input("Divide this: "))
di2 = float(input("by this: "))
print(di1, "/", di2, "=", di1 / di2)
elif choice == Q:
loop = 0
print("Thank-you for using calculator")
First off, you don't need to assign choice to zero
Second, you have your code right, but you need to put quotes around the operators in your if statements like this
if choice == '+':
to show that you are checking for a string
make your loop like this:
while 1: #or while True:
#do stuff
elif choice == 'Q': #qoutes around Q
break #use the `break` keyword to end the while loop
then, you don't need to assign loop at the top of your program
You should try replacing if choice == + by if choice == "+".
What you're getting from the input is actually a string, which means it can contain any character, even one that represents an operator.