This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 7 years ago.
This is a piece of code I was trying to make one day:
proceed = 0
print """Welcome to Magyck and Monsters
A text-based RPG"""
charactor_name = raw_input("What is your name? ")
print "Welcome ", charactor_name
while proceed == 0:
gender_answer = raw_input("Are you male or female? ")
if gender_answer == "male" or "MALE" or "mALE" or "Male":
charactor_gender = "male"
proceed = 1
elif gender_answer == "Female" or "FEMALE" or "female" or "fEMALE":
charactor_gender = "female"
proceed = 1
else:
print "Sorry, I could not understand you."
proceed = 0
if proceed == 1:
print "You are a ", + charactor_gender
It was supposed to be a text-based RPG game, the problem is, when i run it, no matter what I enter for the gender, I get get the printed message "You are a male" as if it overrided the first if statement and somehow made it true. The way it is supposed to work is that during a loop you would be asked a question, then check if the answer really made any sense and assign it a specific value that would not change. if the answer did not make any sense, it was supposed to say "Sorry, I could not understand you." and loop back to the question. I am fairly new to coding and would appreciate any input.
The line if gender_answer == "male" or "MALE" or "mALE" or "Male": will always be true.
What you are checking is if gender_answer equals "male" or if one of the other options are true where the other options are tested for their truthiness. As any non-empty string is True, the condition becomes gender_answer == "male" or True which will always be true.
Use if gender_answer in ("male", "Male", "MALE", "mALE"): instead or better yet if gender_answer.lower() == "male":.
You need to make a complete condition.
if gender_answer == "male" or gender_answer=="MALE" or gender_answer=="mALE" or gender_answer=="Male":
Same solution for the elif.
Because "male" (or any string) is considered to be true, you go into the if. You need to compare it every times.
Related
I am writing Python code for the game Tic Tac Toe, however I have stumbled upon a hurdle already and can't seem to break out of a While loop:
print("Welcome to Tic Toe!")
Player1_Tag=input("Player 1: Choose between X and 0: ")
while Player1_Tag != "X" or Player1_Tag != "0":
print("Invalid input")
Player1_Tag=input("Player 1: Choose between X and 0: ")
else:
if Player1_Tag=="X":
Player2_Tag="0"
else:
Player2_Tag="X"
When I run this the program, it asks if I want to be "X" or "0" - if i choose '#' for example I get "Invalid input" and it asks me again in which case I choose "X" but it again gives me "Invalid input" and asks me again.. which is of course not what I want. I am confused as I don't understand why the loop keeps going even though I choose a valid input?
I have tried putting a "break" in the while loop but the loop breaks out if I choose an invalid input twice consecutively.. which is not what I want, I want it to ask me again for the third time, fourth time until I get it right.
Player1_Tag != "X" or Player1_Tag != "0" will always be true.
Consider 3 possibilities:
If Player1_Tag == "X", then Player1_Tag != "0"
If Player1_Tag == "0", then Player1_Tag != "X"
If Player1_Tag is anything else, it is neither "X" nor "0".
A clearer way to write this would be while Player1_Tag not in ("X","0"):
Your issue is caused by a logic error in the condition you're testing in your loop. You're currently testing Player1_Tag != "X" or Player1_Tag != "0", which is always True, regardless of what Player1_Tag is. If the variable is equal to one of the strings, it will be not-equal to the other. Since you're joining the two comparisons with or, you'll never exit the loop.
You need to either join the pieces of your test with and instead of or (Player1_Tag != "X" and Player1_Tag != "0"), or negate the comparisons (by changing != to ==) and do a negation of the whole expression: not (Player1_Tag == "X" or Player1_Tag == "0"). By De Morgan's laws, those are equivalent.
The problem is that you've used or when you should have used and
If Player1_Tag is equal to 0 It's at the same time not equal to X
And or checks if either is `True'
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 6 years ago.
I'm trying to make a program that rolls a dice and checks if the user wants to continue every roll, if not, the program should halt. Although, no matter what you input, the program breaks out of the loop. Can someone explain why and give me some tips to making a program that is simpler and works? Thanks
import random
sideNumber = int(input("Enter the number of sides in the die: "))
print("Dice numbers: ")
while True:
print(random.randint(0, sideNumber))
print("Do you want to continue?")
response = input()
if response == "n" or "no":
break
That's because the statement "no" is still true.
You should do :
if response == "n" or response == "no":
or better :
if response in ["n", "no"] :
if response == "n" or "no":
makes your code fail. This checks if the boolean value of "no" is true, and it always is. replace it with:
if response == "n" or response == "no":
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.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
I've just started using python and have got stuck on something that, in my mind, clearly should work. This is my first code and I just try to have a conversation with the user.
year = input("What year are you in school? ")
yearlikedislike = input("Do you like it at school? ")
if (yearlikedislike == "yes" or "Yes" or "YES" or "yep" or "yup" or "Yep" or "Yup"):
print("What's so good about year " + year, "? ")
input("")
print("That's good!")
time.sleep(1)
endinput = input("I have to go now. See you later! ")
exit()
if (yearlikedislike == "no" or "No" or "nope" or "Nope" or "NOPE"):
print("What's so bad about year " + year, "?")
input("")
time.sleep(1)
print("Well that's not very good at all")
time.sleep(1)
endinput = input("I have to go now. See you later! ")
time.sleep(1)
exit()
My problem is that even if I reply with a negative answer it will still reply with a response as if I have said yes and if I switch the 2 around (so the code for the negative answer is above the code for the positive answer) it will always reply as if I have given a negative response.
if yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup"):
or
if yearlikedislike.lower() in ("yes","yep","yup"):
will do the trick
This is because Python is evaluating the "truthiness" of "Yes".
Your first if statement is interpreted like this:
if the variable "yearlikedislike" equals "yes" or the string literal "Yes" is True (or "truthy"), do something
You need to compare against yearlikedislike each time.
Try it like this:
if yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup"):
#do something
if (yearlikedislike == "yes" or "Yes" or "YES" or "yep" or "yup" or "Yep" or "Yup"):
Strings evaluate to True. I know you think you're saying that if yearlikedislike is equal to any of those things, keep going. However, what you're actually saying is:
if yearlikedislike equals "yes", or if "Yes" exists (which it does), or "YES" exists, etc:
What you want is either:
if (yearlikedislike == "yes" or yearlikedislike == "Yes" or yearlikedislike == "YES")
or better:
yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup")
It is because the condition is interpreted as :
if(yearlikedislike == "yes" or "Yes" == True or "YES" == True #...
try
if(yearlikedislike == "yes" or yearlikedislike == "Yes" or yearlikedislike == "YES"#...
or a more concise way :
if(yearlikedislike in ("yes", "Yes", "YES", #...
even more concise way :
if(yearlikedislike.lower() in ("yes", "yup", #...
A String (here "Yes") converted to a boolean is converted to True if it's not empty
>>> bool("")
False
>>> bool("0")
True
>>> bool("No")
True
Each part after or is independant from the previous.
Also consider using else or elif instead of two related if. And try to lower character before testing them so you need less test.
I was wondering if somebody could tell me what is wrong with this code, when I run the code it shows nothing but if I take out the "elif" it does work.\
first=input("What is your first name? ");
middle=input("What is your middle name? ");
last=input("What is your last name? ");
test = [first, middle, last];
print ("");
print ("Firstname: " + test[0]);
print ("Middlename: " + test[1]);
print ("Lastname: " + test[2]);
print ("");
correct=input("This is the information you input, correct? ");
if (correct == "Yes" or "yes"):
print ("Good!")
elif (correct == "no" or "No"):
print ("Sorry about that there must be some error!");
Here's the problem:
if (correct == "Yes" or "yes"):
# ...
elif (correct == "no" or "No"):
# ...
It should be:
if correct in ("Yes", "yes"):
# ...
elif correct in ("No", "no"):
# ...
Notice that the right way to make a comparison involving several conditions is like this:
correct == "Yes" or correct == "yes"
But usually it gets written like this, which is shorter:
correct in ("Yes", "yes")
You need to use the in keyword:
if correct in ("Yes", "yes"):
print ("Good!")
elif correct in ("no", "No"):
print ("Sorry about that there must be some error!")
or convert the entire input to the same case:
# I use the lower method of a string here to make the input all lowercase
correct=input("This is the information you input, correct? ").lower()
if correct == "yes":
print ("Good!")
elif correct == "no":
print ("Sorry about that there must be some error!")
Personally, I think the lower solution is the cleanest and best. Note however that it will make your script accept inputs such as "YeS", "yEs", etc. If this is a problem, go with the first solution.
You'e checking correct incorrectly
if (correct == "Yes" or "yes"):
means (correct == "Yes") or ("yes"), and non-empty string evaluates to True in python, so first condition will always be True.If you want to check multiple strings, you can do:
if (correct in ("Yes", "yes")):
But this one doesn't takes 'yEs' or 'yES' into account. If you want case-insensitive comparison, then I think correct.lower() == "yes" would be preferred method.