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
Related
I was trying to practice what I've been learning so I had this idea and it covered most of what I've learned. The code works well but I hope if anyone can take a look and let me know how I can make it better.
print("available operations (*, +, /, -)\n\"delete\" to delete every previous calculations\n \"exit\" to stop the program ")
is_running = True
op = ""
while is_running:
try:
num1 = float(input(">> "))
except ValueError:
print("ValueError")
continue
while is_running:
op = input(">> ")
if op == "exit":
is_running = False
break
elif op == "delete":
break
try:
num2 = float(input(">> "))
except ValueError:
print("ValueError")
continue
if op == "*":
num1 = num1 * num2
print(num1)
elif op == "+":
num1 = num1 + num2
print(num1)
elif op == "-":
num1 = num1 - num2
print(num1)
elif op == "/":
num1 = num1 / num2
print(num1)
else:
print("unavailable operator")
break
One thing you can do is to replace the conditionals for operators with dictionary look up as mentioned in below code:
import operator
def calculate(op, num1, num2):
oper = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv
}
try:
return oper[op](num1, num2)
except KeyError:
return 'Invalid Operator'
num1 = 40
num2 = 50
op = '*'
print(calculate(op, num1, num2))
One more thing is that you need not use multiple try-except statements. Only one statement for all the inputs is enough. There is also no need for while loop in the second input statement.
This question already has answers here:
What does "while True" mean in Python?
(18 answers)
Closed 2 years ago.
when i run this code it keeps on giving me the answer
here is my code
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
while True:
if operation == "+":
print num1 + num2
elif operation == "-":
print num1 - num2
elif operation == "*":
print num1 * num2
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
What you might want is to put the input taking code into the while loop:
while True:
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
if operation == "+":
print (num1 + num2)
elif operation == "-":
print (num1 - num2)
elif operation == "*":
print (num1 * num2)
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
`while True:` means Infinite Loop.
You can take input inside while loop or you can change the condition of while loop.
remove the while True: and it will only print out the answer once. while loops continue running as long as the argument is true and True is always true :P
What you probably want is for the application to keep calculating input from the user.
Try this
def calculate():
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
if operation == "+":
print (num1 + num2)
elif operation == "-":
print (num1 - num2)
elif operation == "*":
print (num1 * num2)
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
while True:
calculate()
I'am at the beginning of my road into python, this is my first creation in python and I have a little bit of a problem, I've created a basic calculator, it works kinda good, but my question is how can I make the calculator ask again for num1 and operator after I run it, I mean, I run it, it works, but after the calculation is done, I have to rerun it in order to ask for num1 and op. How can I make it ask again for num1 and op when you press a key after a calculation is done.
This is my first time asking here and if my question is too basic, I'm sorry.
import math
#creating our variables
num1 = float(input("Enter the first number: "))
op = input("Enter the operator: ")
#creating the calculator for simple calculations
if op == "+":
num2 = float(input("Enter the second number: "))
print(num1 + num2)
elif op == "-":
num2 = float(input("Enter the second number: "))
print(num1 - num2)
elif op == "*":
num2 = float(input("Enter the second number: "))
print(num1 * num2)
elif op == "/":
num2 = float(input("Enter the second number: "))
print(num1 / num2)
#creating the advanced calculations
elif op == "square":
print(num1**2)
elif op == "cube":
print(num1**3)
elif op == "square root":
print(math.sqrt(num1))
elif op == "square number":
num2 = float(input("Enter the second number: "))
print(num1**num2)
elif op == "cube root":
print(num1**(1/3))
else:
print("Error, please enter a valid operator")
Run the calculator within a while loop to rerun it continuously.
The simplest way is:
while True:
#calculator code
Or you can have a condition that ends the program:
keep_running = True
while keep_running:
#calculator code
if input('Keep Computing? (yes/no) ').lower() == 'no':
keep_running = False
This is just a simple example but hopefully it breaks down the concept for you.
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 3 years ago.
I'm new to python and am trying to make a basic calculator that takes two numbers and performs the operation specified by the user, but regardless of the operation I enter, the numbers always add.
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" )
if operation == "Add" or "add":
add = num1 + num2
print(add)
elif operation == "Subtract" or "subtract":
sub = num1 - num2
print(sub)
elif operation == "Multiply" or "multiply":
mult = num1 * num2
print(mult)
elif operation == "Divide" or "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
With what I have, if num1 = 10 and num2 = 5 and I enter "multiply" the result I get is 15, not 50.
if operation == "Add" or "add"
These are two conditions:
if operation == "Add" which does what you expect.
if "add" - Always evaluates to True because it's a constant string.
So you could just as well have written:
if True. You need to replace it with:
if operation == "Add" or operation == "add"
Anyway, I would like to suggest a few things.
Lowercase then check only once
You should lowercase your input string instead of double checking "Add" or "add":
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" ).lower() # Notice the `lower` here
if operation == "add":
add = num1 + num2
print(add)
elif operation == "subtract":
sub = num1 - num2
print(sub)
elif operation "multiply":
mult = num1 * num2
print(mult)
elif operation "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
Use the built-in operator module
The operator module contains exactly the methods that you seek for. You could use it for convenience (haven't tested, should work):
import operator
keywords = {"add": "add", "subtract": "sub", "multiply": "mul", "divide": "truediv"}
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" )
op_func = keywords.get(operation.lower(), "add") # defaults to add
print(getattr(operator, op_func)(num1, num2))
def fun(operation, num1,num2):
operation = operation.lower()
if operation == "add":
add = num1 + num2
print(add)
elif operation == "subtract":
sub = num1 - num2
print(sub)
elif operation == "multiply":
mult = num1 * num2
print(mult)
elif operation == "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
fun('multiply', 10,5)
Why:
if operation == "add" or "Add": this is always True
We can use if operation == "add" or operation == "Add":
You have to do like this:
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = str(input("Type Add, Subtract, Multiply, or Divide" ))
if operation == "Add" or operation =="add":
add = num1 + num2
print(add)
elif operation == "Subtract" or operation =="subtract":
sub = num1 - num2
print(sub)
elif operation == "Multiply" or operation =="multiply":
mult = num1 * num2
print(mult)
elif operation == "Divide" or operation =="divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
Because of or operation with string, all your conditions will be true.
That's why it will only go to first condition no matter what you give in the input.
I can't quite figure out why my code won't work.
Whenever I click run, it doesn't follow back with a traceback error, it just says process finished with exit code 0.
I thought it might be the casefold but then when I applied it to "Y". casefold it wouldn't work full stop.
def calculate():
operator = input("please select the kind of maths you would like to do")
if operator == "+":
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
print('{} + {} ='.format(num1, num2))
print(num1 + num2)
elif operator == "-":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} - {} =".format(num1, num2))
print(num1 - num2)
elif operator == "*":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} * {} =".format(num1, num2))
print(num1 * num2)
elif operator == "/":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} / {} =".format(num1, num2))
print(num1 / num2)
else:
_exit = input("would you like to exit? type Y for YES and N for NO")
if _exit.casefold() == "y":
sys.exit()
else:
calculate()
Just add calculate() at the very end to call the function.
Put function calling calculate() at the end without any indent. Your function isn't even getting called, thus giving no error.
You need to call this calculate() function first (at least it's not being executed in your code sample).
def calculate()
# func code here
#Exec this function
calculate()
I guess it should be like this:
def calculate():
operator = input("please select the kind of maths you would like to do")
if operator == "+":
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
print('{} + {} ='.format(num1, num2))
print(num1 + num2)
elif operator == "-":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} - {} =".format(num1, num2))
print(num1 - num2)
elif operator == "*":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} * {} =".format(num1, num2))
print(num1 * num2)
elif operator == "/":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} / {} =".format(num1, num2))
print(num1 / num2)
else:
_exit = input("would you like to exit? type Y for YES and N for NO")
if _exit.casefold() == "y":
sys.exit()
else:
calculate()
calculate()