PYTHON 2.7.3中的布尔运算符

15 浏览
0 Comments

PYTHON 2.7.3中的布尔运算符

我正在编写一个程序,需要向用户请求输入。我希望Python检查输入是否为数字(而不是单词或标点符号...),并且是否是表示我的元组中对象的数字。如果这3个条件中的任何一个结果为False,那么我希望用户为该变量提供另一个值。以下是我的代码:\n

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()

\n当我测试时,无论我输入什么内容,它都会不断地要求我插入height_measurement的输入。请检查我的代码并为我进行更正。如果方便的话,请给我提供你的更好的代码。\n注意:在下面提供的更好的代码中,我已经修正了一些拼写错误和逻辑错误。\n

colour = {'yellow': 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 = input('choose your height measurement: ').lower()
while not (hm_choice.isdigit() and int(hm_choice) > 0 and int(hm_choice) <= len(height_measurements)):
    hm_choice = input('choose your height measurement: ').lower()
print(weight_measurements)
wm_choice = input('choose your weight measurement: ').lower()
while not (wm_choice.isdigit() and int(wm_choice) > 0 and int(wm_choice) <= len(weight_measurements)):
    wm_choice = input('choose your weight measurement: ').lower()

\n在这个改进的代码中,我修正了以下问题:\n1. 将`yello`更正为`yellow`,以使其与字典`colour`中的键匹配。\n2. 将`raw_input`更正为`input`,因为在Python 3中,`raw_input`已被`input`取代。\n3. 将`hm_choce`更正为`hm_choice`,以修复拼写错误。\n4. 在`while`循环中,我更正了逻辑错误,以确保`hm_choice`和`wm_choice`是数字,并且在有效范围内。

0
0 Comments

在Python 2.7.3中,出现了一个关于布尔运算符的问题。问题的原因是在代码中的一行,hm_choice > 0 进行了一个字符串和整数的比较,这在Python中是未定义的,根据具体的实现可能等于True或者False。为了解决这个问题,可以将THE_OTHER_CONDITION = True放在代码中的第三个条件位置,这样代码就可以正常运行了。

代码中定义了一个字典colour和两个元组height_measurementsweight_measurements,然后打印出了height_measurements。接着使用一个无限循环,要求用户输入他们的身高测量单位,只有在输入了正整数并且THE_OTHER_CONDITIONTrue的情况下,才会跳出循环。然后打印出了weight_measurements,再次使用无限循环要求用户输入他们的体重测量单位,同样只有在输入了正整数并且THE_OTHER_CONDITIONTrue的情况下,才会跳出循环。

在代码中的最后,有一段对于"break"代码的疑问。"break"是用来跳出无限循环的,它是在Python中创建do-until循环的经典模式。

0
0 Comments

在Python 2.7.3中的布尔运算符问题的原因是,使用了一个字符串和整数进行比较。在Python中,字符串和整数是两种不同的类型,不能直接进行比较。所以当变量hm_choice是一个字符串时,将字符串与整数进行比较将始终返回True,导致while循环永远不会停止。所以问题是如何从字符串中获取整数。

解决方法是使用isdigit()方法来确保hm_choice是一个整数,然后使用int(hm_choice)将其转换为整数类型。这样就可以将字符串转换为整数,然后进行比较。

另外,还需要检查循环的逻辑。当前的循环逻辑是:当hm_choice不是一个数字时,或者当hm_choice大于0时(这是一个无效的语句),或者当hm_choice小于4(或元组的长度)时,循环将不会结束。如果其中任何一个条件为True,循环将不会结束。需要注意的是,其中一个条件始终为True。

总结起来,问题的原因是在Python 2.7.3中使用了字符串和整数进行比较,解决方法是使用isdigit()方法将字符串转换为整数,并检查循环的逻辑以确保循环可以正确结束。

0