ttr*_*204 0 python boolean-logic python-2.7
我正在编写一个程序,我要求用户输入.
我希望python检查输入是否为数字(不是单词或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()
Run Code Online (Sandbox Code Playgroud)
当我把它测试时,无论我放入什么,它都会让我不断地为height_measurement插入输入
请检查我的代码并为我更正.如果你愿意,请为我提供更好的代码.
我不会完全修复你的代码,但我会向你解释一些你似乎感到困惑的事情.
raw_input
返回一个字符串.字符串和整数是两种类型,不能相互比较(即使在python 2中这不会引起一个TypeError
).所以你的变量hm_choice
是一个字符串,你使用该isdigit
方法确保它是一个整数是正确的.但是,您正在将一个字符串与一个整数进行比较,该整数在其中一个条件中总是计算为True,这意味着while循环永远不会停止.所以我向你提出这个问题:如何从字符串中获取整数?
接下来,您需要检查该循环的逻辑.你说的是:虽然hm_choice
不是数字或者hm_choice
大于0(我们已经知道这是一个无效的语句)或者hm_choice
小于4(或者你的元组的长度).
因此,如果其中任何一个为True,那么循环将不会结束.如果您阅读我上面链接的文章,您将找出其中哪些始终评估为True.;)