Reputation: 429
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)
Upvotes: 3
Views: 78917
Reputation: 15393
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.
Upvotes: 20
Reputation: 3606
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()
Upvotes: 0
Reputation: 21
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.
Upvotes: 2
Reputation: 12577
You need to return localtime.tm_hour
not print
def hours():
localtime = time.localtime(time.time())
print (localtime.tm_hour)
return localtime.tm_hour
Upvotes: 4