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

2024-04-26 02:35:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图做到这一点,这样我的程序会不断地要求用户输入某个值,如果用户不输入,它会一直询问直到他们输入

我试着用“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")

Tags: the用户inputrawreturnifison
1条回答
网友
1楼 · 发布于 2024-04-26 02:35:39

问题是,在检查导致函数返回None的条件之后,您使用的是return,必须使用break而不是带有while循环的return来实现这一点。下面是验证和获取数据的更好方法

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)

上面的代码所做的是对params列表中的每一个param执行while循环检查在其验证器中定义的每一个验证条件,如果有效,它将中断while循环并继续到下一个param并再次重复相同的过程

相关问题 更多 >

    热门问题