Can you only have one string after != - python

I'm just writing some small code and I'm not able to make this work, I am only able to have one string which is e.g boy or girl but I would like to have both, do I have to make a separate elif statement or can I somehow put girl in there as well
gender = input("Are you a boy or a girl? : ")
if (gender != "boy"):
print("Get out of here you mutant")
exit()

You would need to have 3 conditions:
if gender == 'boy':
print ('You are a boy')
elif gender == 'girl':
print ('You are a girl')
else:
print("Get out of here you mutant")
Or you can do like that:
if gender in ('boy', 'girl'):
print('You are a {}'.format(gender)
else:
print("Get out of here you mutant")
In the second script you check if gender is a girl or a boy and if so it puts gender variable in the print output string.

Related

Python IF statement chain error, can I use non-boolean's in this way?

Python newbie here, unsure if this is the correct method but i'm having issues when trying to get the following to run:
from Meal_Options import usual_meals, healthy_meals, hot_meals, other_meals, lunch_meals, fast_food_meals
print("Hello! Lets decide what you want for lunch! Please answer the first question.")
lunch_tea = input("Is it lunch, or tea? ").lower()
if lunch_tea == "lunch":
print(*lunch_meals, sep="\n")
elif lunch_tea == "tea":
healthy = input("Healthy or not healthy? ").lower()
if healthy == "healthy":
food_type = input("Do you want spicy or not spicy? ").lower
if food_type == "not spicy":
print(*healthy_meals, sep="\n")
print(*usual_meals, sep="\n")
print(*other_meals, sep="\n")
elif food_type == "spicy":
print(*hot_meals, sep="\n")
elif healthy == "not healthy" or "unhealthy":
pizza_chinese_indian = input("Do you want pizza, chinese or indian? ").lower
if pizza_chinese_indian == "pizza":
print(*fast_food_meals)
elif pizza_chinese_indian == "chinese":
print(*fast_food_meals)
elif pizza_chinese_indian == "indian":
print("Ok, Korma it is")
elif lunch_tea != "tea" or "lunch":
print("\n" "Invalid input, please enter 'Tea' or 'Lunch'")
finished = input("Are you happy with your selection? ").lower
Output:
Hello! Lets decide what you want for lunch! Please answer the first question.
Is it lunch, or tea? tea
Healthy or not healthy? not healthy
Do you want pizza, chinese or indian? chinese
Are you happy with your selection? no
Why does the code not print anything when answering "pizza", "chinese" or "indian" and just moves onto "Are you happy with your selection?"
Your second argument or "lunch" will always evaluate to True since it's a string of a non-zero length.
Should be
elif lunch_tea != "tea" or lunch_tea != "lunch":
or, even better:
elif lunch_tea not in ("tea", "lunch"):
I believe the main issue here is that you are forgetting to add the () after the str.lower method.
from Meal_Options import usual_meals, healthy_meals, hot_meals, other_meals, lunch_meals, fast_food_meals
...
if lunch_tea == "lunch":
print(*lunch_meals, sep="\n")
elif lunch_tea == "tea":
...
if healthy == "healthy":
food_type = input("Do you want spicy or not spicy? ").lower()
...
elif healthy == "not healthy" or "unhealthy":
pizza_chinese_indian = input("Do you want pizza, chinese or indian? ").lower()
...
...
finished = input("Are you happy with your selection? ").lower()
I've copied only the relevant code in order to highlight exactly where the issues are.
you probably want in or to have something like
if healthy == "not healthy" or healthy == "unhealthy"
The problem is that you're forming a structure like
if healthy == "not healthy" or "unhealthy"
if (var == test) or (True):

an if Statement inside an if Statement?

FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround==("Yes") or FarmGround==("yes"): #this is if
print("You patted the animal") #print statement if you patted the animal it will go onto the next if statement
if print=("You patted the animal"):
elif FarmGround==("No") or FarmGround==("no"): #this is elif
print("You didn't patt the animal and it is triggered")
undescribed image
Your code is quite clear. What I understand is you want to ask another question if animal is patted.
FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround=="Yes" or FarmGround=="yes": #this is if
print("You patted the animal")
holy_field = input("Did you clear the field?")
if holy_field.lower() == "yes":
print("Do something else. Don't look at me.")
else:
print("When are you going to do it ?")
elif FarmGround== "No" or FarmGround== "no": #this is elif
print("You didn't patt the animal and it is triggered")
You can indent additional statements, including if statements inside your existing if block, just like you're indented the first print statement. It's not clear from your question what exactly you want to do, so I'll fill in some pseudo-code (which you can replace with whatever you actually want):
FarmGround=input("Do you want to pat the animal? ")
if FarmGround==("Yes") or FarmGround==("yes"):
print("You patted the animal")
some_other_answer = input("Some other question?") # here's more code inside the first if
if some_other_answer == "Foo": # it can include another if statement, if you want it to
print("Foo!")
elif FarmGround==("No") or FarmGround==("no"):
print("You didn't patt the animal and it is triggered")
Indentation matters in python. To nest an if statement in another if statement, just indent it below the first with 4 spaces.
If ( var1 == 1 ):
If ( var2 == 2 ):
print "Both statements are true."

If string statement: What am I missing? [duplicate]

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 7 years ago.
I've created a simple code which looks like this:
name = str(input ("What is your name?"))
gender = str(input ("What is your gender?"))
if gender == 'male' or 'Male':
print ("Hello Mr %s" % (name))
elif gender == 'female' or 'Female':
print ("Hello Mrs %s" % (name))
else:
print ('Invalid gender. Please try again.')
However, no matter what gender I type (even random words like test), it always prints out the if statement, which means it satisfy the gender == male portion. Like if I key in female, the if statements still prints out. What am I missing here?
In steps
Use the right variable name first:
gender = input("What is your gender?")
Second, the use of or is wrong:
>>> 'male' or 'Male'
'male'
Use:
if gender == 'male' or gender == 'Male':
Alternatively use:
if gender.lower() == 'male':
Whole program
name = input("What is your name?")
gender = input("What is your gender?")
if gender.lower() == 'male':
print("Your are %s" % (gender))
elif gender.lower() == 'female':
print("Your are %s" % (gender))
else:
print('Invalid gender. Please try again.')
Shorter version
name = input("What is your name?")
gender = input("What is your gender?")
if gender.lower() in ('male', 'female'):
print("Your are %s" % (gender.lower()))
else:
print('Invalid gender. Please try again.')
When comparing to more than one string, you need to do it differently:
if gender == 'male' or gender == 'Male':
Or, more simply:
if gender in ['male', 'Male']:
Or with a set:
if gender in {'male', 'Male'}:
Not much difference in speed with only two items, but with a lot of
items a set will be faster because it uses a hash table, while the list
uses linear search.
Now, as for what is happening with your code. If you do this:
if gender == 'male' or 'Male':
you are saying:
if (gender == 'male') or ('Male'):
So, no matter what gender is, if the first comparison is False, it
will just go on to 'Male'. That is a non-empty string, so it’s always
True and the conditional always ends up True as well.

How can I restart my python 3 script?

I am making a program on python 3. I have a place that I need the script to restart. How can I do this.
#where i want to restart it
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
print("Press any key to exit")
input()
It's a general question about programming an not specific to Python ... by the way you can shorten your code with the two conditions on boy and girl...
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy" or gender == "girl":
print("Lets get on with the story.")
break
print("Sorry. You cant have that. Type boy or girl.")
print("Press any key to exit")
input()
Simple but bad solution but you get the idea. I am sure, you can do better.
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
restart = input("Would you like to restart the application?")
if restart != "Y":
print("Press any key to exit")
input()
break
Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:
phrase = "hello, world"
while (input("Guess the phrase: ") != phrase):
print("Incorrect.") //Evaluate the input here
print("Correct") // If the user is successful
This outputs the following, with my user input shown as well:
Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct
or you can have two separate function written over, It's same as above(only it's written as two separate function ) :
def game(phrase_to_guess):
return input("Guess the phrase: ") == phrase_to_guess
def main():
phrase = "hello, world"
while (not(game(phrase))):
print("Incorrect.")
print("Correct")
main()
Hope this is what you are looking for .

