繁体   English   中英

此代码未按我希望的方式打印-python

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

有了这段代码,我没有得到想要的显示。

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)

最后一行引起的问题是:

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

我希望结果格式为以下格式-现在总时间为:12:42:25

但我现在得到的是总时间:12:42:25无

但是当我将该行写为:

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

然后我得到的结果是-现在总时间是:12:42:25

当我不在print所在的行中编写printTime(time)函数时,不会出现None事情。

那么,这里到底发生了什么?

编辑:我尝试使用return语句,但结果仍然相同。 所以,我到底应该在哪里使用return语句。 也许我没有正确使用它。 我尝试这样做

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

但这会导致错误。

然后我尝试用这种方式-

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

仍然得到相同的结果。

您正在打印printTime()函数的返回值

Python中的所有函数都有一个返回值,如果不使用return语句,则该值默认为None

不用在printTime()函数中打印,而是printTime()函数重命名为formatTime()并让它返回格式化的字符串:

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

然后使用

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

上面的str.format()方法使用格式字符串语法 ,该语法引用传入的第一个参数( 0 ,python索引基于0),并从该参数插入属性。 第一个参数是您的time实例。

您可以对此进行扩展并添加更多格式,例如将数字零填充:

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

printTime返回一个打印函数调用,然后您尝试进行打印。

printTime更改为:

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

或者,更有效地:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM