Why does the 'else' statement execute even though the 'if' was true? - python

I can't work out why the output is evaluating to "?" instead of to int(3). Could someone please explain this? Running Python 3.8.
number1=3
number2=1
operator="*"
if operator =="+":
answer=number1+number2
if operator =="-":
answer=number1-number2
if operator =="*":
answer=number1*number2
if operator =="/":
answer=number1/number2
else:
answer="?"
print(answer)
I tried the search function but could not find anything that resolved my issue. Thanks for your help!

You run a few if in a row. The else statement is part of the last if and is not effective in the prev ifs. Try this -
if operator =="+":
answer=number1+number2
elif operator =="-":
answer=number1-number2
elif operator =="*":
answer=number1*number2
elif operator =="/":
answer=number1/number2
else:
answer="?"

The last else statement will be run while operator != "/"。 You should use elif statement
Right way:
number1=3
number2=1
operator="*"
if operator =="+":
answer=number1+number2
elif operator =="-":
answer=number1-number2
elif operator =="*":
answer=number1*number2
elif operator =="/":
answer=number1/number2
else:
answer="?"
print(answer)

Related

Python: can anyone tell me why a while loop i use for invalid operators is not working? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I understand that when typing an invalid operator for the first time the while loop begins but after I type a valid operator after the loop begins, it doesn't seem to exit out of it.
Is it because I have multiple conditions , since it actually works if I only have one condition?
numb_1 = float(input("Enter the first number:"))
operator = input("Enter an operator:")
numb_2 = float(input("Enter the second number:"))
while operator != ("+") or operator != ("-") or operator != ("*") or operator != ("/"):
print("Invalid operator please try again.")
operator = input("Enter an operator:")
if operator == ("+"):
print(numb_1 + numb_2)
elif operator == ("-"):
print(numb_1 - numb_2)
elif operator == ("*"):
print(numb_1 * numb_2)
elif operator == ("/"):
print(numb_1 / numb_2)
A little code snippet might help to understand your exact question. An operator is typically something like '+', '-', '/', '%', '*', '&', ... etc. I'm not clear what you mean with an "invalid operator". Since you are referring to a while loop, and expecting it to exit out, I guess you are referring to a 'condition'?
while(<condition == true>):
<do something>
Make sure your condition actually once becomes not True (False), and your code block should jump out of your while block.
Updating now that the original post has the code.
The problem is here:
operator != ("+") or operator != ("-") or operator != ("*") or operator != ("/")
Since you are using a logical 'or' operator, the moment 1 of these conditions is true, the entire condition is true. See truth table of OR.
Which means... if you enter +, the condition "operator != ("-")" is true... => the while loop condition is true, and you stay in the loop forever.
A better ways would be:
operator = input("Enter an operator:")
while operator not in ["+", "-", "*", "/"]:
print("Invalid operator please try again.")
operator = input("Enter an operator:")
Try this:
numb_1 = float(input("Enter the first number:"))
while True:
operator = input("Enter an operator:").strip()
if operator in["+", "-", "/", "*"]:
break
else:
print("Invalid operator please try again.")
numb_2 = float(input("Enter the second number:"))

Not resulting the way I want it to [duplicate]

This question already has answers here:
Testing user input against a list in python
(4 answers)
Closed 2 years ago.
operator = input("Please select one option: add/subtract/multiply/divide: ")
if operator != "add" or operator != "subtract" or operator != "multiply" or operator != "divide":
print("The option you chose (" + operator + ") is not valid\nPlease try this program again.")
sys.exit()
Result:
Please select one option: add/subtract/multiply/divide: add
The option you chose (add) is not valid
Please try this program again.
You're confusing how boolean algebra works.
operator != "add" or operator != "subtract" or operator != "multiply" or operator != "divide"
This will return true if operator is not either of add/subtract/multiply/divide.
So when you enter add, operator != "add" returns false, but the next one - operator != "subtract" returns true. Since it is an or operator, only one of all the expressions need to return true, for the whole expression to return true.
You should instead do-
operator != "add" and operator != "subtract" and operator != "multiply" and operator != "divide"
In simple english, that reads "return true if operator is none of add/subtract/multiply/divide"
Or more simply, using the in operator-
operator not in ["add", "subtract", "multiply", "divide"]
Which in simple english, reads "return true if operator is not an element in the list ["add", "subtract", "multiply", "divide"]"

Can I use the calculator of the Python shell in my own code?

