faraz
faraz

Reputation: 2733

this code isn't printing as I want it to - python

With this code,I am not getting the kind of display I want.

def printTime(time):
    print time.hours,":",time.minutes,":",time.seconds,

def makeTime(seconds):
    time = Time()
    print "have started converting seconds into hours and minutes"
    time.hours = seconds/3600
    print "converted into hours and no.of hours is :",time.hours
    seconds = seconds - time.hours *3600
    print "number of seconds left now:",seconds
    time.minutes = seconds/60
    print "number of minutes now is :",time.minutes
    seconds = seconds - time.minutes*60
    print "number of seconds left now is :",seconds
    time.seconds = seconds
    print "total time now is:",printTime(time)

The last line is causing the problem that is:

print "total time now is:",printTime(time)

I want the result to be in the format below- total time now is : 12:42:25

but what i get is total time now is : 12:42:25 None

but when I write that line as:

print "total time now is:"
printTime(time)

then i get the result as - total time now is : 12:42:25

The None thing doesn't appear when I dont write the printTime(time) function in the same line as print.

So,what's really happening here?

EDIT: I tried using the return statement, but the result was still the same. so,where exactly should I use the return statement. maybe i was using it incorrectly . i tried doing it as

print "total time now is:",return printTime(time)

but this gives an error.

then I tried doing it this way -

print "total time now is:",printTime(time)
return printTime(time)

still get the same result.

Upvotes: 1

Views: 554

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123340

You are printing the return value of the printTime() function.

All functions in Python have a return value, and if you don't use a return statement, that value defaults to None.

Instead of printing in the printTime() function, rename that function to formatTime() and have it return the formatted string:

def formatTime(time):
    return '{0.hours}:{0.minutes}:{0.seconds}'.format(time)

then use

print "total time now is:",formatTime(time)

The str.format() method above uses a format string syntax that refers to the first parameter passed in (0, python indexing is 0-based), and interpolates attributes from that parameter. The first parameter is your time instance.

You can expand on that and add some more formatting, such as zero-padding your numbers:

def formatTime(time):
    return '{0.hours:02d}:{0.minutes:02d}:{0.seconds:02d}'.format(time)

Upvotes: 4

Chad
Chad

Reputation: 1864

printTime is returning a print function call, which you're then trying to print.

Change printTime to:

return time.hours + ":" + time.minutes + ":" + time.seconds

Or, more efficiently:

return "%s:%s:%s" % (time.hours, time.minutes, time.seconds)

Upvotes: 1

Related Questions