[Tutor] python coding problem

Alan Gauld alan.gauld at yahoo.co.uk
Mon Sep 26 14:26:58 EDT 2016


On 26/09/16 16:35, Richard Koeman wrote:

> The function prints the first two print statements then nothing else
> happens.
> 
> def maximum(n1, n2):
>   print "the first number is" ,n1
>   print "the second number is", n2

We know this works so far, so that's fine.

>   if n1 > n2:
>     return

But this returns no value (so Python will provide a value of None)
and immediately exits the function, no further processing will happen.
But in your test you use 1,2 so this bit of code never gets executed
anyway, so its not your problem(yet).

>     print n1 , "is the bigger number"

Becauyse you used return this print will never, ever be executed.

>   elif n1 < n2:

Given 1,2 this should be where your code goes.

>     return n2

And straight away you return 2, so nothing beyond here gets executed.

>     print n2

ie. This is never executed

>   elif n1 == n2:
>     print "they are equal"

You print a message but don;t return anything so Python
by default returns None.

>   else:
>     print "Sorry, No response found"

Same here, None gets returned.

So your function returns None for any set of values except where the
second is largest, in which case it returns the second.

> maximum(1,2)

So here we should see
the first 2 print outputs
the returned value 2 but only if you execute this in a Python
interactive shell. If you put it in a file and try running
it you will not see the 2. Try adding a print before the call to maximum:

print(maximum(1,2)

That will then print the 2 as well.

BTW As a matter of good style it's better not to mix print
and returns inside a function. Either it returns a value
and the calling function can print the result or it just
prints stuff and never returns anything. This is because
if you try using a function like yours in, say, a sorting
program you will get a lot of printed information that's
irrelevant to the sorting program.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list