将函数结果存储到变量中

时间:2015-09-02 22:24:18

标签: python python-3.x

我试图将功能结果保存到变量var并在屏幕上打印变量var但是当我打印时我只看到文本" none"如何修复它。

import time;


def hours():
    localtime =  time.localtime(time.time())
    print (localtime.tm_hour)

def minutes():
    localtime =  time.localtime(time.time()) 
    print (localtime.tm_min)

def seconds():
   localtime =  time.localtime(time.time())     
   print (localtime.tm_sec)


hours()
minutes()
seconds()

var = hours()
print(var)

4 个答案:

答案 0 :(得分:6)

您需要返回一个将存储到变量中的值。

这样:

def myfunction():
    value = "myvalue"
    return value

var = myfunction()
print(var)

>>> "myvalue"

目前,您只是打印功能中的值,而不是返回它,这是两个不同的东西。

答案 1 :(得分:2)

您需要返回localtime.tm_hour而不是print

def hours():
    localtime =  time.localtime(time.time())
    print (localtime.tm_hour)
    return localtime.tm_hour

答案 2 :(得分:1)

您没有返回该值。该脚本应该:

import time;


def hours():
    localtime =  time.localtime(time.time())
    print (localtime.tm_hour)
    return localtime.tm_hour

In [11]: var = hours()
18
In [12]: print(var)
18

请参阅https://docs.python.org/3.5/tutorial/controlflow.html#defining-functions了解如何使用return。

答案 3 :(得分:0)

我能够通过函数定义中的return来使之工作

def hourMin ():
    localtime = time.localtime(time.time())
    return '{0}{1}{2}'.format(localtime.tm_hour, localtime.tm_min, localtime.tm_sec)

def dateDay ():
    localtime = time.localtime(time.time())
    return '{0}{1}{2}'.format(localtime.tm_mday, localtime.tm_mon, localtime.tm_year)

呼叫区域

def rannum ():
    for x in range(1):
        valo = random.randint(1,21)*5

    TimeHour = hourMin()
    TimeDate = dateDay()
    print ('Time is ' + str(hourMin()))
    path = "/tmp/temp/"
    curr = path + str(valo) + str(TimeDate)
    try:
        os.mkdir(curr)
    except:
        print('Creation of the directory %s failed' % path)
    else:
        print('Directory %s created ' % curr)

rannum()