Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: My function returns "None" after it does what I want it to [duplicate]

Tags:

python

Here is my program

def reverse(letters):
    backwards = ""
    i = len(letters) - 1
    while i >= 0:
        backwards = backwards + letters[i]
        i = i - 1
    print (backwards)

print (reverse("hello"))

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.

like image 635
user2832964 Avatar asked Oct 01 '13 00:10

user2832964


1 Answers

function return None by default, so you should return backwards explicitly

also, you can use a pythonic way to solve the problem:

letters[::-1]
like image 124
liuzhijun Avatar answered Oct 20 '22 17:10

liuzhijun