Python Returning None?

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

Posts: 1
Joined: Tue Sep 18, 2012 6:14 am UTC

Python Returning None?

Postby 1337 » Tue Sep 18, 2012 6:49 am UTC

Having problems with a python script. Could anyone tell me why this is returning a None statement when I call this function?

Code: Select all

def power():
    x = int(raw_input('Enter a number: '))
    y = int(raw_input('Enter the power: '))
    c = 0
    if x < 0:
        print 'The number you entered', x, 'is a negative number'
    elif x == 0:
        print 'You can\'t use', x, 'as the number'
        c = x**y
        return c

print power()


Code: Select all

Enter a number: 0
Enter the power: 5
You can't use 0 as the number

Any help would be appreciated...

User avatar
My HERO!!!
Posts: 5388
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex

Re: Python Returning None?

Postby Xanthir » Tue Sep 18, 2012 8:07 am UTC

Because it automatically returns None if you don't tell it to return something else. Your code only explicitly returns a value in the "good" case - in the others, it just prints something, and then exits the if stack and sees the end of the function, which causes it to infer a "return None;" at the end.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

User avatar
Posts: 414
Joined: Fri Apr 21, 2006 8:19 pm UTC

Re: Python Returning None?

Postby Mat » Tue Sep 18, 2012 8:08 am UTC

Yup. Printing is not the same as returning a value from a function. It is just a side effect that calling the function has.

If x is 0 or below, there are no return statements, so the return value is None.

A more pythonic way would be to handle your bad input using exceptions, like this

Code: Select all

def power():
  if x <= 0:
    raise ValueError()

  print power()
except ValueError:
  print 'you're doing it wrong'

Return to “Coding”

Who is online

Users browsing this forum: No registered users and 4 guests