Another_Mark = raw_input("would you like to enter another mark? (y/n)")
while Another_Mark.lower() != "n" or Another_Mark.lower() != "y":
Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
if Another_Mark == "y":
print "blah"
if Another_Mark == "n":
print "Blue"
This is not the actual code I'm using except for the 1st three lines. anyways my question is why does the while loop keep repeating even when I input a value 'y' or 'n', when it asks again if you want to input another mark on the third line. I'm stuck in a infinitely repeating loop.
It shouldn't repeat when the value for Another_Mark is changed to either "y" or "n"
Try:
while Another_Mark.lower() not in 'yn':
Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
not in operator returns true if given object is not found in the given iterable and false otherwise. So this is the solution you're looking for :)
This wasn't working due to boolean algebra error fundamentaly. As Lattyware wrote:
not (a or b) (what you describe) is not the same as not a or not b
(what your code says)
>>> for a, b in itertools.product([True, False], repeat=2):
... print(a, b, not (a or b), not a or not b, sep="\t")
...
True True False False
True False False True
False True False True
False False True True
Your loop logic only every comes out true - if the input is "n", then it's not "y" so it's true. Conversely if it's "y" it's not "n".
Try this:
while not (Another_Mark.lower() == "n" or Another_Mark.lower() == "y"):
Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
Your logic behind the looping is wrong. This should work:
while Another_Mark.lower() != "n" and Another_Mark.lower() != "y":
Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
You need to use AND instead of OR.
It's the way boolean logic distributes. You can say:
NOT ("yes" OR "no")
Or you can distribute the NOT into the parenthesis (which is what you're trying to do) by flipping the OR to an AND:
(NOT "yes") AND (NOT "no")
Related
In this code:
if raw_input("\n Enter 'y' or 'Y': ")==("y" or "Y"):
print("\n Success!")
It doesn't take the "OR" properly, instead if the in this case noncapital 'y' is entered the condition is fulfilled. If I enter the capital 'Y' I don't get the Success!
What's wrong here?
Try this
if raw_input("\n Enter 'y' or 'Y': ").lower() == "y":
Try to make a list of values and use the in keyword. Something like this will work,
if raw_input("\n Enter 'y' or 'Y': ") in ('y', 'Y'):
print("\n Success!")
The in keyword tests the string against a tuple of strings and on a correct match it returns True.
Since here you have just one character, you can build a string "yY". Something like this will work,
if raw_input("\n Enter 'y' or 'Y': ") in "yY":
print("\n Success!")
Here each character of the string acts like one element of the tuple above.
ERROR in your code:
You used ("y" or "Y"). This does not work in Python. This will only return "y" as both "y" and "Y" are treated as True values. However, if you type (0 or "Y"), you will get "Y" as 0 is treated as a False value.
The right-hand-side of your if-statement is wrong and I think you need to understand a little better how the or operator behaves between strings.
Keep in mind that the return value of or is the value that has been evaluated last, and that Python evaluates empty string as boolean False and non-empty strings as boolean True.
In your case, the interpreter reads ("y" or "Y"), it then evaluates the boolean value of "y" which is True, as it is a non-empty string. Therefore, the boolean value of the or statement it True and the return value of the statement becomes "y", the last evaluated value.
This is how I would write this code. I would keep the return value of raw_input in _input, which will make it easier for me and others to read and understand the if-statement:
_input = raw_input("\n Enter 'y' or 'Y': ")
if input in ["y", "Y"]:
print("\n Success!")
What's wrong here?
In many programming languages, OR is a boolean operator. You apply it to values that are TRUE or FALSE. The operation evaluates to TRUE if at least one operand is TRUE:
TRUE OR TRUE == TRUE
TRUE OR FALSE == TRUE
FALSE OR TRUE == TRUE
FALSE OR FALSE == FALSE
In Python, you can apply or on non-boolean operands:
x or y
returns x if x casted to boolean is True; else it returns y. For boolean operands, this leads to the same results as above, but for non-boolean operands this has interesting effects:
[] or {} is {} (because empty lists are False when casted to
boolean)
[1] or {} is [1] (because non-empty lists are True when casted to boolean)
[1] or 1/0 is also [1] (the right operand doesn't even get evaluated when the left one is True, so we don't hit the ZeroDivisionError. This is known as (left-to-right) short-circuit evaluation.)
Thus, other than in natural language, the Python or cannot be interpreted as separating alternative values. (Only alternative conditions / boolean expressions.)
There are several possibilities on how to make your code behave as expected:
The naive approach:
answer = raw_input("\n Enter 'y' or 'Y': ")
if answer == "y" or answer == "Y":
print("\n Success!")
Normalizing the input:
if raw_input("\n Enter 'y' or 'Y': ").lower() == 'y':
print("\n Success!")
Comparing to set of alternative values with membership operator in:
if raw_input("\n Enter 'y' or 'Y': ") in {'y', 'Y'}:
print("\n Success!")
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 managed to get this code to work before, but I've changed something accidentally and can't figure out what.
The code that will not work is:
while True:
answer = input ("Would you like to play this game? Type yes if you would like to. Type no to end the program")
if answer == 'no' or 'n' or 'No' or 'N':
sys.exit()
elif answer == 'yes' or 'y' or 'Yes' or 'Y':
code = input("Input a three digit code. Must be more than 001 and less than 100.")
When I run the code and put in one of the answers, the program will not run the next part and gives no error message.
In case it is necessary, I have put the code for the entire program below:
import random
import sys
while True:
answer = input ("Would you like to play this game? Type yes if you would like to. Type no to end the program")
if answer == 'no' or 'n' or 'No' or 'N':
sys.exit()
elif answer == 'yes' or 'y' or 'Yes' or 'Y':
code = input("Input a three digit code. Must be more than 001 and less than 100.")
try:
value = int(code)
except:
print ("Invalid code")
continue
if 1 <= value <= 100:
print (code)
print ("Valid code")
print ("I will now try to guess your number")
number = random.randint(1, 100)
while number > int(code) or number < int(code):
print ("Failed attempt. Number guessed is")
number = random.randint(1, 100)
print (number)
else:
if number == int(code):
print ("Your code is")
print (code)
else:
print ("Invalid code")
EDIT: Thank you so much, the yes option is working now, but the program will still not exit when selecting any of the no options, as it did before. The edited code is:
if answer in ('no', 'n', 'No', 'N'):
sys.exit()
elif answer in ('yes', 'y', 'Yes', 'Y'):
I checked by printing the answer value, and i believe it is registering the no input but not executing the command that follows for some reason.
EDIT: I'm still a bit fuzzy on the logic, but changing it to exit() fixed the problem. It asks for confirmation when closing now, when it didn't before, but otherwise sorted.
Problem causing silent exit:
if answer == 'no' or 'n' or 'No' or 'N':
sys.exit()
That test is testing answer == 'no' as one test, then 'n' as a separate test, and so on. or chains return when any test returns a "truthy" value (or the last evaluated value if none are truthy), so the test always ends up evaluating as "truthy" because a non-empty string like 'n' is truthy. If you're trying to test for any one of those values, you'd do an "is contained in" test to see if answer is one of a recognized group of values, e.g.:
if answer in ('no', 'n', 'No', 'N'):
The reason is due to this expression:
if answer == 'no' or 'n' or 'No' or 'N':
In python, the above is exactly the same as this:
if (answer == 'no') or ('n' != '') or ('No' != '') or ('N' != ''):
Since all but the first expression evaluates to true, the whole expression is true.
The simplest solution is to convert your input to lowercase and trim off any extra space, then check if the answer is in a list of allowable answers so that you can easily compare for "n", "N", "no", "NO", "No", "nO".
if answer.strip().lower() in ("n", "no"):
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
Here is a part of my code where the problem is.
It doesn't matter what the input is, the script will end
when I enter something.
It should restart when i enter "yes" or "y"
Without the OR it works without problem
else:
if number == rndnum:
print "Congratulations! You won."
print "Do you want to replay?"
answer = raw_input("Type y (yes) or n (no): ")
dialog = 1
while dialog == 1:
if answer == "n" or "no":
replay = 0
dialog = 0
elif answer == "y" or "yes":
dialog = 0
else:
answer = raw_input("Type y (yes) or n (no): ")
loop = 0 #Will overdo loop var and stop the loop
if answer == "n" or "no":
is interpreted by Python as:
if (answer == "n") or ("no"):
Which is always true, because the second condition in your or clause is always True (non-empty strings in Python are truthy, which means they evaluate to True in a condition):
>>> bool("no")
True
What you need is one of:
if answer in ("n", "no"):
# or
if answer == "n" or answer == "no":
Th same goes for "yes", of course.
Adjust your code like this:
if answer == "n" or answer == "no":
# ...
and:
elif answer == "y" or answer == "yes":
# ...
a or b, where a and b are strings and not both the empty string, will always evaluate to True in a boolean context, demo:
>>> '' or 'x'
'x'
>>> 'y' or 'x'
'y'
>>> '' or ''
''
>>> if 'x': print('hi')
...
hi
>>> if '': print('hi')
...
>>>
The first two expressions will evaluate to True.
My code is:
def nameAndConfirm():
global name,confirm
print("What is your name? ")
name = input()
str(name)
print("Is",name,"correct? ")
confirm = input()
str(confirm)
print(confirm)
if confirm.upper() == "Y" or "YES":
classSelection()
elif confirm.upper() == "N" or "NO":
nameAndConfirm()
else:
print("Valid answers are Y/Yes or N/No!")
nameAndConfirm()
nameAndConfirm()
Critique on this code would be nice as well. I know its very shifty, I know how to make it shorter in some ways but I was trying to get my if-elif-else to work. I have no clue what else I can do as I've tried everything I know. Also I made an indent 4 spaces in the above code. **Edit: sorry the error is that it always runs the "if" it never goes past the first if line no matter what you enter in for confirm
The condition confirm.upper() == "Y" or "YES" and the other one are not evaluated as you expect. You want
confirm.upper() in {"Y", "YES"}
or
confirm.upper() == "Y" or confirm.upper() == "YES"
Your condition is equivalent to:
(confirm.upper() == "Y") or "YES"
which is always truthy:
In [1]: True or "Yes"
Out[1]: True
In [2]: False or "Yes"
Out[2]: 'Yes'
On a separate note, the lines
str(name)
and
str(confirm)
don't do anything. The values returned by the functions are not saved anywhere, and name and confirm are not altered. Moreover, they are already strings to begin with, because they hold the return values of input().
I'm a self taught programmer, and I just started using python. I'm having a bit of a problem, when I execute this code:
x = 0
while x == 0:
question = raw_input("Would you like a hint? ")
if question == "y" or "yes":
print "Ok"
first.give_hint("Look over there")
x = 1
elif question == "n" or "no":
print "Ok"
x = 1
else:
print "I'm Sorry, I don't understand that"
just so you know, first.give_hint("Look over there") was defined in a class earlier in the program, I just left that part out for sake of space. When I run the program no matter what I type, I get the first case "Look over There", I've been trying to figure out what the problem is, but I just don't understand. If you guys could help me, I'd appreciate it a lot.
The problem is this line:
if question == "y" or "yes":
"yes" will always evaluate to True.
What you really want is:
if question == "y" or question == "yes":
Similar changes must be made for the other conditions.
You made a mistake in your if statement, this should be :
if (question == "y") or (question == "yes"):
print "Ok"
Explanation :
(question == "y" or "yes")
is equivalent to :
(question == "y" or "yes" != 0) # operator 'or' having the prevalence
"yes" string being non-null, ("yes" != 0) always return True, and so do your whole original condition.
The condition is wrong. You have question == "y" and a logical or with the string "yes" that is always True. That is why it evaluates to the first case every time.
Try to change to if question[0] == 'y'