I'm not exactly sure why but when I execute this section of code nothing happens.
while (True) :
choice = str(input("Do you want to draw a spirograph? (Y/N) "))
if choice == 'n' or 'N' :
break
elif choice == 'y' or 'Y' :
<CODE>
else :
print("Please enter a valid command.")
choice = input("Do you want to draw a spirograph? (Y/N)")
It won't work because the 'N' literal always evaluates to True within your if statement.
Your if condition currently stands as if choice == 'n' or 'N' :, which is equivalent to if (choice == 'n') or ('N'), which will always evaluate to True irrespective of the value of variable choice, since the literal 'N' always evaluates to True.
Instead, use one of the following
if choice == 'n' or choice == 'N' :
if choice in 'nN' :
if choice in ('n', 'N') :
The same holds for your elif block as well. You can read more about Truth Value testing here.
This expression doesn't do what you want:
choice == 'n' or 'N'
It is interpretted as this:
(choice == 'n') or 'N'
You might want to try this instead:
choice in 'nN'
Related
This question already has answers here:
not equals operator(!=) not working in python string comparison
(2 answers)
Closed 1 year ago.
Trying to add validation to user input.
So the code is:
print ('Does this service require an SFP Module? (y/n): ')
while True:
sfpreq = input()
if sfpreq != 'y' or 'n':
print("You must enter either y or n")
continue
else:
break
So even when the user enters 'n' it returns the "print("You must enter either y or n")" and continues the loop.
I have tried setting the variabl manually to and also tried another convention I found on realpython and also removed the if statement from the while loop:
sfpreq = "n"
if sfpreq != 'y' or sfpreq != 'n':
print("You must enter either y or n")
else:
print("Test")
Again it just returns:
admin#MacBook-Pro Learning Folder % python3 test22.py
You must enter either y or n
Am I just missing something very fundamental here?
Problem with the logic
sfpreq = "n"
if sfpreq != 'y' or sfpreq != 'n':
print("You must enter either y or n")
else:
print("Test")
Here, when you enter the if loop,
sfpreq != 'y' is validated as True and sfpreq != 'n' is validated as False.
Now True OR False statement in boolean algebra equates to True.
So, the if loop gets executed and You must enter either y or n is printed.
See, more about boolean algebra here
A better solution
sfpreq = "n"
if sfpreq not in {"y","n"}:
print("You must enter either y or n")
else:
print("Test")
So, here we are checking if y or n is not there in the set {"y","n"}. As in this case, sfpreq is there in that set so,the else statement gets executed.
This is my Python code:
choice = (input("Are you signed up? (y/n) "))
print(choice)
while True:
if choice != "y" or choice != "n":
choice = (input("Are you signed up? (y/n) "))
print(choice)
else:
break
I want the program to keep asking the user for input until they input "y" or "n". The problem is it never accepts the input, even if they do input "y" or "n".
When I print what they inputted (that's a real word) it says that it's "y" or "n" but it still won't accept it.
I've been using Python for some time now and I'm just trying something out today but I can't figure this out for some reason, I feel like it's something simple and obvious but I'm stupid to notice it.
Can someone explain this to me, please? Thank you.
Since choice cannot be 'y' and 'n' at the same time, one of choice != 'y' and choice != 'n' is always true.
You need to use and, not or.
Well, suppose the user inputs "y".
Your code will enter the while True loop and encounter the if condition
Is choice != "y" or choice != "n", where choice == 'y', true or false?
"y" != "y" is false, check the next condition
"y" != "n" is true, so the whole condition is true
Ask for input again
Goto (1)
Same thing happens for choice == "n".
However, you want a condition that says not (choice == "y" or choice == "n"). According to De Morgan's laws:
not (a or b) == (not a) and (not b)
So your code translates into:
(not (choice == "y")) and (not (choice == "n"))
=> choice != "y" and choice != "n"
As everyone has already pointed out the problem in your code, I am just adding a cleaned version of your code.
while True:
choice = (input("Are you signed up? (y/n) "))
if choice == "y" or choice == "n":
print(f"Your choice is {choice}")
break
You need and instead of or in this case.
if choice != "y" and choice != "n":
or if you prefer you can do
if not (choice == "y" or choice == "n"):
You can also do:
if choice not in ("y", "n"): # THIS ONE IS PROBABLY THE BEST
or because these are each 1-character you can do:
if choice not in "yn":
You can also do:
if choice not in "Randy!" or choice in "Rad!":
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"):
again = True
while(again == True):
yn = input("Do you want to do it again? (y or n)").lower()
if(yn == 'y' or 'yes'):
again == True
elif(yn == 'n' or 'no):
again == False
How do I make this code work? When I run it, it will always come out to be true.. =/
Let's start from the beginning:
while(again == True):
You don't need the parentheses here
You don't need the == True bit. again is suffice as it will have a boolean value of True.
if(yn == 'y' or 'yes'):
Once again, parenthesis aren't needed.
That line of code is translated as if (yn == 'y') or ('yes'):. This will always be true as 'yes' is considered True (not an empty string)
In python, you need to do if yn == 'y' or yn == 'yes':
Or you can do if yn in ('y', 'yes')
again == True
== is for comparisons. = is for assignments
This occurs in your else block.
In the final 4 lines of your program you aren't assigning again to have the value true, you are checking if again equals True/False.
== is completely different from =.
This won't work:
if (yn == 'y' or 'yes'):
# ...
elif(yn == 'n' or 'no):
The correct way is:
if yn in ('y' or 'yes'):
# ...
elif yn in ('n' or 'no):
Also, inside the conditions the assignments are wrong, use a single =. They should look like this:
again = True
# ...
again = False
You are mistaking the equality operator == with the assignment operator =. Also the statement yn == 'y' or 'yes' is buggy, since the right hand side is a non-empty string, which evaluates to True in a boolean context.
Declaring a variable simply to handle loop termination is not pythonic. I would rewrite your code entirely to be:
while True:
yn = input("Do you want to do it again? (y or n)").lower()
if yn in ('n','no'):
break
if(yn == 'y' or 'yes'):
# ----
The value of above statement is always true independent of valu of “yn” because right side of “or” is always true in your case. so it will never execute else part. So to avoid this, You have to compare value of “yn” with each possibility.
one of the simple way is that
if(yn == 'y' or yn == 'yes'):
again == True
elif(yn == 'n' or yn == 'no):
again == False
your if else statment should be
if xxx:
again = True
elif yyy:
again = False
Note difference between = and ==.
I have written a very basic encryption program, and whilst writing the decrypting algorithm for it, I have encountered some problems with a loop I have.
from re import *
cipher = open('cipher.txt')
ciphertext = cipher.read()
keyfile = open('key.txt')
key = keyfile.read()
decoded = []
chardec = ''
inval = 1
print("Decoder for encrypt1.py")
while inval == 1:
useManKey = input("Use a manual key? Y or N\n> ")
if useManKey == 'Y' or 'y':
key = input("Please enter the key you wish to use to decrypt\n> ")
inval = 0
elif useManKey == 'N' or 'n':
inval = 0
print("OK, decrypting")
else:
print("That wasn't a valid option/nPlease re-enter")
When I run this, and declare useManKey as N or n it seems to run the if part of the loop as if I had declared it as Y or y. I am probably being stupid here, but any help would be much appreciated thanks.
useManKey == 'Y' or 'y' does not work how you think it does. What you want is useManKey in ('Y', 'y'). What you have first evaluates useManKey == 'Y', then, if that check fails, tests the string 'y' for truishness. Since non-empty strings are always truish, your if statement always evaluates to True. As is pointed out in the comments, you could also use upper() or lower() to first convert the input to a fixed case if you want.
useManKey == 'Y' or 'y'
Doesn't actually check whether useManKey value being 'Y' or 'y', Use sr2222's answer for what you need to do. ie.
useManKey in ('Y', 'y')
The earlier expression evaluates to
(useManKey == 'Y') or 'y'
Which is always True irrespective of the value of useManKey as 'y' being non-Falsy (non-None) the 'or' of these always evaluates to True,