How to make an if statement have a output [duplicate] - python

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()")

Related

Create a conversation that has a Y/N answer [duplicate]

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

Why won't the while loop continue and stop after a user question? [duplicate]

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

Why is my program doing this? [duplicate]

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.

If/Then statement not working inside of while loop [duplicate]

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.

My Program is not printing what I want it to print

I have just finished this code , added my final print line and now suddenly when I test it , it doesn't print out what I want it to print.
import random
name=input("Welcome to this Arithmetic quiz,please enter your name:")
score = 0
for i in range(10):
number1=random.randint(20,50)
number2=random.randint(1,20)
oper=random.choice('+-*')
correct_answer = eval(str(number1)+oper+str(number2))
answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer)
if answer == correct_answer:
print('Correct!')
score +=1
else:
print('Incorrect!')
print("You got",score,"out of 10")
When I ever I give the right answer it still gives me Incorrect leading it to tell me that I got 0/10.
To match the symptoms reported I believe that your code is actually:
import random
name=input("Welcome to this Arithmetic quiz,please enter your name:")
score = 0
for i in range(10):
number1=random.randint(20,50)
number2=random.randint(1,20)
oper=random.choice('+-*')
correct_answer = eval(str(number1)+oper+str(number2))
answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer)
if answer == correct_answer:
print('Correct!')
score +=1
else:
print('Incorrect!')
print("You got",score,"out of 10")
Note the indentation of the else statement is aligned with the if, not the for. Given that this line:
answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer
assigns a boolean to the variable answer, not the answer that the user entered. You can do 2 things:
remove the == correct_answer part resulting in:
answer = int(input('What is:'+str(number1)+oper+str(number2)+'='))
or
change the if statement to:
if answer:
Here are the problems with your code:
You are incrementing score regardless of whether the answer is correct or not. Increase the indentation of score += 1 so that it lines up with the print that indicates a correct answer.
The else is bound to the for statement. Indent it so that it is bound to the if statement. Indent the print that follows it accordingly.
Your assignment to answer isn't just picking up the answer, but it's comparing it to the expected answer. So it will be True or False. You are then comparing that boolean value to the answer again, so of course the result if False. Change the assignment to:
answer = int(input('What is:'+str(number1)+oper+str(number2)+'='))
Probably the first two items were just posting errors, and the last one is what's preventing your code from working.

Categories

Resources