[英]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.编辑:另请注意,当没有 return 指令时,默认返回值为
None
。
You need to return localtime.tm_hour
not print
您需要返回
localtime.tm_hour
不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.有关如何使用 return 的信息,请参阅https://docs.python.org/3.5/tutorial/controlflow.html#defining-functions 。
I able to make this working with return within function definition我能够在函数定义中使用 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)
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.