You could cut down on code slightly by just writing
if variable and variable.upper() == "X":
#Do something
If the variable is none or empty, then it's equivalent to False.
Answer from obmarg on Stack OverflowYou could cut down on code slightly by just writing
if variable and variable.upper() == "X":
#Do something
If the variable is none or empty, then it's equivalent to False.
if variable and variable.upper() == 'X'
is a little less wordy. It will also treat None and the empty string in the same way if that is something you want
Edit: Note that this does have different semantics to the expression you posted in the way it handles empty strings... i.e. in your expression the rhs of the and would get evaluated if variable is the empty string, but in this expression it would not as the empty string evaluates to False
I recently came across a problem in a textbook where these 2 were interchangeable. So what’s the difference between these 2 and when to use which? Thanks!
Edit for context:
would like to clarify the use of None in this question to initialize the while loop, how does it initialize the loop?
start = None
while start != “”: start = int(input(“Start: “) . . .