在这个时钟中,我首先要求用户输入时间,但是它不会在变量中返回时间。我得到了
Traceback (most recent call last):
File "C:/Documents and Settings/Brett/My Documents/Programming/Python/clock.py", line 20, in <module>
print(hour,":",mins,":",sec)
NameError: name 'hour' is not defined
我知道设定时间部分dosnt需要是一个功能但我想稍后使用它。
import time
def setTime():
print("Set time \n--------")
time=input("24 hour or 12 hour \nType 1 or 2: ")
if time=="2": hour12=input("AM or PM \nType 1 or 2: ")
else: hour12=0
hour=input("Hour: ")
mins=input("Minute: ")
print("--------")
sec=0
return time,hour12,hour,mins,sec
def printTime24():
print(hour,":",mins,":",sec)
#def printTime12():
setTime()
print(hour,":",mins,":",sec)
while True:
time.sleep(1)
sec+=1
if sec == 60:
sec=0
mins+=1
if mins == 60:
mins=0
hour+=1
if time=="1": printTime24()
# elif time=="2": printTime12()
答案 0 :(得分:3)
return
语句返回值,而不是变量。如果没有对返回的值进行任何操作,则会丢弃它们。
您调用setTime()
但不对其返回的值执行任何操作。
您需要以新名称存储返回的值:
time, hour12, hour, mins, sec = setTime()
我使用了与setTime()
函数本身相同的名称,但我也可以给它们不同的名称:
foo, bar, baz, spam, eggs = setTime()
然后在其余代码中使用这些名称:
print(baz, ":", spam, ":", eggs)