This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
I am a novice coder who's just started coding about 4-5 weeks ago. The best I have achieved is a basic Python username and password login page for a 'top secret' website (the website is fake). However, just to refresh my memory of basic coding (I've been doing some un-related things lately), I tried making a basic childrens game to do with the alphabet. Here's my current code:
name = input("What's Your Name?: ")
print("Welcome" , name , "to the 3 lucky guess alphabet skills builder!")
print("Let's get started:")
C = input("What Is The 3rd Letter of The Alphabet: ")
if C == 'C' or 'c':
print("Congraulations!")
else:
print("Think We Should Retry That!")
C
if C == 'C' or 'c':
print("That's Better!")
Z = input("What Is The Last Letter of The Alphabet: ")
if Z == 'Z' or 'z':
print("You're Really Good At This! One More!")
else:
print("Have Another Go!")
Z
if Z == 'Z' or 'z':
print("That's More Like It! Last One!")
J = input("What Is The 10th Letter Of The Alphabet: ")
if J == 'J' or 'j':
print("Great! How Many Did You Get In Total?")
else:
print("Unlucky, Better Luck Next Time!")
total = input("How Many Did You Get In Total?: " , print("Out Of 3!")
print("Wow! You Got" , total , "! Well Done" , name , "!!!")
exit
Why aren't any of the 'else' arguments working?
Also, why won't the second to last bit of code work - it just states a syntax error!
I have tried indenting all the else statements but that results in a syntax error too!
Please help! :)
The if statement you wrote, like the following
if C == 'C' or 'c':
doesn't do what you mean. The expression after or just checks whether 'c' evaluates to true, which it always will. That's why the code after else: won't execute.
You have to write it like this:
if C == 'C' or C == 'c':
It's difficult to know what you mean by "not working" - you should be more specific about the error you're seeing. Are you referring to this?
else:
print("Have Another Go!")
Z
if Z == 'Z' or 'z':
print("That's More Like It! Last One!")
The second line of the body simply evaluates the variable Z - it doesn't change anything. Therefore, the conditional following it still returns the same result as the last time you evaluated it.
Also, as the other answer points out,
if a = "foo" or "bar"
will always be True, because "bar" is a non-false value, and an or with any non-false value is True.
Related
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()")
Im writing code with a part that is confusing me.
while answer1 != 'a':
if answer1 == 'b':
print('\nWrong answer.\n')
answer1= input("\nEnter again.\nYou only have one more try!\n")
amount = amount+1
print(amount)#for testing
if amount == 1:
print("\nTry next question")
break
What I want to do is to have the tries to be two if the user said 'b' twice. I have put amount as 1 but if the user says a, then it will be two. What I want to do is to have the tries to two if 'b' is said twice but one if 'a' is said once.
So, the overall goal here is unclear. However, I think this may help you out:
First of all, drop the while answer != 'a', and go to while True, rely on the conditional inside the loop to handle break / continue.
amount = 1 # Initiate amount outside of the loop, otherwise it'll get reset on each loop.
while True: # Run until base condition is met.
print("I am the question")
ANSWER = input("Answer: ")
if ANSWER == 'a' or amount >= 2: # Base condition.
print(amount)
break
else: # This runs if answer isn't what you want.
print("Wrong, please try again.")
amount += 1
continue
Best
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.
def choosing_room():
print "Welcome! You now must choose!"
answer = raw_input("Type a or b and hit Enter")
if answer == 'a' or 'A':
print "You chose 'a'!"
elif answer == 'b' or 'B':
print "You chose 'b'!"
else:
print "That is incorrect, please try again"
choosing_room()
choosing_room()
This is my code. It's very simple, but for some reason it keeps returning and error message of reference error: 'prompt' is undefined
This is probably not going to solve the problem you are having (although the code worked for me in an iPython shell), there is an issue with your if/else statements. The following statement:
if answer == 'a' or 'A':
print "You chose 'a'!"
will always print "You chose 'a'!" regardless of the letter you enter upon prompting. In python, the or expression you are using asks the following question: Is the answer given equal to 'a' OR is the boolean value of "A" True? What you mean to ask is: Is the answer given equal to 'a' OR is the answer given equal to "A"? This is most concisely represented through:
if answer.lower() == 'a':
print "You chose 'a'!"
That should solve at least one problem that this code is having.
As #Bhargav Rao commented, your code does not match your error, when you run it you will get an output of a regardless of what you enter.
This is because if answer == 'a' or 'A': is the same as saying:
if answer == 'a': OR if 'A': <-- this is always true
To fix this you can use the condition in:
def choosing_room():
print "Welcome! You now must choose!"
answer = raw_input("Type a or b and hit Enter: ")
if answer in ['a','A']:
print "You chose 'a'!"
elif answer in ['b','B']:
print "You chose 'b'!"
else:
print "That is incorrect, please try again"
choosing_room()
choosing_room()
I have created a Python program that guesses the number programmer thinks in mind. Everything is working file but i don't know how to use guess in print statement in a way that print statement display number as well. I tried adding word "guess" but it is not working. I am C programmer and working with Python for the first time, so i am unable to figure it out.
hi = 100
lo = 0
guessed = False
print ("Please think of a number between 0 and 100!")
while not guessed:
guess = (hi + lo)/2
print ("Is your secret number " + //Here i need to Display the guessed Number + "?")
user_inp = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too"
"low. Enter 'c' to indicate I guessed correctly: ")
if user_inp == 'c':
guessed = True
elif user_inp == 'h':
hi = guess
elif user_inp == 'l':
lo = guess
else:
print ("Sorry, I did not understand your input.")
print ("Game over. Your secret number was: " + //Here i need to display final number saved in guess.)
Just convert it to string.
print ("Game over. Your secret number was: " + str(guess))
You could also use string formatting.
print("Game over. Your secret number was {}".format(guess))
Or, since you come from a C background, old style string formatting.
print("Game over. Your secret number was %d." % guess)
Try this in your print statement and let me know if it works.
str(guess)
Python has very nice string formatting, which comes in handy when you need to insert multiple variables:
message = "Game over after {n} guesses. Your number was {g} (pooh... got it in {n} times)".format(g=guess, n=number)
print(message)