简体   繁体   中英

Store function result into variable

I am trying to save the result of a function into a variable and print that variable on the screen, but when I print I see "none".
How to repair this?

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)

You need to return a value that will be stored into the variable.

This way :

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

var = myfunction()
print(var)

>>> "myvalue"

Currently you're just printing the value in your function, not returning it , that's two different things.

Edit: Also note that the default returned value is None when there is no return directive.

You need to return localtime.tm_hour not print

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

You are not returning the value. The script should do:

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

see https://docs.python.org/3.5/tutorial/controlflow.html#defining-functions for how to use return.

I able to make this working with return within function definition

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)

Calling area

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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