Python:我的函数返回“无"在它完成我想要它做的事之后 [英] Python: My function returns "None" after it does what I want it to
问题描述
这是我的程序
def reverse(letters):
backwards = ""
i = len(letters) - 1
while i >= 0:
backwards = backwards + letters[i]
i = i - 1
print (backwards)
print (reverse("hello"))
它有效,它打印出olleh",但之后,它在新行上打印None".我在问为什么会这样.显然程序是反转一个单词,代码有效,没有函数它不打印none,所以我不知道为什么它在函数中.这是在另一个更大的程序中使用的,所以我需要它作为一个函数,因为它是用于学校的,我不能简单地使用 .reverse() 函数.所以如果可能的话,我真的需要修复这个代码而不是大的改变.
It works, it prints out "olleh" but after, it prints "None" on a new line. And I'm asking why this is. Obviously the program is to reverse a word, the code works, and without a function it doesn't print none, so I don't know why it does in the function. This is being used in another larger program, so I need it as a function, and because it's for school, I'm not allowed to simply use the .reverse() function. So I really need this code fixed rather than large changes, if possible.
推荐答案
function return None
默认情况下,所以你应该return backs
明确
function return None
by default, so you should return backwards
explicitly
另外,你可以使用pythonic的方式来解决这个问题:
also, you can use a pythonic way to solve the problem:
letters[::-1]
这篇关于Python:我的函数返回“无"在它完成我想要它做的事之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!