How to input operator in python? - python

#Faulty calculator
I want to make a calculator that give the wrong answer of my given question and
give all correct answer of other question
operator = input("Enter operator")
number1 = int(input("Enter your number 1"))
number2 = int(input("Enter your number 2"))
if operator == * and number1 == (45) and number2 == (3):
print(number1operatornumber2: 555)
elif operator == + and number1 == 56 and number2 == 9:
print(number1operatornumber2: 77)
elif operator == / and number1 == (56) and number2 == 6:
print(number1operatornumber2: 4)
else :
print(number1 opertor number2: number1operatornumber2)
In my program comming like this
enter image description here

If you want to take operators as inputs, then you must check every single operator. Here's an edited version of your code that works a little bit.
operator = input("Enter operator: ")
number1 = int(input("Enter your number 1"))
number2 = int(input("Enter your number 2: "))
if operator == '*' and number1 == (45) and number2 == (3):
print(f'{number1 * number2} : 555')
elif operator == '+' and number1 == 56 and number2 == 9:
print(f'{number1 + number2} : 77')
elif operator == '/' and number1 == (56) and number2 == 6:
print(f'{number1 / number2} : 4')
#else :
# print(number1 opertor number2: number1operatornumber2)
Notice the last one. Here you don't know what the operator could be. Hence, you can't apply any operation on it.

operator = input("Enter operator")
number1 = int(input("Enter your number 1"))
number2 = int(input("Enter your number 2"))
if (operator == '*' and number1 == 45 and number2 == 3):
print(number1,operator,number2, 555)
elif (operator == '+' and number1 == 56 and number2 == 9):
print(number1, operator, number2, 77)
elif(operator == '/' and number1 == 56 and number2 == 6):
print(number1, operator, number2, 4)
else :
print(number1, operator, number2, number1,operator,number2)
Update the code by correcting the syntax errors as above. Variables should be seperated by , in the print statement and use quotes to compare operators

Related

Calculator not working if you enter a letter instead of a number

My Calculator is half working. I really put my brain in it but I cant figure out why its not working. Can someone help me?
number1 = input("Enter first number: ")
number2 = input("Enter second number: ")
operator = input("Enter the operation character: ")
result = number1 + operator + number2
if operator == '+':
result = int(number1) + int(number2)
elif operator == '-':
result = int(number1) - int(number2)
elif operator == '*':
result = int(number1) * int(number2)
elif operator == '/':
result = int(number1) / int(number2)
if number1.isdigit() == True:
print (result)
elif number2.isdigit() == True:
print(result)
else:
print("Enter a number.")
It's printing the calculated value, but if you enter a letter instead of a number.
For example:
Enter a first number: 5
Enter a second number: f
Now it should print "enter a number". But im getting this message istead
ValueError: invalid literal for int() with base 10: 'a'
if number1.isdigit() == True:
print (result)
elif number2.isdigit() == True:
print(result)
**else:
print("Enter a number.")**
You have lines like these:
if operator == '+':
result = int(number1) + int(number2)
Before lines like these:
if number1.isdigit() == True:
print (result)
elif number2.isdigit() == True:
print(result)
else:
print("Enter a number.")
So, if operater is indeed a +, Python will try to evaluate int(number1) + int(number2) and fail if number1 or number2 is not the string representation of a number.
This raises a ValueError (as it should) and a raised exception that isn't caught in a try .. except .. block will cause your program to terminated. You cannot continue with uncaught exceptions.
Either you should check first and then try to convert these strings, or you should catch the exception.
Also, you seem to expect your code to continue running after the mistake is made, so you'll need some sort of loop that keeps the program running until the user enters some input that makes sense.
I am not sure that I understood what you what but I think this solves the problem
number1 = input("Enter first number: ")
number2 = input("Enter second number: ")
operator = input("Enter the operation character: ")
result = number1 + operator + number2
if number1.isdigit() == True and number2.isdigit() == True:
if operator == '+':
result = int(number1) + int(number2)
elif operator == '-':
result = int(number1) - int(number2)
elif operator == '*':
result = int(number1) * int(number2)
elif operator == '/':
result = int(number1) / int(number2)
print (result)
else:
print("Enter a number.")
If you are just starting on coding, I suggest you to use this as a reason to search and learn on some few important concepts that will help you to get going.
First, you must validate your inputs before doing anything else with them. In your case, validate that your first and second numbers are actually valid integers, right after they are input. As it is the same validation to be done on both, you can create a function so you can reuse the logic.
def input_number():
num = input("Enter a number: ")
if num.isdigit():
return int(num)
else:
print("Invalid number.")
return input_number()
Here, I check if the input is valid (isdigit is true), and then I return the value already converted to int. If it is not, I call the same function again, and repeat the process. This is called recursion.
You should also validate the operator, because it is only valid among a few options.
def input_operator():
while True:
op = input("Enter the operation character: ")
if op in ["+", "-", "*", "/"]:
return op
else:
print("Invalid operator.")
Here I used a different technique. It is called while statement, and it will repeat the execution inside it until the condition is not True, or until it is explicitly broken (in this case, with a return statement).
Now, you have to add both function definitions on top of your code, then adjust you logic accordingly.
number1 = input_number()
operator = input_operator()
number2 = input_number()
if operator == "+":
result = number1 + number2
elif operator == "-":
result = number1 - number2
elif operator == "*":
result = number1 * number2
elif operator == "/":
result = number1 / number2
print (result)

