Calculator: Terminate program if the mathematical operation is invalid - python

I am very new to coding in general and have started learning python just very recently. I am trying to make a simple calculator. However, I am experiencing a problem whereas I want it to terminate the program if the mathematical operation that the user has input is invalid. However, in my case it simply proceeds with the program.
Here is a part of my code
if use_calculator.lower() == "yes":
print("That's great to hear, " + name + " please proceed")
operation = input("What mathematical operation would you like to execute? ")
num1 = float(input("Please input a number: "))
num2 = float(input("Please input another number: "))
if operation.lower() == "+" or "addition":
print(num1 + num2)
elif operation.lower() == "-" or "subtraction":
print(num1 - num2)
elif operation.lower() == "division" or "/":
print(num1 / num2)
elif operation.lower() == "multiplication" or "*" or "x":
print(num1 * num2)
else:
exit()
else:
print("That is very sad to hear, " + name)

Non-empty strings in Python are truthy. This means they will always evaluate to True when used in an if-statement. This can be seen after the or for your if blocks. Instead, you should check if the operation.lower() is contained in a set for every if statement you have like so:
if operation.lower() in ("+", "addition"):
....

Related

How can i make this part of my new code loop?

i want to make it so when you get your answer it automatically asks for another operator and another number until you type stop
like real calculators
from math import*
info = input("Would you like information? : ")
if info == "yes":`enter code here`
print("+ = add")
print("- = subtract")
print("* = multiplication")
print("/ = division")
print("pow/power/p = raise to power")
num1 = float(input("Enter your first number: "))
op = input("Enter your operator: ")
num2 = float(input("Enter your second number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "pow" or "power" or "p":
print(pow(num1, num2))
else:
print("Something went wrong please try again")
from math import *
info = input("Would you like information? : ")
if info == "yes":
print("+ = add")
print("- = subtract")
print("* = multiplication")
print("/ = division")
print("pow/power/p = raise to power")
while True:
num1 = input("Enter your first number: ")
if num1 == "stop":
break
num1 = float(num1)
op = input("Enter your operator: ")
num2 = float(input("Enter your second number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "pow" or "power" or "p":
print(pow(num1, num2))
else:
print("Something went wrong please try again")
print("Code finished")
It obviously does not take edge cases into concideration (like division by zero, making sure that the stuff that you pass to float() is actually a number) but this should get you going :)
cheers.

I am a little bit confused about creating kinda a loop

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.

Computer recognize response as non case sensitive

I'm making a calculator program, it has a square root feature, but first, you need to type 's' in order to access it, I wanna make it so that the user can type "S" or "s" and have the computer still recognize it and bring up the square root option but if I add the s.upper() and the s variable it works but not as intended the code is:
import math
def calculator():
while True:
s = "s"
intro = input('Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n')
if intro not in ["*", "/", "+", "-", "**", s.upper(), s]:
print ("that wasnt an option!")
continue
if intro != s:
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro != s.upper():
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro == "*":
print(num1 * num2)
break
elif intro == "/":
print(num1/num2)
break
elif intro == "+":
print(num1 + num2)
break
elif intro == "-":
print(num1 - num2)
break
elif intro == "**":
print(num1 ** num2)
break
elif intro == s.upper():
num_sqr = int(input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
elif intro == s:
num_sqr = int(input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
calculator()
whenever a user types s it ignores variables num1 and num2 so it can just do run the num_sqr variable so the output is:
s (or S)
Whats your first number
2
Whats your second number
4
What number do you wanna find the square root of
24
4.898979485566356
Rather than:
s (or S)
What number do you wanna find the square root of
24
4.898979485566356
Why is it doing this and how can I fix it?
Go ahead and call the .capitalize() string method over your intro string; it'll insure the correct formatting for the string letters without messing up the formatting on the operators.
import math
def calculator():
while True:
intro = input('Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n')
intro = intro.capitalize()
if intro not in ["*", "/", "+", "-", "**", "S"]:
print ("that wasnt an option!")
continue
if intro != "S":
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro == "*":
print(num1 * num2)
break
elif intro == "/":
print(num1/num2)
break
elif intro == "+":
print(num1 + num2)
break
elif intro == "-":
print(num1 - num2)
break
elif intro == "**":
print(num1 ** num2)
break
else:
num_sqr = int(input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
calculator()
Also just for fun, since this is evaluating string expressions, Python actually provides us with a handy function for applying computations over string objects using the eval() function. So we could also do this:
def calculator():
while True:
intro = input('Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n')
intro = intro.capitalize()
if intro not in ["*", "/", "+", "-", "**", "S"]:
print ("that wasnt an option!")
continue
if intro != "S":
num1 = input("Whats your first number \n")
num2 = input("Whats your second number \n")
print(
eval(num1+intro+num2)
)
break
else:
num_sqr = int(input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
Instead of checking if the command is s and then waiting till the end to execute the square root command, you can run the "s" or "S" command before asking the first or second number.
This code will do`
import math
def calculator():
while True:
s = "s"
intro = input('Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n')
if intro not in ["*", "/", "+", "-", "**", s.upper(), s]:
print ("that wasnt an option!")
continue
if intro == s:
num_sqr = int(input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
if intro == s.upper():
num_sqr = int(input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
if intro != s:
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro != s.upper():
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro == "*":
print(num1 * num2)
break
elif intro == "/":
print(num1/num2)
break
elif intro == "+":
print(num1 + num2)
break
elif intro == "-":
print(num1 - num2)
break
elif intro == "**":
print(num1 ** num2)
break
calculator()
The problem with the code is that you did not actually format the input. You just have to upper() your input, and check all the condition with "S". This will also shorten your code.
import math
def calculator():
while True:
intro = input(
'Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n').upper()
if intro not in ["*", "/", "+", "-", "**", "S"]:
print("that wasnt an option!")
calculator()
if intro != "S":
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro == "*":
print(num1 * num2)
break
elif intro == "/":
print(num1/num2)
break
elif intro == "+":
print(num1 + num2)
break
elif intro == "-":
print(num1 - num2)
break
elif intro == "**":
print(num1 ** num2)
break
elif intro == "S":
num_sqr = int(
input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
calculator()
You made two if statements with two different conditions and even if you enter "s" or "S" one of the if statements is going to evaluate to True all the time.
# ONE OF THIS IF STATEMENT IS GOING TO BE TRUE ALL TIME WHEN ENTER "S" or "s"
if intro != s:
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro != s.upper():
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
You can easily solve this by evaluating both conditions in only one if statement
if intro != s and intro != s.upper(): #<-- if not "s" or "S"
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
Try changing this:
intro = input('Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n')
into this:
intro = input('Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n').lower()

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

How do I get rid of the text from produced by the except?

This is a calculator written in python 3.7 and it works PERFECTLY fine but I just want to have a little improvement so I will ask you, from line 0 to 6, I made a try except block and looped it with while True. This will make the user of this calculator notice "You entered an invalid number". While it does work fine according to the result of the command, for the sake of simplicity, I would like to make the computer only say "enter_first_number" again after the user types in an invalid number at the first. So I want to get rid of the "invalid_number". I could just type in print() instead of print(invalid_number), but I don't like how it looks like the blank that is produced by a that. Can anyone solve this problem?
code:
while True:
try:
num1 = float(input("enter_first_number_&_press_enter: "))
break
except ValueError:
print("invalid_number")
op = input("enter_an_operator: ")
while True:
if op == "+":
break
elif op == "-":
break
elif op == "*":
break
elif op == "/":
break
else:
print("invalid_operator")
op = input("enter_an_operator: ")
while True:
try:
num2 = float(input("enter_second_number_&_press_enter: "))
break
except ValueError:
print("invalid_number")
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
So I want to get rid of the "invalid_number".
Replace the print statement inside the except with pass, which does nothing.
while True:
try:
num1 = float(input("enter_first_number_&_press_enter: "))
break
except ValueError:
pass
Try replacing the print statement with pass.
For example:
try:
num1 = float(input("enter_first_number_&_press_enter: "))
break
except ValueError:
pass
The pass command tells python to continue running without doing anything.
Otherwise, replacing the print statement with print('', end='') will print out an empty string with no newline character at the end.

Categories

Resources