Elif and if not working or me not understanding [duplicate] - python

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.
Well my code is working, but when I type No if I want to retry to enter the password it doesn't work; it just goes to the enter password line (line 20). I have tried multiple ways to fix this but I simply cannot.
import time
import os
print ("Hello world.")
time.sleep(1)
print ("Waiting 5 seconds.")
time.sleep(5)
print ("You have waited 10 seconds.")
print ("Executing Chrome.")
time.sleep(1)
print ("Execution failed!")
password = input("Enter the execution password: ")
if password == 'password1234':
os.system ('C:\\Users\\Harry\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe')
else:
print ("Wrong password!")
time.sleep(1)
passretry = input("Do you want to try again? ")
if passretry == 'yes' or 'Yes':
passretry1 = input("Enter password: ")
if passretry1 == 'password1234':
os.system ('C:\\Users\\Harry\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe')
elif passretry == 'no' or 'No':
print ("Closing...")
time.sleep(1)
else:
print ("Wrong password.")
time.sleep(.5)
print ("Retry limit exceeded, closing.")
time.sleep(1)

if passretry == 'yes' or 'Yes':
the above if statement is evaluated as: -
if (passretry == 'yes') or 'Yes':
Now, since 'Yes' is evaluated to True, so, your if statement is always True, and hence you always have to enter new password.
You need to change the condition to: -
if passretry in ('yes', 'Yes'):
likewise, the following elif should be changed to: -
elif passretry in ('no', 'No'):

This condition:
if passretry == 'yes' or 'Yes':
means "If passretry == 'yes' is true, or 'Yes' is true". 'Yes' is always true, because a non-empty string counts as true. That's why you're always taking the first code path.
You need to spell things out a little more:
if passretry == 'yes' or passretry == 'Yes':
(Or to make your code a bit more general:
if passretry.lower() == 'yes':
which would allow for people shouting YES.)

You need another complete statement:
passretry == 'yes' or passretry == 'Yes':
The string 'Yes' always evaluates to True.

Related

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

How can I create a function with Yes or No?

How can I go about creating a input and output with Y\N (yes or no) function in a question?
My example; if my question is Would you like some food? (Y \ N):, how can I do this and have the answers show Yes, please. or No, thank you. for either choice and then proceed to the next question with the same function?
I thought about using this: valid=("Y": True, "y": True, "N": False, "n": False) but that only shows up as True or False for me, or is there a way to change from True \ False to Yes \ No? or this one:
def user_prompt(yes_no):
while True:
user_input=input(yes_no)
But I'm really not sure how else to proceed with this one, or if there's any other easier solution to this.
I think what you're looking for is a conditional print statement rather than a true/false return statement on the function.
For example:
def user_prompt():
while True:
user_input = input("Would you like some food? (Y \ N)")
print ("Yes, please" if user_input == 'Y' else "No, thank you")
Or, more readable:
def user_prompt():
while True:
user_input = input("Would you like some food? (Y \ N)")
if (user_input == 'Y'):
print("Yes, please")
elif (user_input == 'N'):
print("No, thank you")
I hope I understood your question correctly, you basically check the first letter (incase user enters yes/no) every time the user enters a value and try to verify that if it's Y/N you break the loop if not you keep asking the same question.
def user_prompt(yes_no):
while True:
user_input=input(yes_no)
if user_input[0].lower() == 'y':
print("Yes, please.")
break
elif user_input[0].lower() == 'n':
please("No, thank you.")
break
else:
print("Invalid, try again...")
Not sure if this is the best way, but I have a class based implementation of same
""" Class Questions """
class Questions:
_input = True
# Can add Multiple Questions
_questions = [
'Question 1', 'Question 2'
]
def ask_question(self):
counter = 0
no_of_question = len(self._questions)
while self._input:
if counter >= no_of_question:
return "You have answred all questions"
user_input = input(self._questions[counter])
self._input = True if user_input.lower() == 'y' else False
counter += 1
return "You have opted to leave"
if __name__ == '__main__':
ques = Questions()
print(ques.ask_question())
Firstly there is many ways you can go around this, but I am guessing you found the solution yourself already but here is one that is the best.
def get_yes_no_input(prompt: str) -> bool:
allowed_responses = {'y', 'yes', 'n', 'no'}
user_input = input(prompt).lower()
while user_input not in allowed_responses:
user_input = input(prompt).lower()
return user_input[0] == 'y'
continue = get_yes_no_input('Would you like to proceed? [Y/N]: ')
And there we go.

Why does my program print this string even when i have a while != string [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 5 years ago.
Hello i made this program that asks the user to input the choices Print,sort1,sort2 or quit
usrinpt=0
while usrinpt != "quit": #if usrinpt == quit then no if statements right?
usrinpt = input("Enter choice Print, Sort1 (distance), Sort2 (price) or Quit : ")
usrinpt = usrinpt.lower()
if usrinpt == "print":
PrintList(mat)
pass
elif usrinpt == "sort1":
SelectionSortDistorPrice(mat,0)
PrintList(mat)
pass
elif usrinpt == "sort2":
SelectionSortDistorPrice(mat, 1)
PrintList(mat)
pass
elif usrinpt != "quit"or"sort1"or"sort2": #why does it print the string even when i enter quit?
print("please enter a valid choice")
pass
expected outcome for the choice "quit" is for a the program to stop
actual outcome is that the program prints " please enter a valid choice" and then quits
how can i fix it to only print that string if a choice not stated is entered?
elif usrinpt not in ["quit","sort1","sort2"]:

Python 'if' statement not triggering correctly [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, 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.

Python condition not applying (if/elif)

I have a problem with a condition in my python code.
It's a mathematics application, and here's the part of the code that is not working well:
def askNumber():
"""Asks the number to test"""
a=raw_input("Select the number to test (type 'exit' for leaving):")
if len(a)!=0 and a.lower!="exit":
try:
b= int(a)
processing(b)
except ValueError:
print "Your input is not valid. Please enter a 'number'!"
time.sleep(1)
askNumber()
elif len(a)!=0 and a.lower=="exit":
answer()
else:
print "Your input can't be 'empty'"
time.sleep(1)
askNumber()
So, when in the raw_input for "a" I type "exit", the supposed condition to apply is the elif one but ends up applying the if one, ending up printing "Your input is not valid. Please enter a 'number'!" Sorry, if it's something obvious, I'm a begginer, although I tried to find the mistake several times.
You need to call the .lower() function.
if len(a) != 0 and a.lower() != "exit":
# ...
elif len(a) != 0 and a.lower() == "exit":
There is no real need to test for len(a)!=0, simply test for a itself:
if a and a.lower() != "exit":
# ...
elif a and a.lower() == "exit":
Empty strings evaluate to False in a boolean context.
Your program flow is a bit inside out, may I suggest some improvements?
def askNumber():
"""Asks the number to test"""
while True:
a = raw_input("Select the number to test (type 'exit' for leaving):")
if not a:
print "Your input can't be 'empty'"
continue
if a.lower() == "exit":
answer()
break
try:
b = int(a)
except ValueError:
print "Your input is not valid. Please enter a 'number'!"
continue
processing(b)
Actually, the not a branch can be eliminated as well (empty inputs will be handled in except).
You could change the condition for the following one:
if a and a.lower() !="exit":
# .....
elif a and a.lower() == "exit":
answer()
elif a and not a.isdigit(): print "invalid input"
else:
#.............
Please note that yo don't need len(a) != 0 , just by using a will evaluate if it's empty or not.

Categories