This question already has answers here:
Priority of the logical operators (order of operations) for NOT, AND, OR in Python
(8 answers)
Closed 4 months ago.
The code is supposed to return false if the user's input is not "Y" or "N". When the user types "Y", it ends the loop, but when the type "N" it still continues the loop. How can this be corrected?
# Ask if they want to continue
while True:
noOrYes = input(f"Do you want to continue? (Y/N)")
if not noOrYes == "Y" or noOrYes == "N":
print("Sorry, I didn't understand that.")
#better try again... Return to the start of the loop
continue
else:
#firstName & lastName was successfully parsed!
#we're ready to exit the loop.
print(f"break")
break
Much like mathematical operations and PEMDAS, boolean operators (and, or, ==) have an "order of operations." Right now you are asking two questions:
Is noOrYes not equal to Y?
Is noOrYes equal to N?
Fix the order of operations by using parentheses.
if not (noOrYes == "Y" or noOrYes == "N")
you can do this instead:
while True:
noOrYes = input(f"Do you want to continue? (Y/N)")
if noOrYes == "Y":
break
else :
print("Sorry, I didn't understand that.")
Instead of asking "if not"s. The following code takes care of every input that's not some variation of "yes" or "no"(Ex. "yeah", "nope", etc.).
# Ask if they want to continue
while True:
noOrYes = input(f"Do you want to continue? (Y/N)")
if noOrYes.lower().startswith('y'):
#User gave a proper response
#we're ready to exit the loop.
break
elif noOrYes.lower().startswith('n'):
#User gave a proper response,
#we're ready to exit the loop.
break
else:
print("Sorry, I didn't understand that.")
#Better try again... returning to the start of the loop
continue
Related
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
Background:
I'm experimenting with while loops and I just made a simple program nested in a while loop.
Code:
while True:
userinput = input("Is nem jeff? ")
if userinput == "y" or "yes" or "Y" or "Yes":
print ("YAY!")
elif userinput == "n" or "no" or "N" or "No":
print ("das sad :(")
else:
print ("wrong input")
break
Problem:
My program should be looping until the user types in an invalid input, but instead, it always returns the value nested in the if statement, no matter what I type in. What am I doing wrong?
Your conditionals aren't doing what you think they are.
In Python, a non-zero-length string evaluates to True in a boolean
context. The or operator performs a boolean or operation between
the lefthand operand and the righthand operand.
So when you write this:
if userinput == "y" or "yes" or "Y" or "Yes":
What you are saying is this:
if (userinput == "y") or True or True or True:
Which will always evaluate to True. You want to write instead:
if userinput == "y" or userinput == "yes" or userinput == "Y" or userinput == "Yes":
Or more simply:
if userinput.lower() in ['y', 'yes']:
The reason false down to truthsy or falsy in if conditions.
based on your initial code block
print('y'=='yes'or'y')
[output] y
print('n'=='yes'or'y')
[output] y
based on the above you can see that regardless of you input, your first if statement would be evaluated as True.
rather than doing that, try doing this instead.
while True:
userinput = input("Is nem jeff? ").lower()
if userinput in ['yes','y']:
print ("YAY!")
elif userinput in ['no','n']:
print ("das sad :(")
else:
print ("wrong input")
break
Started learning python a few days ago and was doing a task with simple yes/no inputs and doing different things with the while loop depending no whether the user wants to continue using the program or not.
The whole program is fairly small so hope it's alright to post the entirety of its code here. This is what worked for me:
import random
print("=====================================")
print("I Add Numbers and Tell You the Sum v2")
print("=====================================")
while True:
rand1 = random.randint(1, 100)
rand2 = random.randint(1, 100)
result = rand1 + rand2
print(f"I'm adding {rand1} and {rand2}. If you add them together,the result would be {result}")
print()
again_input = input("Would you like to try again? (Y/N) ")
again = again_input.lower().strip()
validyes = ["yes", "y"]
validno = ["no", "n"]
if again in validyes:
print("Sure thing!")
print()
elif again in validno:
print("Okay. See you!")
break
else:
print("That's not a valid response. The program will now exit.")
break
While the relevant code that didn't work as expected was this, to do with checking the user input against the valid list:
valid = ["yes", "y", "no", "n"]
if valid == "yes" or "y":
print("Sure thing")
elif valid == "no" or "n":
print("Okay bye")
break
else:
print("That's not a valid response. The program will now exit")
break
The former would run just fine, while the latter will print "Sure thing" regardless of what the user inputs. Why is that the case?
On that front, I'm happy to hear any other tips you guys might have with regards to making the rest of the code better. Eager to hear from and take part in this community!
You have to show what all the string what they are comparing to
if again == "yes" or again == "y":
print("Sure thing")
elif again == "no" or again == "n":
print("Okay bye")
break
else:
print("That's not a valid response. The program will now exit")
break
Also a tip is to use "\n" for a new line. The \n will not be shown
Old:
print(f"I'm adding {rand1} and {rand2}. If you add them together,the result would be {result}")
print()
New:
print(f"I'm adding {rand1} and {rand2}. If you add them together,the result would be {result}\n")
Last is that for the lower and strip function u can use it in the same line were u get your input
Old:
again_input = input("Would you like to try again? (Y/N) ")
again = again_input.lower().strip()
New:
again = input("Would you like to try again? (Y/N) ").lower().strip()
In the second case you're using the OR operand wrong and that's why it is always printing Sure thing. Here you can take a look and understand it better.
To make the code better, i would suggest keeping the valid list with all valid inputs, and checking for yes or no using the if again in valid method, but playing with what is and isn't valid inputs.
This is how or works
operation: x or y result: if x is false, then y, else x
Explanation:
valid == "yes" will be false for obvious reason because you are comparing a list to a string. When the first condition is false operator or goes to evaluate next condition which is just "y" and will always be true(you can confirm it using bool("y")) so that's why it's always printing "Sure thing".
You use this:
if valid == "yes" or "y":
print("Sure thing")
elif valid == "no" or "n":
print("Okay bye")
break
So in the first condition you check if (valid == "yes") or ("y"), but not if valid == ("yes" or "y"). Non-empty string is always True, when you use it as bool, so the first condition is always True. If you want to do somwthing like this, you can use tuples (it's like lists, but you cant edit it): if valid in ("yes", "y")
valid is a list, so valid will never equal to "yes", so it just goes to "y", which will always equal true. You need to check if "yes" or "y" is in valid:
if "yes" in valid or "y" in valid:
print("Sure thing")
elif "no" in valid or "n" in valid:
print("Okay bye")
break
Of course, with this code it will always print "Sure thing" because valid includes all the options.
I have just started learning Python and I have some issues with the while loop.
instruction_yes_no = ""
while instruction_yes_no.lower() != "y" or "n":
instruction_yes_no = input("Do you want to see the instruction? Please write 'Y' or 'N'\n")
if instruction_yes_no.lower() == "y":
print("You are gonna lose even if you read the instructions...")
print("\n")
time.sleep(1)
instruction()
elif instruction_yes_no.lower() == "n":
print("Do you think you are better than me? I will beat you faster since you have not read the instructions")
time.sleep(1)
else:
print("You mortal...you have not chosen a valid input. Type or 'Y' or 'N'")
time.sleep(1)
break
Basically I would like to obtain the following:
1) If the user inputs 'y', the instruction() function is called (THIS WORKS)
2) If the user inputs 'n', it prints ""Do you think you are better than me?..." (THIS WORKS)
3) If the user does not type either 'y' or 'n', I would like to keep looping until the user insert or 'y' or 'n'.
HOWEVER this is not working.
I am not understanding why. This is how I think it should work:
At the beginning the variable instruction_yes_no is set to ""
It enter the loop because instruction_yes_no != than 'y' or 'n'
Now, instruction_yes_no assumes the value that the user inputs
If the user does not input either 'y' or 'n' it should keep looping, but is does not.
If the user does not input either 'y' or 'n' it should keep looping, but is does not
Because you have the break after the if-elif-else. So it will break in any case.
Move that break inside the if block (when instruction_yes_no.lower() == "y").
Oh, this is a classic common error:
while instruction_yes_no.lower() != "y" or "n":
It's the same as
while (instruction_yes_no.lower() != "y") or True:
You want this instead:
while instruction_yes_no.lower() != "y" and instruction_yes_no.lower() != "n":
Or maybe this, it's shorter :)
while instruction_yes_no.lower() not in ["y", "n"]:
number=input("enter a whole number")
if number.isdigit():
print("Good one")
else:
print ("haha, really clever")
answer=str(input("Wanna try again? y/n"))
if answer == 'n':
print("Ok loser")
break
elif answer== 'y':
print("ok...good luck")
continue
I tried to make a code that would react if the input is integer or float, and if its float it would restart if the person wants it to; but the command 'break' doesnt want to work for some reason please help... (make it simple please)
You just need to wrap your code with a while loop.
while True:
number=input("enter a whole number")
if number.isdigit():
print("Good one")
else:
print ("haha, really clever")
answer=str(input("Wanna try again? y/n"))
if answer == 'n':
print("Ok loser")
break
elif answer== 'y':
print("ok...good luck")
continue
To use a break, you need it to be in a loop (while, for, ...). A break stop the execution of the loop if it's condition is met. In your casse you only have ifs, so you don't need a break as it will not check the other conditions if the first one is met.
You need to use a while loop.
answer = 'y'
while answer == 'y':
number = input("Please enter a whole number: ")
if number % 1 == 0:
print("Good one!")
else:
print("Haha, really clever.")
answer = input("Wanna try again? (y/n) ")
Set the answer to y so the loop runs at least once.
If the user wants to try again they enter y and the condition will be true meaning the loop wil run again.
Hope this helped!
question = input('Please choose one. add, times, divide, minus')
if (question=='add'):
if (question=='times'):
if (question=='divide'):
if (question=='minus'):
I want to make it so if I enter something else it will ask me to enter it again instead of error
Use elif to chain your conditions together; only one matching condition will then be picked:
if (question=='add'):
elif (question=='times'):
elif (question=='divide'):
elif (question=='minus'):
The added advantage is that you can now tack on an else block, to catch the case where the user picked none of the above:
if (question=='add'):
elif (question=='times'):
elif (question=='divide'):
elif (question=='minus'):
else:
You could put your question asking in an endless loop, and use break to step out of that loop, and perhaps use continue to restart the loop from the top:
while True:
question = input('Please choose one. add, times, divide, minus')
if (question=='add'):
#
elif (question=='times'):
#
elif (question=='divide'):
#
elif (question=='minus'):
#
else:
print('Please enter a valid option!')
continue
# we got here, so we must've had a proper input
break
Also see the canonical Asking the user for input until they give a valid response question here on Stack Overflow.
It will continuously ping the user unless he/she enters the correct input ,
while True:
question = input('Please choose one. add, times, divide, minus')
if (question=='add'):
#Do processing
break
elif (question=='times'):
#Do processing
break
elif (question=='divide'):
#Do processing
break
elif (question=='minus'):
#Do processing
break
else:
print "Please enter a valid input !"
To continue asking:
question = ''
while question not in ('add', 'times', 'divide', 'minus'):
question = input('Please choose one. add, times, divide, minus')
if question == 'add':
# do something
elif question == 'times':
# do something
...
Note, that to interrupt the loop the answer must be one of the alternatives.