Python 'if' statement not triggering correctly [duplicate] - python

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, no matter what user_input is (Yes, No, "", eserw3) the first if statement will always be triggered. Any insight as to why the elif and the else never get activated? (The below code compiles perfectly without any errors)
Thank you in advance.
def retry():
user_input = raw_input("Would you like to face %s again? (Yes/No)" % (Enemy))
if user_input == "Yes" or "yes":
respawn()
getMove()
elif user_input == "No" or "no":
print "Thanks for playing!"
else:
print "Please enter either Yes or No."

def retry():
user_input = raw_input("Would you like to face %s again? (Yes/No)" % (Enemy))
if user_input == "Yes" or user_input == "yes":
respawn()
getMove()
elif user_input == "No" or user_input == "no":
print "Thanks for playing!"
else:
print "Please enter either Yes or No."

def retry():
user_input = raw_input("Would you like to face %s again? (Yes/No)" % (Enemy)).lower()
if user_input == "yes":
respawn()
getMove()
elif user_input == "no":
print "Thanks for playing!"
else:
print "Please enter either Yes or No."

Change your if condition to
user_input in ["Yes", "yes"]
Reason: When you write user_input == "Yes" or "yes", it evaluates as:
(user_input == "Yes") or "yes"
The second part of OR is a True always(non-zero length string). Hence your problem of if block executing always.

Related

Python: Depending on IF statement output, execute different code outside of itself

If my_input == "n" I want to my program to loop again, which works fine.
But if my else statement is True I dont want it to run the whole program again and just "start" at the my_input variable.
How can I achieve this?
def name_user_validation():
while True:
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split()
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
my_input = input("Is that right? (y/n) ")
if (my_input == "y"):
print("Great!")
break
elif my_input == "n":
print("Oh no :(")
else:
print("Invalid input, try again.")
name_user_validation()
I misunderstood your question, I would probably restructure your code a bit, so you get rid of your while loops and use recursive function calling to go back when you need to,
something like the below
def name_user_validation():
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split() # This line actually doesn't do anything
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
if not accept_input():
name_user_validation()
def accept_input():
my_input = input("Is that right? (y/n) ")
if my_input == "y":
print("Great!")
return True
elif my_input == "n":
print("Oh no :(")
return False
else:
print("Invalid input, try again.")
accept_input()
name_user_validation()
Add another loop that doesn't terminate until user enters acceptable input.
def name_user_validation():
while True:
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split()
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
while True:
my_input = input("Is that right? (y/n) ")
if (my_input == "y"):
print("Great!")
break
elif my_input == "n":
print("Oh no :(")
break
else:
print("Invalid input, try again.")
if my_input == 'y':
break
name_user_validation()
Edit: The program terminates only when my_input = y.

my if else statements don't work and command everything [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
ans = input("Enter yes or no: ")
if ans != "Yes" or "yes" or "no" or "No":
print("Can't do that")
if ans == "yes" or "Yes":
print("Great!")
if ans == "no" or "No":
print("Okay, then")
If I type let's say "Okay" it outputs this:
Can't do that!
Great!
Okay, then
instead of "Can't do that". I don't know what's wrong, and I couldn't find questions like this.
do instead something more pythonic:
if ans.lower() in ['no', 'yes']:
and use elif instead of doing another if verification.
Use in:
ans = input("Enter yes or no: ")
if ans in ["Yes", "yes"]:
print("Great!")
elif ans in ["No", "no"]:
print("Okay, then")
else:
print("Can't do that")
Test whether the answer is in a list or a set (using sets in the example below). Otherwise, your first condition evaluates to True. This is because of the operator precedence, Python considers it equivalent to (ans != "Yes") or ("yes") or ("no") or ("No"). And "yes" is True because it is not an empty string (docs), which makes the whole expression evaluate to True as well.
ans = input("Enter yes or no: ")
if ans not in {"Yes", "yes", "no", "No"}:
print("Can't do that")
if ans in {"yes", "Yes"}:
print("Great!")
if ans in {"no" or "No"}:
print("Okay, then")
Better still, make it shorter like so:
ans = input('Enter yes or no: ').lower()
if ans == 'yes':
print('Great!')
elif ans == 'no':
print('Okay, then')
else:
print("Can't do that")
That's not the way to use logical operators in a programming language, it should be:
if (ans != "Yes") or (ans != "yes") or (ans != "no") or (ans != "No")
As you see, you should always repeat your variable.
the or operator assignment is not right please try this
ans = input("Enter yes or no: ")
if ans != "Yes" or "yes" or "no" or "No":
print("Can't do that")
if ans == "yes" or "Yes":
print("Great!")
if ans == "no" or "No":
print("Okay, then")
you can either write
if ans in ('stringone', 'stringtwo'):
dosomething()
Or you can write separate equality tests,
if var == 'stringone' or var == 'stringtwo':
dosomething()

Ending a "While" loop python? [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 2 years ago.
This might be a really dumb question, but I can't see why this loop doesn't end. I'm aware that while True is an infinite loop, but I'm pretty sure there are also ways to get out of them. Does anyone know how to end this code, so that if they enter "yes" etc. it continues on through the program but if they enter "no" etc. or anything else it asks them for their name again
while True:
user_name = input("What do you want your name to be? (Suggest using Forename and Surname!")
user_name_check = input("Your name is " + user_name + "? Is this correct?")
if user_name_check == "yes" or "Yes" or "y" or "Y":
break
elif user_name_check == "no" or "No" or "n" or "N":
pass
else:
print("Sorry, please only enter yes or no. Re-enter your name and try again.")
pass
try
if user_name_check == "yes" or user_name_check == "Yes" or user_name_check == "y" or user_name_check == "Y":

why multiple condition in python while loop are not working? [duplicate]

This question already has answers here:
OR statement handling two != clauses Python
(5 answers)
Closed 3 years ago.
I can't seem to find the problem in code...
user_decision = ""
while not user_decision == "yes" or not user_decision == "no":
user_decision = input("You want to Join?: Please answer (yes/no): ")
else:
if user_decision == "yes":
print("test")
else:
print("test")
Thanks....
I cleaned it up a bit:
user_decision = ""
while (user_decision != "yes") and (user_decision != "no"):
user_decision = input("You want to Join?: Please answer (yes/no): ")
if user_decision == "yes":
print("test yes")
else:
print("test not yes")

What is wrong with my 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.
This is a code i am working on but when i execute it , creates a problem towards the end
restart = "No" or "no"
while restart == "No" or "no":
print("League Registration")
Fristname = input("What is first name?")
Lastname = input("What is your Last name?")
Nickname = input("What is your nick name?")
Eaddress = input("What is your e-mail address?")
Skill = input("What is your skill level, E for expert or C for casual?")
if Skill == "C" or Skill == "c":
print("Casual")
elif Skill == "E" or Skill == "e":
print("Expert")
print (" These are your personal details:")
print ("First Name:",Fristname)
print("Last Name:",Lastname)
print("Nickname:",Nickname)
print("Email Address:",Eaddress)
print("Skill Level:",Skill)
Detailscon = input("Are your personal details correct: Yes or No?")
if restart == "Yes" or "yes":
print("Thanl you , you are now registered")
elif restart == "No" or "no":
print("Try again")
my code towards the end keeps messing up i don't know what to do
The error in your code, lies here. You see, in python
while (restart == "No") or "no":
The operator equal will evaluate first and then check if it is true or if the string "no" is longer than zero, which it is so it will run forever.
Instead change it to.
while restart in ["No", "no"]:

Categories