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.
Related
This question already has answers here:
How do I do a case-insensitive string comparison?
(15 answers)
Closed 6 days ago.
I am trying to create a small bit of code in Python that runs a conversation, then asks a Y/N question i.e "Do you believe the sky is blue?"
When I run the code, it works well until I reach the question. It ignores my parameters for Y/N answers to print specific responses. It gives me the print response attached to my "else" statement.
I am confused if I am writing my If/elif/else statements wrong?
My code is written as follows:
x = input('do you believe the sky is blue')
if x == "yes":
print("I believe you are correct")
elif x == "no":
print('I think you have a unique perspective.')
else:
print('Please answer Yes or No.)
You use .lower() to obtain a lower case version of a string, and you are missing a ' in the last print():
x = input('do you believe the sky is blue ').lower()
if x == "yes":
print("I believe you are correct")
elif x == "no":
print('I think you have a unique perspective.')
else:
print('Please answer Yes or No.')
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
questionnumber=0
color=("Red")
userask=input("What color of the rainbow am I thinking of? ")
color = userask
if color == "Red":
print("CORRECT")
else:
print("INCORRECT")
questionnumber = questionnumber+1
#print(questionnumber)
while color != "Red":
userask=input("What color of the rainbow am I thinking of? ")
color = userask
if color == "Red":
print("CORRECT")
else:
print("INCORRECT")
questionnumber = questionnumber+1
#print (questionnumber)
if questionnumber>3:
quitter=input("Do you want to quit? ")
if quitter == "yes"or"Yes":
break
else:
continue
So the idea is you have to guess the correct color which in this case is red. But after three attempts, the program asks the user if they want to quit; if yes, the while loop stops, and if no, the while loop continues for another three attempts. I can't seem to figure out why the loop ends regardless of the user's answer.
Your problem is that:
if quitter == "yes"or"Yes"
is based on a misunderstanding of Python logic statements.
It is not interpreted as if quitter == ("yes"or"Yes") as you intended, but it is actually interpreted as:
if (quitter == "yes") or ("Yes")
Any non-blank string evaluates to True, so the break is always executed.
A better way of writing this would be:
if quitter.lower() == "yes":
This converts the contents of quitter to lower case and checks that, so you don't need to check upper and lower case, and other variants like "YES".
Please change this statement to as below :
if ((quitter == "yes") or (quitter == "Yes")):
After prompting the user if they want to quit, change the if statement to
if quitter == "yes" or quitter == "Yes":
break
else:
continue
The reason the program exits is because it's evaluating the string 'Yes' on it's own as True which means the or statement evaluates as True and thus break is ran. You have to specify quitter both before and after the or statement.
truth_val = bool('Yes')
print(truth_val)
>>>True
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 3 years ago.
I am currently working on a blackjack game without graphics or pygame I can not seem to make an if statement with input, I took a month off of python and can't really understand the questions already answered.
Here is my code so far:
def pullCard():
print(f"You pulled a {r} of {s} the value is {v}")
print(f"The dealer pulled a {dr} of {ds} the value is {dv}")
pullCard()
Answer = input('Do you want to Hit or Stand?')
if Answer == 'Stand' or 'stand':
dealerOnly()
if Answer == 'Hit' or 'hit':
pullCard()
I have not defined dealerOnly() every time i say Hit or Stand it just comes out with the error.
Do you want to Hit or Stand?Hit
Do you want to Hit or Stand?
Traceback (most recent call last):
File "C:\Users\Brody Critchlow\Downloads\Blackjack\Blackjack.py", line 36, in <module>
dealerOnly()
NameError: name 'dealerOnly' is not defined
Even though i said Hit not Stand
your if statement is incorrect it should be
if Answer == 'Stand' or Answer == 'stand':
A cleaner approach is to make the user input string all lower case, that way you only need to check one scenario.
def pullCard():
print(f"You pulled a {r} of {s} the value is {v}")
print(f"The dealer pulled a {dr} of {ds} the value is {dv}")
pullCard()
Answer = str(input('Do you want to Hit or Stand?')).lower()
if Answer == 'stand':
dealerOnly()
elif Answer == 'hit':
pullCard()
I also used an elif statement to make it more efficient so that if the first statement is true, then it won't run the second.
You have to understand that python uses truthy and falsey values, it means, that not only True and False are true and false, also strings and lists and other values, examples:
if "":
print("wont enter, falsay value")
if("Hit"):
print("Something, truthy value")
if []:
print("wont enter, falsay value")
if [1,2,3]:
print("Something, truthy value")
your main problem, is in this two expressions:
if Answer == 'Stand' or 'stand':
if Answer == 'Hit' or 'hit':
here, you use an or, it means that if anything is truthy, the block inside the if will be executed, and 'stand' and 'hit' are not an empty str, so it will always be executed because they are both True
Also, the other problem is that you have to make the two questions, Answer == "Stand" or Answer == "stand", as I don't have the methods, I will print something just to you can see what is called:
def pullCard():
print("You pulled a {r} of {s} the value is {v}")
print("The dealer pulled a {dr} of {ds} the value is {dv}")
pullCard()
Answer = input('Do you want to Hit or Stand?')
if Answer == 'Stand' or Answer == 'stand':
print("dealerOnly()")
if Answer == 'Hit' or Answer == 'hit':
print("pullCard()")
you can also simplify the if like this:
Answer = input('Do you want to Hit or Stand?').lower()
if Answer == 'stand':
print("dealerOnly()")
if Answer == 'hit':
print("pullCard()")
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 years ago.
I'm trying to create a small python program to emulate rolling a single die. My problem arises in that I want the program to accept both upper and lower-case 'Y' to trigger a re-roll. My program works when I accept either upper or lower case y but when I try to change the line
if usr == 'Y'
to
if usr == 'Y' or 'y'
creates a problem where it never enters the else statement, making the program never terminate.
import random
def DiceRoll():
number = random.randrange(1, 7, 1)
print("Dice Roll: ", number)
AskUser()
return
def AskUser():
usr = input("Roll Again? (Y/N) \n")
if usr == 'Y':
DiceRoll()
else :
print("Thank you for playing!")
return
DiceRoll()
You must do
if usr == 'Y' or usr == 'y'.
It is currently evaluating the statement 'y' as its own condition, and in this case 'y' always evaluates to true.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
For some reason my program keeps rolling the dice again regardless of the users answer, and it doesn't print the goodbye message.
I'll include the code below so you can test yourself (Python 3)
from random import randint
def rollthedice():
print("The number you rolled was: "+ str(randint(1,6)))
rollthedice()
shouldwecontinue = input("Do you wish to roll again? (y or n) ").lower()
if shouldwecontinue == "y" or "yes":
rollthedice()
elif shouldwecontinue == "n" or "no":
print("Goodbye.")
elif shouldwecontinue != type(str):
print("Sorry the program only accepts 'y' or 'n' as a response.")
The desired effect of the program should be that if the user enters y, it rolls the dice again, respectively starting the whole program again. Whereas, if the user enters no then it should print the Goodbye message.
or doesn't work like that. Right now your program is evaluating (shouldwecontinue == "y") or "yes", and since Python interprets "yes" as truthy, then that condition always succeeds. The simplest fix is to change it to shouldwecontinue == "y" or shouldwecontinue == "yes". And then similar changes for the other conditional expressions, of course.