Program keeps looping without calling function

I am writing a program that asks two users boy or girl names and whether they like them or not. This is the beginning of the program and I created a function so if they don't input boy or girl, it asks them again so the program can properly run.
user_name_class= BabyNames()
print "Let's get started!"
print "Who will user1 be and who will user2 be?"
name_user1 = raw_input("User1 = ")
name_user2 = raw_input("User2 = ")
print user_name_class.baby_namer(raw_input("Do you want boy or girl names? \n").lower())
class BabyNames():
def baby_namer(self, gender):
self.gender = gender
if 'b' not in gender or 'g' not in gender:
return self.start_wrong_input()
elif 'b' in gender:
test = raw_input("What round are you on? (1-{}) \n".format(str(len(boy_rounds))))
return boy(boy_rounds[test])
elif 'g' in gender:
test = raw_input("What round are you on? (1-{}) \n".format(str(len(girl_rounds))))
return girl(girl_rounds[test])
else:
pass
def start_wrong_input(self):
x = BabyNames()
print "You need to put boy or girl to move on!"
re_try = raw_input("Do you want boy or girl names? \n").lower()
if 'g' in re_try:
return x.baby_namer('girl')
elif 'b' in re_try:
return x.baby_namer('boy')
else:
print "You need to put boy or girl to move on!"
I know creating the class probably wasn't necessary, but I just learned about them so I tried incorporating them into my code.
What is happening is at "Do you want boy or girl?" if you input anything else besides that, it properly calls the function and re-asks it but then when you put boy or girl, it loops and continues to asks the question without breaking. Why is this happening and let me know if I need to elaborate on anything else!(ps I'm a beginner so it may not be pythonic, but I'm working on it!)
Use if 'b' not in gender and 'g' not in gender, using or always puts you back to the start_wrong_input method because if gender is girl b is not in girl and if gender is boy g is not in boy so if 'b' not in gender or 'g' not in gender: will always evaluate to True
class BabyNames():
def baby_namer(self, gender):
if 'b' not in gender and 'g' not in gender:
return self.start_wrong_input()
elif 'b' in gender:
test = raw_input("What round are you on? (1-{}) \n".format(str(len(boy_rounds))))
return boy(boy_rounds[test])
elif 'g' in gender:
test = raw_input("What round are you on? (1-{}) \n".format(str(len(girl_rounds))))
return girl(girl_rounds[test])
else:
pass
def start_wrong_input(self):
print "You need to put boy or girl to move on!"
re_try = raw_input("Do you want boy or girl names? \n").lower()
if 'g' in re_try:
return self.baby_namer('girl') # use self.baby_namer, you don't need to use x = BabyNames()
elif 'b' in re_try:
return self.baby_namer('boy')
else:
print "You need to put boy or girl to move on!"
The error in your code is in baby_namer:
if 'b' not in gender or 'g' not in gender:
You probably want a 'and' there, you fail if it is not a boy or if it is not a girl. You could try with entering the 'boyg' value...
Apart from that, you should not use recursive calls to make loops, it's difficult to read ! Use a proper while loop.
You've create something that's called mutual recursion functions
function: baby_namer() calls start_wrong_input() and then start_wrong_input() calls back in return to start_wrong_input(). And you got yourself an infinite loop.

Categories