Displaying a friendly error message for dividing by 0

number1_str = input(" First number: ")
number1 = int(number1_str)
number2_str = input("Second number: ")
number2 = int(number2_str)
operation = input("Operation [+, -, *, /]: ")
if operation == "+":
combination = number1 + number2
elif operation == "-":
combination = number1 - number2
elif operation == "*":
combination = number1 * number2
elif operation == "/":
combination = number1 / number2
else:
print(f"Answer: {combination}")
print()
input("Press return to continue ...")
Hi I'm trying to modify this code so that it displays an error message when number2 is zero and you are using the divide function to say "Sorry division by 0 is impossible" or along the lines of that. I'm very new to Python so this might be trivial for some. I've tried try and except statements however no luck. Very eager to learn from all answers!
You can try this:
number1_str = input(" First number: ")
number2_str = input("Second number: ")
operation = input("Operation [+, -, *, /]: ")
operation_list = ["+", "-", "*", "/"]
if operation in operation_list and number1_str.replace(".", "", 1).isnumeric() and number2_str.replace(".", "", 1).isnumeric():
number1 = float(number1_str)
number2 = float(number2_str)
if operation == "+":
combination = number1 + number2
elif operation == "-":
combination = number1 - number2
elif operation == "*":
combination = number1 * number2
else:
if number2 == 0:
combination = "Sorry division by 0 is impossible"
else:
combination = number1 / number2
print(f"Answer: {combination}")
else:
print("Error! Not valid formula")
Use Exception handling try-except can handle any error and if you want to make your own error message using raise keyword.
number1_str = input(" First number: ")
number1 = int(number1_str)
number2_str = input("Second number: ")
number2 = int(number2_str)
operation = input("Operation [+, -, *, /]: ")
try:
if operation == "+":
combination = number1 + number2
elif operation == "-":
combination = number1 - number2
elif operation == "*":
combination = number1 * number2
elif operation == "/":
combination = number1 / number2
else:
print(f"Answer: {combination}")
print()
input("Press return to continue ...")
except ZeroDivisionError:
print("Sorry division by 0 is impossible")

Is there a way to skip lines of code when condition has been met

newbie to python and I was creating a basic calculator with functions and variables and such, was wondering if there was a way for python to skip the two lines that you enter num1 and num2 in. Currently if you make the opr == cube/square it doesn't ask for a number to cube/square it just goes straight to the lines asking for num1 and num2.
opr = input("Would you like to multiply (*), Divide (/), Subtract (-), Add (+), Cube (cube) or Square (square):")
if opr == "cube":
cube1 = int(input("Enter Number To Cube"))
elif opr == "square":
square1 = int(input("Enter Number To Square"))
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
def cube(num):
return num * num * num
def square(num):
return num * num
if opr == "*":
result = float(num1) * float(num2)
if opr == "/":
result = float(num1) / float(num2)
if opr == "-":
result = float(num1) - float(num2)
if opr == "+":
result = float(num1) + float(num2)
if opr == "cube":
result = cube(cube1)
if opr == "square":
result = square(square1)
print(result)
Any help is greatly appreciated!
You can simply add them in a condition :
elif opr == "*" or opr == "-" or opr == "+" or opr == "/":
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))

Calculator to execute loop until "exit"

