This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
I'm having a bit of trouble with my python3 persistent password locker. It stores and retrieves passwords as expected/desired, but I decided to insert a "backout" check so that if information is entered incorrectly you can go back and re-enter it. It seems to be skipping this check for no easily identifiable reason.
elif choice == 2:
conti = False
while conti != True:
print('Enter an account and password to store')
acc = input('Account: ')
apass = input('Password: ')
print('Account: ' + acc + '\n' + 'Password: ' + apass)
print('Correct?')
corr = input(': ')
corr.lower()
if corr == 'yes' or 'ye' or 'y':
print('Making Changes persistent')
# Shelve Stuff
conti = True
break
else:
print('Please make appropriate changes.')
continue
When I run this code it makes changes persistent regardless of what the corr variable happens to be. This is not what I want. I tried explicitly stating in an elif statement the no options and it skipped those as well. Are the multiple 'or' statements throwing it off or is there something else going on that I should be aware of?
This line is not doing what you'd hoped:
if corr == 'yes' or 'y' or 'y':
This translates to "is corr equal to 'yes'? It's not! So, is the value 'y' True? It is! Let's do this!" Note, it's not checking that corr is equal to 'y', just that the string 'y' is Truthy.
The longhand way would be:
if corr == 'yes' or corr == 'y':
but you could also do:
if corr in ['yes', 'y', 'Y', 'YES']:
or something similar to cover more options
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 question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
result = {}
question = '你叫什么名字? ' #What is your name
question_2 = '如果你能去世界上的任何一个地方度假,你想去哪? ' #If you could go to any place in the world for vacation, where would you like to go?
question_3 = '你愿意让你旁边的人也来参加这个调查吗? (yes/ no) ' #Would you like to let people next to you participate in this survey?
while True:
name = input(question)
place = input(question_2)
result[name] = place #除了yes或者no不允许输入其他字符
while True: #No other characters are allowed except "yes" or "no"
opinion = input(question_3)
if opinion.lower() != 'yes' or 'no':
print('请重新输入') #please enter again
else:
break
if opinion == 'no':
break
No matter what you enter after running, you can't jump out of the loop
if opinion.lower() not in ('yes','no'):
It's normal to change to this, but I'm still curious why something went wrong
Beginners, thanks
Consider this line:
if opinion.lower() != 'yes' or 'no':
So this is how that expression is evaluated (according to order of precedence):
if (opinion.lower() != 'yes') or ('no'):
And 'no' is always evaluated as True. Moreover, it should be option not 'yes' 'and' not 'no' (instead of 'or'). Consider changing it to:
if opinion.lower() != 'yes' and opinion.lower() != 'no':
More shortly,
if opinion.lower() not in ('yes', 'no'):
And this will fix your issue.
result = {}
question = "What is your name"
question_2 = "If you could go to any place in the world for vacation, where would you like to go?"
question_3 = "Would you like to let people next to you participate in this survey?"
while True:
name = input(question)
place = input(question_2)
result[name] = place #除了yes或者no不允许输入其他字符
while True: #No other characters are allowed except "yes" or "no"
opinion = input(question_3)
if opinion.lower() not in ('yes','no'):
print('please enter again')
else:
break
if opinion == 'no':
break
You could use a tuple to fix your problem, that's one thing first.
Now what you want is why isn't the following code working:
x != "yes" or "no"
Recall from the order of precedence that != has a higher priority than or, so x!= "yes" will be evaluated first, then it will be ORed with "no", simply to fix it, add parenthesis around the or statement:
x != ("yes" or "no")
Would do the trick for ya!
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)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 8 years ago.
EDIT - Apparently this is a duplicate. And while I've no doubt the core problems are answered elsewhere I think that the level is pretty blatant and thus the ability to comprehend other solutions and transpose them into my own problem is diminished. I searched before asking.
I'm just having a mess about and was trying to write a little thing with user input.
However, I'm not sure how to go about this without knowing how many iterations are needed, or having two questions?
I tried to modify it to take an if condition, which I don't really want anyway but that didn't work either :
for i in range(50):
userIn = raw_input()
urlList.append(userIn)
print 'Continue? Y/N'
ynAns = raw_input()
if ynAns == 'n' or 'N':
break
Basically I'm just trying to take user input to fill up a list and then print it out.
I also tried
import sys
listOne = []
num = int(raw_input('How many'))
for x in range(num):
listOne.append(raw_input(('Entry #' + x+1 + ' '))
print listOne
pretty basic
You need to compare ynAns with both 'n' and 'N':
if ynAns == 'n' or ynAns == 'N':
An alternative syntax:
if ynAns in ('n', 'N'):
The reason why your if statement doesn't work is that ynAns == 'n' and 'N' are two separate expressions. 'N' is always evaluated to True, so the if condition is always true.
It's basically jh314's answer, but shorter:
if ynAns.lower() == 'n':
What it does is converts ynAns to lowercase, making your code more concise.
Dont use a for loop for this, you´re restricting your app to run within a limit of 50 iterations, instead use while:
userInput = None
userInput = raw_input("Enter input (N or n to stop): ")
while(userInput not in ['N', 'n']):
urlList.append(userIn)
userIn = raw_input("Enter input (N or n to stop): ")
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,