If else function does not working correctly [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
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.
When I say "n" or "no" for the input if works fine but when i say "y" or "yes" for the input it just does the same thing as for "no". everything else in the program runs perfectly apart from this. i have absolutely no clue as to why this is happening.
def restart():
replay = input("Do you want to restart? (Y/N): ")
if replay.lower() == "n" or "no":
print("exiting")
sys.exit()
if replay.lower() == "y" or "yes":
calc()
else:
print("Unknown Command")
restart()
restart()

The conditions in your if statements aren't evaluating the way you think they are. When you use a logical operator like the or you have, it evaluates first the part before the or, and then the part after the or, and if either is true the whole statement is true.
So instead of
if replay.lower() == "n" or "no": #always runs because just "no" evaluates as being true
use
if replay.lower() == "n" or replay.lower == "no":
and make a similar change to your if statement which tests for yes.

Replace this:
if replay.lower() == "n" or "no":
print("exiting")
sys.exit()
if replay.lower() == "y" or "yes":
calc()
With this:
if replay.lower() == "n" or replay.lower() == "no":
print("exiting")
sys.exit()
if replay.lower() == "y" or replay.lower() == "yes":
calc()

Related

My python code has errors, but just in the try- except loop. [duplicate]

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 4 years ago.
My python code has some errors in the try- except loop. If you enter an input which is not yes or no, it first prints the "yes" reply output, then once you answer the question it shows the output for if you do not enter yes or no. Here's the code:
playAgain = None
while playAgain != "Yes" or "No" or "yes" or "no" or "y" or "n":
try:
playAgain = str(input("Do you want to play again? Enter Yes or No: "))
if playAgain == "Yes" or "y" or "yes":
displayIntro()
elif playAgain == "No" or "no" or "n":
print("Oh, well. The magic 8 ball will see you next time...")
sys.exit()
except:
print("That wasn't yes or no, idiot. The magic 8 ball will not give a fortune to such an imbocile.")
Please help and thank you!
playAgain != "Yes" or "No" or "yes" or "no" or "y" or "n"
Is not a correct way to do this.
When you say playAgain != "Yes" then you need to do the same for the remaining expression. So a valid way to do what you were intended to do is the following:
playAgain != "Yes" or playAgain != "No" or playAgain != "yes" or playAgain != "no" or playAgain != "y" or playAgain != "n"
But this is ugly and too long.
Instead, use
playAgain not in ["Yes", "No", "yes", "no", "y", "n"]
In Python, we have some handy ways to deal with such problems. You can use the in operator to check if the string in question exists (or does not exist) in a list of possible values. It's also very nice to read: "if playAgain (is) not in [this list of values]".
You can even manipulate the input so it's easier for you to work with. That is, you lower all the letters and you don't check for case-sensitive input (if you really don't care about case sensitive input; do you really care if is Yes or yEs?):
playAgain.lower() not in ["yes", "y"]
Something like this should do:
while True:
playAgain = str(input("Do you want to play again? Enter Yes or No: "))
if playAgain.lower() in ["yes", "y"]:
# do something with your yes input. Consider `break` out of the endless loop.
elif playAgain.lower() in ["no", "n"]:
# do something with your no input. Consider `break` out of the endless loop.
else:
print("That wasn't yes or no.")
Note that the above loop is endless. You need to break-out according to your program logic. That is, you need to put a break statement somewhere when you need to break out of the endless loop.

How to fix the logical error in my while loop? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 years ago.
Hello programmers of StackOverFlow, I am a teenager that studies Python, And I can't find the logical errors in one of my codes. I wish you could help with that.
I got two logical errors.
1. If the answer is "yes" or "no" it keeps opening the while commands while it shouldn't.
2. Concluding from first error it never stops when the choice == "yes" or "no"..
My coding is here:
choice = raw_input("Do you like programming? (yes/no) : ")
while choice != "yes" or "no":
choice = raw_input('Come on, answer with a "yes" or with a "no" ! : ')
if choice == "yes":
print "I like you !"
elif choice == "no":
print "I am sorry to hear that .. "
, Thank you in advance !
the second line evaluates to True. Because the string "no" evaluates to true
try the following
if "any string": print(1) #will always print 1, unless the string is empty
What you should use instead is
while choice not in ["yes", "no"]:
which checks if choice matches either "yes" or "no"
This is the problem:
while choice != "yes" or "no":
This is interpreted by Python as (choice != "yes") or ("no"). Since "no" is a string of non-zero length, it is truthy. This makes the or expression true because anything OR true is true. So your condition is always true and the loop never stops.
It should be:
while choice != "yes" and choice != "no":
Or:
while choice not in ("yes", "no"):

Python 2: What is wrong with this else/if statement. always receiving same output [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 7 years ago.
So, I Am trying to create some code, and for whatever reason the following always gives the same output, "Great! let's continue"
I am fairly new programmer, so any explanation has about why this is happening and how I can fix it is welcome. Thank you!
#python 2
UserAnswer = raw_input('Is your age and birthday correct? (yes/no):')
if UserAnswer == 'yes' or "Yes":
print ("Great! let's continue.")
elif UserAnswer == 'no' or "No":
print("check for your error, the program will now end")
SystemExit
else:
print 'Invalid input.'
The following line will always evaluate to True:
if UserAnswer == 'yes' or "Yes"
This is because "Yes", when treated as a boolean, evaluates to True. So the result of the OR will be True. You can fix it by changing it to the following (and do the same thing for the other line)
if UserAnswer == 'yes' or UserAnswer == 'Yes'
Don't do:
if UserAnswer == 'yes' or "Yes":
Do instead:
if UserAnswer == 'yes' or UserAnswer == "Yes":
Same applies to the elif condition

In this if statement when i type no in the raw_input it is going through the yes part. How do i fix it? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
When I type no into the input on the terminal. It goes through the if choice == "yes" part.
I want it to go through the else. Please help.
choice=raw_input("Will you help us? Yes or no?")
if choice == "yes" or "Yes":
print "Yeah! You are a hero!"
name = raw_input("What is your name?")
print "Alright, " + str(name) + " ,let's go choose a weapon from the blacksmith."
else:
print "You're a coward. :("
quit()
What's wrong?
The bug is in this line of code:
if choice == "yes" or "Yes":
Python sees this as an "or" of two conditions:
if (choice == "yes") or ("Yes"):
Which is same as:
if (choice == "yes") or True:
because a non-empty string is always True.
And this finally reduces to:
if True:
as "or"ing with True always evaluates to True.
This would give you the desired result:
if choice == "yes" or choice == "Yes":
However, that is considered C-style and the pythonic way of comparing multiple values is:
if choice in ("yes", "Yes"):
But in this case, you just want to do a case-insensitive match. So the right way to do that would be:
if choice.lower() == "yes":
And this would even handle odd capitalization in inputs like "yEs" or "YEs".
choice=raw_input("Will you help us? Yes or no?")
if choice == "yes" or choice == "Yes":
print "Yeah! You are a hero!"
name = raw_input("What is your name?")
print "Alright, " + str(name) + " ,let's go choose a weapon from the blacksmith."
else:
print "You're a coward. :("
quit()
The above is the correct format. You did not have the logic set up correctly. Note the following:
a = 1
if a == 2 or 3 :
print 'OK'
It prints 'OK'. Why?
The reason is that python values are evaluated in a left to right fashion. If any value is true then that value is returned. However if all values are false then the last value is returned, in your case 'Yes'. This is what is causing you problems as far as I understand it. You need basically two 'or' conditions, not one....

Case insensitivity in "if" statement (Python) [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 8 years ago.
I am working on a project that at one point will ask the user a yes/no question. I currently use this code to handle such questions:
def yn():
global finalchoice
choice=str(raw_input("Y/N: "))
if choice == "Y":
finalchoice="true"
elif choice == "y":
finalchoice="true"
elif choice == "N":
finalchoice="false"
elif choice == "n":
finalchoice="false"
else:
yn()
pass
but this seems to be quite inefficient, specifically where I have to check for both "Y" and "y" or "N" and "n" separately. I've tried:
if choice == "Y" or "y":
finalchoice="true"
Unfortunately, all this does is ignore the 'else' command and will pass whatever I give it.
Any tips?
if choice == "Y" or "y": is not right! It will always evaluate to True.
It essentially is (choice == "Y") or ("y"). And the latter is True because any non empty string in python logically evaluates to boolean True.
You should be doing:
if choice in ["Y","y"]:
Or,
if choice == "Y" or choice == "y":
Or you can use:
if choice.lower() == "y":
finalchoice="true"
To add to #Sudipta's answer, one way would be to remove the case AND just take the first letter:
if choice.lower().startswith("y"):
finalchoice="true"

Categories