I am using a very simple and basic if elif in python but it only will give me the same result no mater what my input is.
answer = input('Do you like christmas? ')
if answer == 'no' or 'No':
print('Your so uncool, just leave, this is a place for festive people you
heartless monster')
elif answer == 'yes' or 'Yes':
print('Your pretty cool, you can stay, just dont get drunk on the eggnog and
make out with the dog...')
elif 'brit' or 'Brit' in answer:
print('I was gunna be mean to brit, but its christmas and I am not allowed
because a fat man in a red suit will reck me')
else:
print('MAKE UP YOUR MIND, YOU SUCK')
the outputs are place holders but at the moment all I get when I run this is the the print for the no answer, weather I answer no yes or anything else...
edit: I see now that in the question my indenting looks really terrible, that isn't how I wrote it but that is just from posting it here, please assume that indentation is correct.
You are getting this because your first if statement is actually being parsed like this:
if (answer == 'no') or ('No'):
Which means if either answer == 'no' or 'No' is considered "truthy", then the statement will go ahead. Any non-empty string in python is considered to be true so you will always get True in your first statement.
bool('')
# will output False
bool('No')
# will output True
If you actually want to perform this, you've got to run the comparison every time...
if answer == 'no' or answer == 'No':
However, there are some cleaner ways of doing this, such as
answer.lower() == 'no'
# or, if you want lots more examples
answer in ['no', 'No', 'NOPE', 'Not at all', 'Never']
Would recommend reading up
Your problem is with the if's statements:
answer = 'yes'
if answer == 'no' or 'No':
1. ^ (this is saying, 'yes' == 'no' or 'No')
2. ^ (this is saying, False or 'No')
3. ^ (this is saying, False or True)
4. ^ (this is saying True)
In python strings are truthy, meaning that they are interpreted as true in boolean statements.
So your correct statement (and for the others):
answer = 'yes'
if answer == 'no' or answer == 'No':
1. ^ (this is saying, 'yes' == 'no' or 'yest == ''No')
2. ^ (this is saying, False or False)
3. ^ (this is saying False)
So that's it! Oh, another tip, you can compare any type of no/yes this way
answer = str.lower(input('Do you like christmas? '))
if answer == 'no':
^ Even if the user types 'No', it will be turned into 'no'.
Related
I want to do confirmation question from a selection question
e.g
x_selection = 0
x_confirmation = 0
while x_selection = 0:
x = input("are you hungry").lower
if x == "yes"
print("Well heres some food")
x_selection = 1
elif x == "no"
print("Alright then")
then I want to make a confirmation question using x (our input question) but I don't the output of x but x's original question.
I attempted this
while x_confirmation == 0:
x_confirm = input("Are you sure this is right?").lower
if x_confirm == "yes":
print("yay")
x_confirmation = 1
elif x_confirm == "no":
print("nay")
x_selection = 0
print(x)
I want x as the question not as the answer and repeat the sequence of while confirmation x_selection == 0. Any Tips will help me. (my problem is that i want x as the question not x as the output). Expected Output: "Are you hungry" (and I can say again if I'm hungry or not if I said no the x_confirm question) But my Acutal Output was either Yes or No, the answer from first and only time i had run the code (sorry if i'm horribly explaining this, i'm new-ish to coding and I don't know what to write and not write)
At the top of the first loop, you have this loop condition:
while x_selection = 0:
I think you mean to use the equality comparison operator == here, rather than the assignment operator =.
Because of this typo, Python makes the assignment by setting x_selection to 0, instead of using it as a loop control variable as you intended.
So fixing the operator to == should solve that.
I've tried to make a program that randomizes meals and outputs a random dish. The only problem is, when it first asks you if you want a dish it returns a dish no matter what the response it. Any help appreciated.
print('Random Dinner Dish?')
response = input()
while True:
if response == 'Yes' or 'yes' or 'Y' or 'y':
print(dinner[random.randint(0,len(dinner) - 1)])
break
else:
print('Goodbye')
break
I'm expecting it to print Goodbye and stop the program if some form of yes isn't used.
The result of response == 'Yes' or 'yes' or 'Y' or 'y' is always truthy, so the else-block is unreachable.
You probably meant
if response in {'Yes', 'yes', 'Y', 'y'}:
or will return its left side if it is truthy, otherwise it returns its right.
So False or 'yes' returns 'yes'.
I have the following function which basically asks user to enter the choice for "X" or "O". I used the while loop to keep asking user until I get the answer that's either "X" or "O".
def player_input():
choice = ''
while choice != "X" and choice != "O":
choice = input("Player 1, choose X or O: ")
pl1 = choice
if pl1 == "X":
pl2 = "O"
else:
pl2 = "X"
return (pl1, pl2)
The above code works fine but I quite don't understand how that 'and' works in this particular scenario. If I understand it right, 'and' means both conditions have to be true. However, choice can only be either "X" or "O" at any given time.
Please help me understand this. Apologies in advance if you think this is a dumb question. I am new to python and programming in general.
Thank you!
In this case the choice starts off as blank before entering the while loop. During the while loop, the player is asked to choose X or O. The condition enforces the user to input either X or O. If the user types Z, then the condition is true and repeats the loop asking for another input. If the user types X or O, the condition now returns false and the while loop is exited.
In English the condition says "your choice is not X and your choice is not O", in other words "your choice is neither X nor O". It's part of a while, so basically it's saying it will loop until you don't give it something that's neither X nor O. In other words it will only stop looping when you give it an X or an O.
Indeed, it works, but is also difficult to understand. Others have already explained how it works, but I'd like to propose another version of the function which does the same thing but is shorter and more easily understandable:
def player_input():
choice = ''
while choice not in ["X" ,"O"]:
choice = input("Player 1, choose X or O: ")
return choice
choice = player_input()
The 'and' connects the two checks on the variable 'choice'. If both are true, it will repeat, if one is false, it will drop out of the 'while'. If you put brackets around it maybe it's a bit more clear.
while (choice is not 'X') and (choice is not 'O'):
First you check if choice is not 'X', if that is true, check if choice is not 'O', if that is also true, you have 'true' and 'true', which is 'true'.
If choice is either 'X' or 'O' you get either 'false' and 'true' or 'true' and 'false', which is 'false'.
In general, for any 'and' to be true, both sides of the 'and' have to be true.
For 'or' only one of the sides has to be 'true' to evaluate to 'true'.
I think what's really confusing you is that you don't believe
not x and not b == not (x or b)
not x or not b == not (x and b)
however I can assure you this is the case. In fact, here's a whole wikipedia page on demorgans theorem (which states the above) proving that is is.
I'm writing an Interactive Fiction game for a school project, and for some reason, when I try to use an if/else statement with input (or raw_input), the if else statement defers to the wrong branch regardless of what I input. Here is the code in question:
print( """
You enter the room to the south.
Upon entering you mark that it is pitch black,
and if you were in the famous text adventure Zork,
you would be likely to be eaten by a grue. Thank
the programmer for small favors. Unlike in that game,
you have a candle, a single stick of 100-year-old
dynamite, and that matchbook from earlier.
You just knew that would be useful! The candle and
the dynamite have the same shape, size, and weight.""")
choice1 = True
while choice1 == True:
choice2 = input("Will you strike a match? ")
if choice2 == "Yes" or "yes" or "y":
print("""
It flickers for a second. You can kind of make
out which is which, but alas! They are both
covered in red paper! You are beginning to sweat
from the nervousness.""")
choice1 = False
elif choice2 == "No" or "no" or "n":
print("""
Okay. I can wait, you aren’t leaving this room until
you light a match. You will eventually light a match,
but I can wait until you do.""")
choice1 = True
else: choice1 = True
The if/else statement is treating anything that I type as though I typed yes. Can anyone help me with this error?
Your if statements are wrong, they should look like this:
if choice in ["Yes", "yes", "y"]:
…
or like this:
if choice == "Yes" or choice == "yes" or choice == "y":
…
Python treats an non-empty string as true, e.g. "Yes" is considered true. So if you write choice == "yes" or "Yes", the expression is always true because if even if choice == "yes" isn't true, "Yes" will be considered true.
I believe your problem is in the if statements' conditionals, such as if choice2 == "Yes" or "yes" or "y". This looks like it would check whether choice2 is "Yes" or choice2 is "yes" or choice2 is "y", but it doesn't. The problem is the or statement. The if statement in your code could be written as if (choice2 == "Yes") or ("yes") or ("y") and have the same meaning. This makes it easier to see that, even if choice2 does not equal Yes, the expression will be true because the string "yes" is non-empty and as thus is converted to True in an if statement. This is because the or operator in python is a boolean OR, so if either side of the operator, converted to a boolean, is true, then the expression is. The easiest (i.e. least code refactoring) way to fix this is a series of =='s:
if choice2 == "Yes" or choice2 == "yes" or choice2 == "y": #...
There are others, but this should do the trick for a simple-is program like yours. If you need to do more and more complex matching, you should look into string operators. FOr example, your expression could be rewritten as if "yes".startswith(choice2.lower()): #..., but don't use this without understanding it. For a program of the size of yours, the chained =='s will do just fine. Hope this helps!
The line if choice2 == "Yes" or "yes" or "y" doesn't work like you think it does. After the first statement choice2 == "Yes" it is like asking if "yes" or if "y". The if statement on a string will always return true, unless it is an empty string. To fix this you'll need either
if choice2 == "Yes" or choice2 == "yes" or choice2 == "y":
or this more pythonic approach:
if choice2 in ["Yes", "yes", "y"]:
which will check if the string is in that array.
Of course the same thing applies to elif choice2 == "No" or "no" or "n":, which in its current form will also always return true.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
The if/else statement inside of this loop will not work. If I enter "no" it still continues the loop. I don't understand why, any help would be appreciated.
while keepPlaying == True:
play = input(str('Would you like to play rock, paper, scissors? Yes or no?\n'))
if play == str('yes') or str('Yes'):
playerChoice = input(str('Ok! what\'s your choice?\n'))
else:
keepPlaying = False
print ('Thanks for playing.')
I've put the code through a visualizer and even if the variable play != yes or Yes it still chooses the == to path.
The problem is this:
if play == str('yes') or str('Yes'):
It is equivalent to:
if (play == str('yes')) or str('Yes'):
Note that str('Yes') is always truthy (and with an or means you'll never get the false part).
You want:
if play in ('yes', 'Yes'):
Or maybe (just a tip):
if play.lower() == 'yes':
Change the if condition to play in ('Yes', 'yes', 'y', 'Y')
The issue is, the second part of the or clause (str('Yes')) always evaluates to true.