None shown in output
Dan Sommers
dan at tombstonezero.net
Fri Jun 22 00:15:25 EDT 2012
On Fri, 22 Jun 2012 11:42:28 +0800
Xander Solis <xrsolis at gmail.com> wrote:
> Noob here with a newbie question. I'm reading and working on the
> exercise of the book, Learn Python the Hard way 2.0. When I use this
> code, I get "None" on the output. My question is why does this happen?
>
> def get_numbers(first_num, second_num, operator):
>
> if operator == 'add':
> print first_num + second_num
> elif operator == 'minus':
> print first_num - second_num
> elif operator == 'divide':
> print first_num / second_num
> elif operator == 'multiply':
> print first_num * second_num
This function prints a result, but doesn't return anything.
> print "%r" % (get_numbers(1, 2, 'minus'))
> print "%r" % (get_numbers(1+3, 2+9, 'add'))
> print "%r" % (get_numbers(10, 2, 'divide'))
This:
(get_numbers(1, 2, 'minus'))
calls get_numbers and evaluates to None (because get_numbers doesn't
return anything).
Then this:
"%r" % (get_numbers(1, 2, 'minus'))
formats that None into the string "None."
Finally, this:
print "%r" % (get_numbers(1, 2, 'minus'))
prints that string.
> Output:
>
> C:\code\python>ex19.py
> -1
This "-1" comes from get_numbers.
> None
This "None" comes from the print statement that called get_numbers.
Contrast your code with this snippet:
def add(x, y):
return x + y
print "%r" % (add(3, 2))
HTH,
Dan
--
Μὴ μοῦ τοὺς κύκλους τάραττε -- Αρχιμηδησ
Do not disturb my circles. -- Archimedes
Dan Sommers, http://www.tombstonezero.net/dan
More information about the Python-list
mailing list