If function doesn't work as expected in PYTHON [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
Here is a part of my code where the problem is.
It doesn't matter what the input is, the script will end
when I enter something.
It should restart when i enter "yes" or "y"
Without the OR it works without problem
else:
if number == rndnum:
print "Congratulations! You won."
print "Do you want to replay?"
answer = raw_input("Type y (yes) or n (no): ")
dialog = 1
while dialog == 1:
if answer == "n" or "no":
replay = 0
dialog = 0
elif answer == "y" or "yes":
dialog = 0
else:
answer = raw_input("Type y (yes) or n (no): ")
loop = 0 #Will overdo loop var and stop the loop

if answer == "n" or "no":
is interpreted by Python as:
if (answer == "n") or ("no"):
Which is always true, because the second condition in your or clause is always True (non-empty strings in Python are truthy, which means they evaluate to True in a condition):
>>> bool("no")
True
What you need is one of:
if answer in ("n", "no"):
# or
if answer == "n" or answer == "no":
Th same goes for "yes", of course.

Adjust your code like this:
if answer == "n" or answer == "no":
# ...
and:
elif answer == "y" or answer == "yes":
# ...
a or b, where a and b are strings and not both the empty string, will always evaluate to True in a boolean context, demo:
>>> '' or 'x'
'x'
>>> 'y' or 'x'
'y'
>>> '' or ''
''
>>> if 'x': print('hi')
...
hi
>>> if '': print('hi')
...
>>>
The first two expressions will evaluate to True.

Related

If elif else does not detect correct string input 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 5 years ago.
Exit=("")
Exit=str(input("Do you require another service? "))
if Exit=="Yes" or "Yeah" or "Y" or "yes":
print("Okay")
elif Exit=="No" or "Nah" or "N" or "no":
print("Terminating Program")
else:
print("Terminating Program")
When Exit=No, the Yes path is chosen. Why?
That's because it short-circuits and returns "Yeah" on the first logical evaluation:
>>> False or True or True
True
>>> False or 'exit'
'exit'
>>> bool(False or 'exit')
True
>>>
I recommend doing this:
if Exit.lower() in ('yeah', 'y', 'yes'):
print("okay")
elif Exit.lower() in ('no', 'nah', 'n'):
print ("Terminating Program")
else:
print ("Terminating Program")
You can use x in (a, b, c) in python to check if variable x contains one of the values a, b or c:
Exit=("")
Exit=str(input("Do you require another service? "))
if Exit in ("Yes", "Yeah", "Y", "yes"):
print("Okay")
elif Exit in ("No", "Nah", "N", "no"):
print("Terminating Program")
else:
print("Terminating Program")
its easier to just check the first character in a case insensitive way
if exit.lower().startswith("y"):
print ("OK")
else:
print("adios muchacho")
as to why your existing code does not work see below
if "anything" is always boolean True
if some_condition or True is also always True, regardless of whether some_condition is True or False

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....

If Statement and while loop

I'm a self taught programmer, and I just started using python. I'm having a bit of a problem, when I execute this code:
x = 0
while x == 0:
question = raw_input("Would you like a hint? ")
if question == "y" or "yes":
print "Ok"
first.give_hint("Look over there")
x = 1
elif question == "n" or "no":
print "Ok"
x = 1
else:
print "I'm Sorry, I don't understand that"
just so you know, first.give_hint("Look over there") was defined in a class earlier in the program, I just left that part out for sake of space. When I run the program no matter what I type, I get the first case "Look over There", I've been trying to figure out what the problem is, but I just don't understand. If you guys could help me, I'd appreciate it a lot.
The problem is this line:
if question == "y" or "yes":
"yes" will always evaluate to True.
What you really want is:
if question == "y" or question == "yes":
Similar changes must be made for the other conditions.
You made a mistake in your if statement, this should be :
if (question == "y") or (question == "yes"):
print "Ok"
Explanation :
(question == "y" or "yes")
is equivalent to :
(question == "y" or "yes" != 0) # operator 'or' having the prevalence
"yes" string being non-null, ("yes" != 0) always return True, and so do your whole original condition.
The condition is wrong. You have question == "y" and a logical or with the string "yes" that is always True. That is why it evaluates to the first case every time.
Try to change to if question[0] == 'y'

Python loop keeps repeating? Why?

Another_Mark = raw_input("would you like to enter another mark? (y/n)")
while Another_Mark.lower() != "n" or Another_Mark.lower() != "y":
Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
if Another_Mark == "y":
print "blah"
if Another_Mark == "n":
print "Blue"
This is not the actual code I'm using except for the 1st three lines. anyways my question is why does the while loop keep repeating even when I input a value 'y' or 'n', when it asks again if you want to input another mark on the third line. I'm stuck in a infinitely repeating loop.
It shouldn't repeat when the value for Another_Mark is changed to either "y" or "n"
Try:
while Another_Mark.lower() not in 'yn':
Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
not in operator returns true if given object is not found in the given iterable and false otherwise. So this is the solution you're looking for :)
This wasn't working due to boolean algebra error fundamentaly. As Lattyware wrote:
not (a or b) (what you describe) is not the same as not a or not b
(what your code says)
>>> for a, b in itertools.product([True, False], repeat=2):
... print(a, b, not (a or b), not a or not b, sep="\t")
...
True True False False
True False False True
False True False True
False False True True
Your loop logic only every comes out true - if the input is "n", then it's not "y" so it's true. Conversely if it's "y" it's not "n".
Try this:
while not (Another_Mark.lower() == "n" or Another_Mark.lower() == "y"):
Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
Your logic behind the looping is wrong. This should work:
while Another_Mark.lower() != "n" and Another_Mark.lower() != "y":
Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
You need to use AND instead of OR.
It's the way boolean logic distributes. You can say:
NOT ("yes" OR "no")
Or you can distribute the NOT into the parenthesis (which is what you're trying to do) by flipping the OR to an AND:
(NOT "yes") AND (NOT "no")

Categories