我对Python很陌生,我正试图为单个变量实现多个或多个条件。我想知道和理解以下几种形式的最佳方式:
if ((word < 1) | (word > 10)):
print "\n\n\nThe word entered is not valid!"
print "Words that are valid are 1,2,7,8,9 and 10"我想把“1”和数字5-10比较一下。会不会是类似于:
if ((word < 1) | (word > 10) and (word < 1) | (word >9) and (word < 1) and etc...):
print "The word entered is not valid!"
print "Words that are valid are between 1,2,7,8,9 and 10"号码1、2、7、8、9和10有效。数字3、4、5和6必须检查为小于“word”的变量。
我该怎么做?
发布于 2016-01-06 17:53:53
在Python中,|是按位的--或者。你想:
if word < 1 or word > 10:根据问题更新,下面是检查一组特定值的一种方法:
if word not in (1,2,7,8,9,10):
print('invalid')等效和(或)逻辑是:
if word < 1 or (word > 2 and word < 7) or word > 10:
print('invalid')但是你可以看到not in的方式更简单。
发布于 2016-01-06 18:13:39
if word < 1 or word == 10 or word > 15 or word == 11:
print 'All will be considered'就像前面提到的,你也能做到。
if word in (1,2,3,4,5,6,7):
<do something>或者在范围内。
if word in range(0,10):
<do something>如果其中任何一个是真的,也会是真的。如果所有这些都是真的。
发布于 2016-01-06 18:18:20
除了@mark-tolonen的答案之外,还有几种方法可以检查一个数字的范围是否小于某个值。一种方法是显式地使用循环:
less_than_word = True
for i in range(5, 10):
if i > word:
less_than_word = False
break
print('All values < word: {}'.format(less_than_word))或者,您可以使用all()和map()的组合来解决这个问题(但是,如果您对python还不熟悉,那么您可以找到all()和map() 这里的文档):
less_than_word = all(map(lambda x: x < word, range(5, 10)))
print('All values < word: {}'.format(less_than_word))另一种选择是检查数字序列中最大的元素(在您的示例中为5-10)是否小于word。如果是这样的话,它们都小于word,如果不是,那么就不是。
https://stackoverflow.com/questions/34639375
复制相似问题