[英]How can I make it so that the program loops until the conditions are met?
I was trying to make it so that my program will keep asking the user to input a certain value and if the user doesn't it keeps asking until they do. 我试图这样做,以便我的程序将继续要求用户输入一定的值,如果用户没有,它会一直询问,直到他们这样做。
I tried to use "while" instead of "if" but I know I'm probably missing something, somewhere. 我试图使用“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")
The problem is you are using return
after checking the condition which causes the function to return None
you have to use break
instead of return
with while loop instead of if
to achieve this. 问题是你在检查导致函数返回的条件后使用
return
None
你必须使用break
而不是使用while循环return
而不是if
来实现这一点。 A better way to validate and get data is below 下面是验证和获取数据的更好方法
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)
What the above code does is for every param
in params
list it runs a while loop checking for every validation condition defined in its validator if valid it breaks the while loop and proceeds to next param
and repeats the same process again 上面的代码所做的是对于
params
列表中的每个param
,它运行一个while循环检查其验证器中定义的每个验证条件,如果有效则它会中断while循环并继续下一个param
并再次重复相同的过程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.