I got to do this calculator on python 3 that must execute on loop until the user types exit. Besides, programming ahead of the user typing invalid characters, such as letters when asked to type an operator or a number.
I must use while, if... However, I cannot use import.
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator != "+" or "-" or "*" or "/":
print ("You must enter an operator")
break
no1 = input("Enter a number: ")
no2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else :
output = int(num1) / int(num2)
print("The result is " + str(result))
print("See you soon!")
I expect it to actually not stop when we enter anything but an operator, I want it to loop back to:
operator = input("Give me an operator or \"exit\" to stop : ")
You will find below this your code that work as expected, however lets start with general rules.
Be attentif, when you declare a variable, use the same elsewhere in your code.
Test, simple part of your code before trying to do a script. You condition to test operator was totally broken.
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator not in [ "+", "-", "*" , "/"]: #<== here you condition is wrong ,do this instead
print ("You must enter an operator")
continue
try:
num1 = int(input("Enter a number: ")) #
num2 = int(input("Enter a number: ")) # <== both of this variable are not use else where ,rename to be consitdnt with the rest of your code
except ValueError:
print("Please enter an integer")
if operator == "+":
output = num1 + num2
elif operator == "-":
output = num1 - num2
elif operator == "*":
output = num1 * num2
else :
output = num1 / num2
print("The result is " + str(output)) #<=== here also, results was not defined
print("See you soon!")
Put a generic else statement which will continue with the next iteration.
if condition1 :
//logic
elif condition2 :
//logic
else:
continue
Your problem is that you are doing:
if operator != "+" or "-" or "*" or "/":
And what that is really doing, is that:
if operator != "+" or 45 or 42 or 47: (ASCII representation of these characters)
What this means, is that the condition is true no matter what, because or n where N is not 0, would pass any time.
You want:
if operator != "+" and operator != "-" and operator != "*" and operator != "/":
You want an AND gate.
Also, I noticed you are saying no1 = input(...) then doing int(num1) instead of int(no1).
As for jumping back to input, you use continue
Final code:
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator not in [ "+", "-", "*" , "/"]: # credit to Florian Bernard for this line :)
print ("You must enter an operator")
continue
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else:
output = int(num1) / int(num2)
print("The result is " + str(output)) # this was previously str(result) but result is was not defined
print("See you soon!")
BUT! if you are feeling new today, you can use the walrus operator introduced in PEP 572 and available from python 3.8
while (operator := input("Give me an operator or \"exit\" to stop : ")) != "exit":
if operator not in [ "+", "-", "*" , "/"]: # credit to Florian Bernard for this line :)
print ("You must enter an operator")
continue
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else:
output = int(num1) / int(num2)
print("The result is " + str(output))
print("See you soon!")
EDIT:
Edited the final code to use continue, previous version was.
Also added a python 3.8 implementation.
EDIT2:
Just correcting some stuff, making sentences truer.

How to parse user input as a number

