Input selection in Python using IF statements [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
Im trying to create code that prints a game's difficulty level based on what the "diffChoice" value is using IF statements. However, I can't get the "gameDiff" value to correctly represent what the "diffChoice" was. Any help/feedback is appreciated.
diffChoice = 'm'
if diffChoice == 'e' or '1':
gameDiff = 'EASY'
if diffChoice == 'm' or '2':
gameDiff = 'MEDIUM'
if diffChoice == 'h' or '3':
gameDiff = 'HARD'
print(gameDiff)

In all of your Boolean conditions, the second expression after the or is truthy, so x or y will always yield True.
Consider:
if "1":
print("I'll print!")
if "2":
print("So will !")
if "":
print("I won't print; the empty string (an empty sequence of characters) is treated as False.")
if []:
print("I won't print: the empty list is treated as False.")
if False or 1:
print("I WILL print: False or 1 is treated as False or True.")
You can read more about this here. In particular:
By default, an object is considered true unless its class defines either a bool() method that returns False or a len() method that returns zero, when called with the object.
What you want is to test a or b, so write:
if diffChoice == 'e' or diffChoice == '1':
gameDiff = 'EASY'
or, equivalently:
if diffChoice in ('e', '1'):
gameDiff = 'EASY'
and so on.

Related

Python: Keyboard prompt with capital/noncapital letters

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!")

Python will not accept user inputs [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 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"):

python if statement evaluation with multiple values

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'

If function doesn't work as expected in PYTHON [duplicate]

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.

Why does my elif go back to my if?

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,

Categories