Python 满足条件后,在循环过程中再运行一次
我正在制作一个面积计算器来帮助我理解Python的基础知识,但我想对它进行一些类型的验证——如果长度小于零,请再次询问。 我已经设法用形状函数中的“验证”代码(例如,在“正方形”函数中)来实现这一点,但当我将验证代码放在单独的函数“negativeLength”中时,它就不起作用了。这是我在单独函数中的代码:Python 满足条件后,在循环过程中再运行一次,python,loops,python-3.x,while-loop,Python,Loops,Python 3.x,While Loop,我正在制作一个面积计算器来帮助我理解Python的基础知识,但我想对它进行一些类型的验证——如果长度小于零,请再次询问。 我已经设法用形状函数中的“验证”代码(例如,在“正方形”函数中)来实现这一点,但当我将验证代码放在单独的函数“negativeLength”中时,它就不起作用了。这是我在单独函数中的代码: def negativeLength(whichOne): while whichOne < 1: whichOne = int(input('Please
def negativeLength(whichOne):
while whichOne < 1:
whichOne = int(input('Please enter a valid length!'))
def negativeLength(whichOne):
whichOne<1时:
whichOne=int(输入('请输入有效长度!'))
当我通过调用“negativeLength(Length)”来运行此函数时,它会再次询问长度(它应该这样做),但当我输入正长度时,条件满足,因此实际循环不会运行
我也尝试过(在以下内容之后)
def negativeLength(whichOne):
尽管如此:
whichOne=int(输入('请输入有效长度!'))
如果whichOne<1:
打破
。。。但这也不行
我把参数设为“whichOne”,因为圆的“长度”叫做半径,所以我把它叫做negativeLength(Radius),而不是正方形的negativeLength(length)
那么有没有办法让whichOne=int(输入…)之后的while循环完成呢
编辑:我正在使用Python3.3.3您编写的代码可以正常工作。但是,它实际上不会做任何有用的事情,因为
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)
def负_长度(x):
当x<0时:
x=int(输入('为负。请输入非负长度:'))
返回x
x=输入('输入长度:')
x=负长度(x)
我假设您使用的是Python 3。如果不是,则需要使用原始输入()而不是输入()
我通常使用的代码如下所示:
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
它应该做你想做的。准确地查看你从中调用它的代码是什么样子是很有帮助的。我怀疑您试图通过引用传递
长度
和半径
,这样它们就永远不会被设置。@bytbox这就是我所说的:print('正方形的一条边的长度,单位为cm?')Length=int(输入())negativeLength(长度)Area=Length*Length return Area
非常感谢,我不知道您可以同时调用函数和定义函数-您真的帮了忙,我如何将此标记为已回答?这是我第一次来这里stackoverflow@shub我甚至不知道该怎么查:)但看起来你已经知道了。
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