如何使程序循环直到满足条件?

时间:2019-04-13 14:34:42

标签: python loops

我试图做到这一点,以便我的程序将继续要求用户输入某个值,如果用户没有输入,则继续询问直到他们输入。

我尝试使用“ while”代替“ if”,但我知道我可能在某处缺少了某些内容。

def terrain(surface):
    surface = raw_input("What surface will you be driving on? ")
    if surface == "ice":
                u = raw_input("what is the velocity of the car in meters per second? ")
                u = int(u)
                if u < 0:
                    u = raw_input("Velocity must be greater than 0")
                    return
                if u == 0:
                    u = raw_input("Velocty must be a number greater than zero")
                    return
                a = raw_input("How quickly is the vehicle decelerating? ")
                a = int(a)
                if a > 0:
                    print ("Deceleration cannot be a positive integer")
                    return
                else: 
                        s1 = u**2
                        s2 = 2*.08*9.8
                    s = s1/s2
                    print "This is how far the vehicle will travel on ice: "
                    print ("The vehicle will travel %i meters before coming to a complete stop" % (s))
terrain("ice")

1 个答案:

答案 0 :(得分:0)

问题是您在检查导致函数返回return的条件后使用None,而必须使用break代替return并使用while循环代替if实现这一目标。下面是一种更好的验证和获取数据的方法

class ValidationError(Exception):
    pass

def validate_and_get_data_count(x):
    if int(x) < 0:
        raise ValidationError("Cannot be less than 0")
    return int(x)

def validate_and_get_data_name(x):
    if len(x) < 8:
        raise ValidationError("Length of name cannot be less than 8 chars")
    elif len(x) > 10:
        raise ValidationError("Length of name cannot be greater than 10 chars")
    return x

validators = {
    "count": validate_and_get_data_count,
    "name": validate_and_get_data_name
}

data = {}

params = [
    ("count","Please enter a count: "),
    ("name","Please enter a name: "),
]

for param in params:
    while True:
        x = input(param[1])
        try:
            data[param[0]] = validators[param[0]](x)
            break
        except ValidationError as e:
            print(e)

print(data)

上面的代码针对param列表中的每个params进行操作,它对验证器中定义的每个验证条件运行一次while循环检查,如果有效,它将打破while循环并继续进行下一个{{ 1}},然后再次重复相同的过程