[Tutor] Codehelp: confused by the output in IDLE

Alan Gauld alan.gauld at freenet.co.uk
Fri Dec 16 12:45:01 CET 2005

> def funcA(x): # function describiing the oddness or eveness of an x number
>  if x%2 == 0:
>    print x, "is even"
>  else:
>    print x, "is odd"

>def funcB(y): # function describiing the oddness or eveness of an y number
>  if y%2 ==0:
>    print y, "is even"
>  else:
>    print y, "is odd"

These two functions are identical. What you call the parameter is irrelevant 
the outside world its only a local name inside the function!  Neither 
returns a value so Python will silently return the special value 'None'

Also its usually a bad idea to do the printing of results inside the 
function, its
better to return the result and let the caller display the result. Thus a 
solution here is probably:

def isOdd(x):
   return x % 2

Now you can do things like:

x = int(raw_input('Type a number: '))
y = int(raw_input('Type a number: '))
if isOdd(x):
   print x, ' is odd'
else: print x, ' is even'
if isOdd(y):
   print y, ' is odd'
else: print y, ' is even'

> *if x>y:
>     print x,("is greater than"),y
> else:
>     print y,("is greater than"),x*
> *if y and x >=0:
>     print ("Both are positive numbers!")*

This doesn't work because Python will evaluate it like:

if y
   if x >=0:
     print ...

you need to use

if y >=0 and x >= 0
   print ...

> *print funcA(x)
> print funcB(y)*

Because your functions don't retuirn any value Python returns None.
So that is the value that you print. Thats why its probably better to
return the result of the test and lat your calling program display the
result as described above.

> 10 is greater than 5
> Both are positive numbers!

This is because of the incorrect if test

> 5 is odd

This is printed inside the function

> None

And this is what was returned by the function

> 10 is even
> None*

and the same here


Alan G
Author of the learn to program web tutor

More information about the Tutor mailing list