Python根据输入创建while循环

时间:2014-12-17 01:41:18

标签: python

所以在过去一小时左右的时间里,我一直在努力工作。我想添加一个while循环,让用户回到开始时,他们输入的东西不是数字。但是我不知道从哪里开始。我一直在尝试各种各样的东西,但似乎没有什么对我有用。

try:
    length=float(raw_input("Insert Length of room"))
except ValueError:
    print "That's not a number try again"
try:
    width=float(raw_input("Insert Width of room"))
except ValueError:
    print "That's not a number try again"
else:
    cost=(width*length)*3.99
 print cost

4 个答案:

答案 0 :(得分:0)

您可以使用whilebreak

length = 0
while True:
    try:
        length = float(raw_input("Insert Length of room: "))
        break
    except ValueError:
        print "That's not a number try again"

# You'll have a valid float in length at this point
print(length)

答案 1 :(得分:0)

你可以这样做:

dimensions = ['Length', 'Width']
values = []

for dimension in dimensions:
    while True:
        try:
            v = float(raw_input("Insert {} of room: ".format(dimension)))
            values.append(v)
            break
        except ValueError:
            print "That's not a number try again"

length, width = values

cost = (width * length) * 3.99
print cost

已修改以了解更新的要求。

答案 2 :(得分:0)

如果要检查多个输入,可以定义一个函数来获取输入并进行检查:

def numeric_input(message, numeric_type=float):
    while True:
        try:
            return numeric_type(raw_input(message))
        except ValueError:
            print "That isn't a valid number! Try again."

然后:

length = numeric_input("Insert Length of room")
width = numeric_input("Insert Width of room")
cost = (width*length)*3.99
print cost

这样,如果用户给出了长度的数字,但宽度有一些非数字输入,程序不会要求用户再次输入长度,只有宽度。

答案 3 :(得分:-1)

你可以这样做:

while True:
    try:
        length = float(raw_input("Insert Length of room: "))
    except ValueError:
        print "That's not a number try again"
    else:
        break

如果您有多个问题,可以执行以下操作:

in_data = {
           'length': ['Insert Length of room: ', -1], # the -1 is placeholder for user input
           'width': ['Insert Width of room: ', -1], 
           }


for k,v in in_data.items():
    while True:
        try:
            user_data = float(input(v[0]))            
        except ValueError:
            print("That's not a number try again")
        else:
            v[1] = user_data
            break

print(in_data)   
# example output: {'width': ['Insert Width of room: ', 7.0], 'length': ['Insert Length of room: ', 8.0]}