【问题标题】:boolean operators in PYTHON 2.7.3 [closed]PYTHON 2.7.3 中的布尔运算符 [关闭]
【发布时间】:2012-12-21 12:07:04
【问题描述】:

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

我希望 python 检查输入是否是数字(不是单词或标点符号......),以及它是否是一个数字,表示我的元组中的一个对象。如果 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()

当我对此进行测试时,无论我输入什么,它都会不断地让我为 height_measurement 插入输入

请检查我的代码并为我更正。另外,如果您愿意,请为我提供更好的代码。

【问题讨论】:

  • not 的优先级高于 or。使用括号。

标签: python python-2.7 boolean-logic


【解决方案1】:

我不会为你完全修复你的代码,但我会向你解释一些你似乎感到困惑的事情。

raw_input 返回一个字符串。字符串和整数是两种类型,不能相互比较(即使在 python 2 this is does not raise a TypeError 中)。所以你的变量 hm_choice 是一个字符串,你正确地使用 isdigit 方法来确保它是一个整数。但是,您随后将一个字符串与一个整数进行比较,该整数在其中一种条件下总是评估为 True,这意味着 while 循环永远不会停止。所以我向你提出这个问题:如何从字符串中获取整数?

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

因此,如果其中任何一个为 True,则循环不会结束。如果您阅读我上面链接的文章,您会弄清楚其中哪些总是评估为 True。 ;)

【讨论】:

  • 非常感谢!你的回答让我受益匪浅。你在那里写的正是发生的事情!我现在明白为什么程序一直要求输入。但是,我仍在处理您向我提出的问题“如何从字符串中获取整数”。我原以为当用户输入一个数字时,Python 会将其作为一个数字对象,因此提供对数字起作用的方法和运算符。
  • 由于您似乎卡住了,如果您查看@jary 的答案,您会看到他接受hm_choice 并调用int(hm_choice) 假设hm_choice 是一个整数(您保证通过放置@987654332 @first) 它会为你返回一个整数。
【解决方案2】:

当我对此进行测试时,它一直让我插入输入 无论我放入什么,高度测量都会持续

这是因为 hm_choice &gt; 0 是字符串和 int 之间的比较,即 undefined 并且可以等于 TrueFalse,具体取决于实现。

我不太明白第三个条件的含义,所以我只是将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

【讨论】:

猜你喜欢
  • 2016-08-16
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多