I am making a calculator program in my Python, following a tutorial. Here is my code:
print ("This is a calculator program, press Enter to continue")
a = input()
while a == "":
print("Enter 1 for option 1 which adds")
print("Enter 2 for option 2 which subtracts")
print("Enter 3 for option 3 which multiply")
print("Enter 4 for option 4 which divides")
print("Enter 5 for option 5 which quits",)
Option = input("Enter an option number:")
int(Option)
if Option == 1:
Number1 = input("Enter number 1")
Number2 = input("Enter number 2")
int(Number1,Number2)
print(Result = Number1 + Number2)
if Option == 2:
Number1 = input("Enter number 1")
Number2 = input("Enter number 2")
int(Number1,Number2)
print(Result = Number1 - Number2)
if Option == 3:
Number1 = input("Enter number 1")
Number2 = input("Enter number 2")
int(Number1,Number2)
print(Result = Number1 * Number2)
if Option == 4:
Number1 = input("Enter number 1")
Number2 = input("Enter number 2")
int(Number1,Number2)
print(Result = Number1 / Number2)
if Option == 5:
break
It is very basic, it gets up to the point of printing all the option numbers and then asks me to pick one. So I enter "1" as a string, parsing it to an integer 1. However it doesn't go straight to option 1 and instead loops again which is fine I will sort that out later. But again it doesn't go to any option when I enter 1-5. I think I typed in the wrong code to parse it or something?
input() converts the input to a string, so if you need to read an int, you have to cast it.
In the if condition, you could cast the input() result (a string) to int:
Number1 = int(input("Enter number 1"))
then create a variable, let's say result and assign it the sum of the numbers:
result = Number1 + Number2
and finally print the result
print "Result = " + str(result)
The final code should look like this:
print ("This is a calculator program, press Enter to continue")
a = input()
while a == "":
print
print("Enter 1 for option 1 which adds")
print("Enter 2 for option 2 which subtracts")
print("Enter 3 for option 3 which multiply")
print("Enter 4 for option 4 which divides")
print("Enter 5 for option 5 which quits",)
Option = input("Enter an option number:")
if Option == 1:
Number1 = int(input("Enter number 1"))
Number2 = int(input("Enter number 2"))
result = Number1 + Number2
print "Result = " + str(result) # To print you have to cast to `str`
elif Option == 2:
...
elif Option == 3:
...
elif Option == 4:
...
else:
break
Notes:
You could use an if-elif-else as the structure, so if Option == 1, the following conditions won't be checked.
I would also recommend you to follow Python naming convention. Your variable Number1 should be called number1 and so on.
Result of input function is a string, you need to convert it to int, using int type .
>>> foo = "3"
>>> foo
'3'
>>> int(foo)
3
Your misconception might come from that python is a dynamically typed language. But remember that despite variables themselves are untyped, variable values have types.
>>> type(foo)
<class 'str'>
>>> type(int(foo))
<class 'int'>
Your code should look more like this:
print("This is a calculator program. Press Enter to continue.")
while True:
_ = input()
print("Enter 1 for option 1 which adds")
print("Enter 2 for option 2 which subtracts")
print("Enter 3 for option 3 which multiply")
print("Enter 4 for option 4 which divides")
print("Enter 5 for option 5 which quits")
option = int(input("Enter an option number: "))
if option == 5:
break
else:
number1 = int(input("Enter number 1: "))
number2 = int(input("Enter number 2: "))
if option == 1:
result = number1 + number2
elif option == 2:
result = number1 - number2
elif option == 3:
result = number1 * number2
elif option == 4:
result = number1 / number2
print(result)
Salient points:
You aren't doing anything with a. So I got rid of it, and put a call to input that stores its result in _, which is the standard name for a variable whose value you don't care about.
You must explicitly convert option to an int. Python will not implicitly convert for you, and so '1' != 1.
You cannot convert to an int in-place - writing int(number1) does nothing. You must write number1 = int(number1) or similar.
You cannot convert multiple strings to an int in a single statement of the form int(number1, number2). What you're actually doing here is calling int(x, base), where you convert x into an int, interpreted as being in base base.
I refactored your if statements to be more concise
Variable names are typically lowercase in Python.
You cannot assign to a variable inside a print statement.
that code posted contains several errors, below is the corrected code:
print ("This is a calculator program, press Enter to continue")
a = input()
while a == "":
print("Enter 1 for option 1 which adds")
print("Enter 2 for option 2 which subtracts")
print("Enter 3 for option 3 which multiply")
print("Enter 4 for option 4 which divides")
print("Enter 5 for option 5 which quits",)
Option = int(input("Enter an option number:"))
if Option == 1:
Number1 = int(input("Enter number 1"))
Number2 = int(input("Enter number 2"))
# int(Number1,Number2)
Result = Number1 + Number2
if Option == 2:
Number1 = int(input("Enter number 1"))
Number2 = int(input("Enter number 2"))
# int(Number1,Number2)
Result = Number1 - Number2
if Option == 3:
Number1 = int(input("Enter number 1"))
Number2 = int(input("Enter number 2"))
# int(Number1,Number2)
Result = Number1 * Number2
if Option == 4:
Number1 = int(input("Enter number 1"))
Number2 = int(input("Enter number 2"))
# int(Number1,Number2)
Result = Number1 / Number2
print(Result)
if Option == 5:
break
I corrected your code.
_ = input("This is a calculator program, press Enter to continue")
print ("""Enter 1 for option 1 which adds
Enter 2 for option 2 which subtracts
Enter 3 for option 3 which multiplies
Enter 4 for option 4 which divides
Enter 5 for option 5 which quits""")
while True:
Option = input("Enter an option number: ")
if Option == '1':
Number1 = int(input("Enter number 1: "))
Number2 = int(input("Enter number 2: "))
print("The Result is {0}".format(Number1 + Number2))
elif Option == '2':
Number1 = int(input("Enter number 1: "))
Number2 = int(input("Enter number 2: "))
print("The Result is {0}".format(Number1 - Number2))
elif Option == '3':
Number1 = int(input("Enter number 1: "))
Number2 = int(input("Enter number 2: "))
print("The Result is {0}".format(Number1 * Number2))
elif Option == '4':
Number1 = int(input("Enter number 1: "))
Number2 = int(input("Enter number 2: "))
print("The Result is {0}".format(Number1 / Number2))
else:
break
Notes:
Triple quote syntax is good for long multiline strings.
The pythonic way of formatting a printed string is the str.format method.
Good luck learning!

Categories