在条件满足后多执行一次while循环
我正在做一个面积计算器,想通过这个项目来学习Python的基础知识。不过,我想在程序中加一些验证功能,比如如果输入的长度小于零,就让用户重新输入。
我已经在形状的函数里面(比如'square'函数)实现了这个验证功能,但当我把验证代码放到一个单独的函数'negativeLength'里时,它就不工作了。下面是我在这个单独函数里的代码:
def negativeLength(whichOne):
while whichOne < 1:
whichOne = int(input('Please enter a valid length!'))
当我通过调用'negativeLength(Length)'来运行这个函数时,它会让我重新输入长度(这本来是应该的),但是当我输入一个正数时,条件就满足了,所以实际的循环就没有执行。
我也尝试过(在参考了如何在Python中模拟do-while循环?之后)
def negativeLength(whichOne):
while True:
whichOne = int(input('Please enter a valid length!'))
if whichOne < 1:
break
...但那也不行。
我把参数命名为'whichOne',因为圆的'长度'叫做半径,所以我会用negativeLength(Radius)来调用,而不是negativeLength(Length)用于正方形。
那么有没有办法让while循环在'whichOne = int(input...)'之后结束呢?
补充:我使用的是Python 3.3.3
2 个回答
0
我假设你是在用Python 3。如果不是的话,你需要用raw_input()而不是input()。
我通常用的代码大概是这样的:
def negativeLength():
user_input = raw_input('Please enter a length greater than 1: ')
if int(user_input) > 1:
return user_input
input_chk = False
while not input_chk:
user_input = raw_input('Entry not valid. Please enter a valid length: ')
if int(user_input) > 1:
input_chk = True
return user_input
这段代码应该能满足你的需求。
1
你写的代码在某种程度上是能工作的。不过,它实际上没有什么用,因为whichOne
这个值并没有返回给调用这个函数的地方。请注意,
def f(x):
x = 2
x = 1
f(x)
print(x)
这段代码会打印出1,而不是2。你应该这样做:
def negative_length(x):
while x < 0:
x = int(input('That was negative. Please input a non-negative length:'))
return x
x = input('Enter a length:')
x = negative_length(x)