python2.7.3中的布尔运算符

2024-04-19 15:10:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,在这个程序中我请求用户输入。在

我希望python检查输入是否是digit(不是单词或puntuation…),以及它是否是一个表示元组中某个对象的数字。如果3个条件中的一个导致False,那么我希望用户为该变量提供另一个值。这是我的密码

colour={'yello':1, 'blue':2, 'red':3, 'black': 4, 'white': 5, 'green': 6}
height_measurements=('centimeter:1', 'inch:2', 'meter:3', 'foot:4')
weight_measurements=('gram:1', 'kilogram:2', 'pounds:3')
print height_measurements
hm_choice = raw_input('choose your height measurement').lower()
while not hm_choice.isdigit() or hm_choice > 0 or hm_choice < len(height_measurements) :
    hm_choice = raw_input('choose your height measurement').lower()        
print weight_measurements
wm_choice = raw_input('choose your weight measurement').lower()
while not wm_choice.isdigit() or wm_choice > 0 or wm_choce < len(weight_measurements) :
    wm_choice = raw_input('choose your weight measurement').lower()

当我把这个测试时,不管我输入什么,它总是让我不断地插入高度测量的输入

请检查我的代码并为我更正。如果你愿意,请给我提供你的更好的代码。在


Tags: or用户程序inputyourrawlowermeasurement
2条回答

When I put this to test, it kept making me insert input for height_measurement constantly no matter what I put in

这是因为hm_choice > 0是字符串和int之间的比较,它是undefined,根据实现的不同可以等于True或{}。在

我不太明白第三个条件的含义,所以我把THE_OTHER_CONDITION放在那里。如果您定义THE_OTHER_CONDITION = True,那么代码就可以工作了。在

colour={'yello':1, 'blue':2, 'red':3, 'black': 4, 'white': 5, 'green': 6}
height_measurements=('centimeter:1', 'inch:2', 'meter:3', 'foot:4')
weight_measurements=('gram:1', 'kilogram:2', 'pounds:3')

print height_measurements
while True:
    hm_choice = raw_input('choose your height measurement: ').lower()
    if (hm_choice.isdigit() and int(hm_choice) > 0 and THE_OTHER_CONDITION):
        break

print weight_measurements
while True:
    wm_choice = raw_input('choose your weight measurement: ').lower()
    if (wm_choice.isdigit() and int(hm_choice > 0) and THE_OTHER_CONDITION):
        break

我不会完全为您修改代码,但我会向您解释一些您似乎很困惑的东西。在

raw_input返回一个字符串。字符串和整数是两种类型,不能相互比较(即使在python2this is does not raiseaTypeError)中也是如此。所以您的变量hm_choice是一个字符串,使用isdigit方法确保它是一个整数是正确的。然而,然后将字符串与整数进行比较,在这些条件之一下,该整数的计算结果始终为True,这意味着while循环永远不会停止。所以我提出这个问题:如何从字符串中得到整数?

接下来,您需要检查该循环的逻辑。你的意思是:While hm_choice不是数字,Whilehm_choice大于0(我们已经知道这是一个无效语句),或者Whilehm_choice小于4(或元组的长度)。在

所以如果其中任何一个是真的,那么循环就不会结束。如果你读了我上面链接的那篇文章,你会发现哪一个总是正确的。;)

相关问题 更多 >