I am trying to practice using ternary operators and I want to use them to set a value to False or True, but I am getting an error. Do you guys know what I am doing wrong?
play = False if ans.lower() is 'n' else play = True
I am trying to practice using ternary operators and I want to use them to set a value to False or True, but I am getting an error. Do you guys know what I am doing wrong?
play = False if ans.lower() is 'n' else play = True
You can fix your immediate problem with:
play = False if ans.lower() is 'n' else True
without the extra assignment after the else
. The basic idea of the ternary is:
finalValue = valueOne if someCondition else valueTwo
However, there are other problems with that(1), so I'd suggest the more succinct:
play = (ans.lower() != 'n')
(1) Amongst them the fact that is
checks for identity equality, not value equality. See, for example:
>>> x = 9999
>>> y = 9999
>>> x == y
True
>>> x is y
False
You'll notice that the two objects are distinct even though they have the same value.
Secondly, you don't actually need a ternary if you're using a boolean value to feed into it, you can just use the boolean operators to manipulate it.
Any ternary of the forms:
True if condition else False
False if condition else True
can be better espressed as (respectively):
condition
not condition