So I am working on a small assistant which is supposed to read websites, convert units etc. Me and my friend are still working on getting the first commands up, so we tried to make a calculator. It is supposed to be able to calculate calculations with multiple operators and brackets, like the Python Shell does. But there seems to be no way to just input a string into the shell to use it for this. All calculator codes we found were very long and couldn't handle more than one operator. Do we have to use a long script for this or is there an easier way? My partner wrote something like this, it seemed to be the easiest option:
calc = input()
calc2 = calc.split()
num1 = float(calc2[0])
num2 = float(calc2[2])
operator = calc2[1]
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == ("*" or "x"):
print(num1 * num2)
elif operator == ("/" or ":"):
print(num1 / num2)
elif operator == "//":
print(num1 // num2)
elif operator == "**":
print(num1 ** num2)
elif operator == "%":
print(num1 % num2)
else:
print("ERROR")
Here is what you can do:
if "+" in s:
print(s[0]+s[-1])
if "-" in s:
print(s[0]-s[-1])
Using the subscriptions [0] and [-1] (first element and last element) will make whether the user adds spaces between the numbers and operator optional.
Yes, you can easily do this with the eval function:
#!/usr/bin/env python3
calc = input()
result = eval(calc)
print(calc + " = " + str(result))
However, what you call "the calculator of the Python shell" is in fact a complete Python interpreter, so just like in a Python shell, you can input strings that will not just compute expressions, but also e.g. delete all your files:
import os; os.system("rm -f /")
Whether this is a problem is up to you.
if you want to input a string like "4 + 5"
then you need to check what operator is there so instead of saying if operator == X (because that's manual) say
if "+" in String:
String = String.split(" + ")
print(String[0] + String[1])
if "-" in String:
String = String.split(" - ")
print(String[0] - String[1])
You can alternatively use exec
calc = input()
exec('res='+calc)
print(res)

Python Invalid Syntax on simple Maths Program

I am trying to create a random maths question quiz but the colon comes up as invalid syntax. Is it due to the operator I can not use the colon? If I take it out it is also seen as invalid syntax.
This is the code to create the 'correct_answer' variable so if the users in putted answer is correct or incorrect it lets them know. If the whole code is needed (which I'm sure it won't be as this is probably something really stupid i'm missing) I can post it.
if operator==+:
correct_answer=random_number1+number2
elif operator==-:
correct_answer=random_number1-number2
else:
correct_answer=random_number1*number2
FULL CODE:
import random
name=raw_input("Hi what's your name?")
print "Alrighty lets go, "+name+"!"
for i in range(10):
operator_list=('+','-','x')
operator=random.choice(operator_list)
random_number1=random.randint(1,12)
random_number2=random.randint(1,10)
question=1
print random_number1, operator, random_number2
if operator==+:
correct_answer=random_number1+number2
elif operator==-:
correct_answer=random_number1-number2
else:
correct_answer=random_number1*number2
answer = eval(str(int(raw_input("What is the answer?"))))
if answer==correct_answer:
print "Great job!"
else:
print"Unlucky pal! It was " +correct_answer+ "
question+1
I'm assuming that + and - are strings. If so, you need quotes around them. It's also good practice to space out your code to make it more legible.
if operator == '+':
correct_answer = random_number1 + number2
elif operator == '-':
correct_answer = random_number1 - number2
else:
correct_answer = random_number1 * number2
ANSWER: All that was needed were speech marks around the operator.
if operator == "+":
correct_answer=random_number1+number2
elif operator == "-":
correct_answer=random_number1-number2
else:
correct_answer=random_number1*number2
Ans:
When you wrote + and - , python took it as a real for integer operator and gave it an error because there were no numbers. Adding " " will define it as a string and should not give a error.
Corrected version:
if operator == "+":
correct_answer=random_number1+number2
elif operator == "-":
correct_answer=random_number1-number2
else:
correct_answer=random_number1*number2

Confusing result from raw_input() in Python

I'm having problems with the "operator" variable. So far I have only tried +. It doesn't seem to register and I can't figure out why. i'm using the online python interpreter on repl.it because I'm having problems with my computer.
EDIT: I should probably add that I just started learning Python (I had some Java experience but it was years ago). I'm trying to create a simple text calculator.
restart=raw_input("to restart calculations enter \'true\'")
#if restart == "true":
#stuff
numone=raw_input("Enter the first number: ")
operator = raw_input("Enter the operator(+,-,*,/):")
operator = str(operator)
numtwo=raw_input("Enter another number: ")
print("operator: " + operator)
if operator== '+':
answer=numone+numtwo
print(answer)
print("test")
if operator == "-":
answer=numone-numtwo
print(answer)
else:
print("something went wrong")
#if operator == "*":
Your problem is that you're concatenating two strings, you should cast to int before:
answer = int(numone) + int(numtwo)
Why? Because raw_input reads the input as string.
Give elif to the second statement
since user give '+'
first if statment excutes but in next statement it fails and go to the else so for + you get two result both addition and something wrong
and also you need to convert the operands to integer
one more thing while converting to integer you need check right conditions for integer else it will give error
numone=raw_input("Enter the first number: ")
operator = raw_input("Enter the operator(+,-,*,/):")
operator = str(operator)
numtwo=raw_input("Enter another number: ")
print("operator: " + operator)
if operator== '+':
try:
answer=int(numone)+int(numtwo)
print(answer)
print("test")
except ValueError:
print "one of the operand is not integer"
elif operator == "-":
try:
answer=int(numone)-int(numtwo)
print(answer)
print("test")
except ValueError:
print "one of the operand is not integer"
else:
print("something went wrong")

Categories

Resources