others - python -"not in"在检查某些字符的空字符串时不工作

检查是否使用某些字符填充空字符串变量时,表达式始终计为true。如果新创建的字符串值为空,则它应该为false,它不包含任何字符,更不用说要检查的字符。


difficulty = ''



while difficulty not in 'EMH':


 print('Enter difficulty: E - Easy, M - Medium, H - Hard')


 difficulty = input().upper()



时间:

任何字符串中都存在空字符串,所以你的条件 difficulty not in 'EMH'difficulty等于''时,将计算为False ; 因此,循环体不会被执行。


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


Out[24]: False



In [33]: '' in 'EMH' 


Out[33]: True



更好的方法可能是通过list('EMH')将字符串EMH转换为列表,以便类似EMEH或空字符,

更好的替代方法是使用None的默认值。


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]: 



我认为你需要使用的是一个列表,而不是一个字符串:


difficulty = ''



while difficulty not in ['E','M','H']:


 print('Enter difficulty: E - Easy, M - Medium, H - Hard')


 difficulty = input().upper()



这对于do-while条件是一个很好的例子,但是,python没有它,请检查下面的样式是否适合你:


while True:


 print('Enter difficulty: E - Easy, M - Medium, H - Hard')


 difficulty = input().upper()


 if difficulty not in 'EMH': #or in ['E', 'M', 'H']


 continue


 else:


 #do some logic


 break



...