Python:带有while循环的函数在末尾返回None。我该如何补救?
我正在做一项调查 我的代码的主要问题是我的函数在while循环中不返回任何值 我知道我可以通过这个练习,不把它当作一个函数来使用,但我个人的目标是保持它作为一个函数。有没有一种方法可以让我的代码作为一个函数而不返回一个函数 我的代码Python:带有while循环的函数在末尾返回None。我该如何补救?,python,function,loops,while-loop,Python,Function,Loops,While Loop,我正在做一项调查 我的代码的主要问题是我的函数在while循环中不返回任何值 我知道我可以通过这个练习,不把它当作一个函数来使用,但我个人的目标是保持它作为一个函数。有没有一种方法可以让我的代码作为一个函数而不返回一个函数 我的代码 def cutOperation(sticks): currentLine = sticks while len(currentLine) != 0: newLine = [] print len(currentLin
def cutOperation(sticks):
currentLine = sticks
while len(currentLine) != 0:
newLine = []
print len(currentLine)
for stick in currentLine:
if stick - min(currentLine) != 0:
newLine.append(stick - min(currentLine))
currentLine = newLine
_ = int(raw_input().strip())
sticks = map(int,raw_input().strip().split(' '))
#First Test Case for sticks = 5 4 4 2 2 8
print cutOperation(sticks)
6
4
2
1
None
#How do I not return none?
运行代码后的结果
def cutOperation(sticks):
currentLine = sticks
while len(currentLine) != 0:
newLine = []
print len(currentLine)
for stick in currentLine:
if stick - min(currentLine) != 0:
newLine.append(stick - min(currentLine))
currentLine = newLine
_ = int(raw_input().strip())
sticks = map(int,raw_input().strip().split(' '))
#First Test Case for sticks = 5 4 4 2 2 8
print cutOperation(sticks)
6
4
2
1
None
#How do I not return none?
与上面的注释中提到的其他语句一样,您可以添加一个return语句,并为函数返回您想要的任何内容。对于未指定return语句的函数,Python默认返回
None
但是,如果您不想在本练习中打印“无”,只需更改:
print cutOperation(sticks)
到
由于您的最后一行正在打印
cutOperation
函数的返回值。Uh,return
某些明确的内容?将return'
放在函数定义的末尾将不会打印任何内容,只需调用函数,不要打印它,例如cutOperation(sticks)