[Tutor] (no subject)

Alan Gauld alan.gauld at yahoo.co.uk
Tue Dec 8 09:55:12 EST 2020


On 08/12/2020 07:27, KNOW NEW wrote:

> trying to create a program in which I want to print "Infinite" when divisor
> is 0. But when I divide by 0, it gives Infinite but also print None. 


When asking us to comment on code you should always include
the code (as plain text in your message body please)
Otherwise we are just guessing!

So making a guess I'd say you are working inside the Python
prompt and did something like this:

>>> def f(n,d):
	if d == 0:
		print( 'Infinity')
	else: return n/d

>>> print(f(5,0))
Infinity
None
>>>

You print infinity inside the function then the function
returns None(Python's default return value) and you see
both in your output. Is that right?

If so the good news is that you can avoid the None by
simply returning 'Infinity' as a string instead of printing
it inside the function.

That is also better programming practice since its better
not to mix printing and calculation inside the same function.

But, it's bad practice to return two different types(a string
and a float) so the professional way to deal with this is to
use a try/except as shown by DN.


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