Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"not in" identity operator not working when checking empty string for certain characters

When checking if an empty string variable is populated with certain characters, the expression is always evaluated as true. If the newly created string value is empty, it should be false, it does not contain any characters let alone the ones being checked for.

When I hard-code a random character that is not the character being checked for the expression is evaluated as false.

difficulty = ''

while difficulty not in 'EMH':
    print('Enter difficulty: E - Easy, M - Medium, H - Hard')
    difficulty = input().upper()

I expect to see the debugger enter the while loop. What actually happens is it continues past the while block without executing.

like image 559
walrath21 Avatar asked May 19 '19 07:05

walrath21


1 Answers

An empty string is present in any string. Therefore your condition, difficulty not in 'EMH' will evaluate to False when difficulty equals ''; so the while loop's body won't be executed.

In [24]: '' not in 'EMH'                                                                                                                                  
Out[24]: False

In [33]: '' in 'EMH'                                                                                                                                      
Out[33]: True

A better approach might be to convert the string EMH to a list via list('EMH') so that something like EM or EH, or a empty character doesn't break your loop, or avoid it from starting in the first place

Also as @Blckknght suggested, a better alternative is use a default value of None for difficulty.

In [3]: difficulty = None                                                                                                                                

In [4]: while difficulty not in list('EMH'): 
   ...:     print('Enter difficulty: E - Easy, M - Medium, H - Hard') 
   ...:     difficulty = input().upper() 
   ...:                                                                                                                                                   
Enter difficulty: E - Easy, M - Medium, H - Hard
A
Enter difficulty: E - Easy, M - Medium, H - Hard
B
Enter difficulty: E - Easy, M - Medium, H - Hard
C
Enter difficulty: E - Easy, M - Medium, H - Hard
EM
Enter difficulty: E - Easy, M - Medium, H - Hard
E

In [5]:      
like image 144
Devesh Kumar Singh Avatar answered Sep 21 '22 02:09

Devesh Kumar Singh