我是 Python 新手,正在学习
time
模块。我正在摆弄模块,试图编写一个程序,根据用户的输入输出 UTC 或当地时间,但是当我运行该程序时,newtime = input("Would you like to see Local or UTC time? ")
会执行,但不会执行 if 语句。
import time
newtime = input("Would you like to see Local or UTC time? ")
#newtime stores user input
if newtime.lower == "utc":
#If newtime lowercase equals to utc this if line will run
print(time.strftime("The current time and date in UTC is: %c ", time.gmtime()))
#strftime formats the struct_time from gmtime() into something more readable
elif newtime.lower == "local":
#If newtime lowercase equals to local this elif line will run
print(time.strftime("The current time and date in local is: %c", time.localtime()))
#strftime formats the struct_time from localtime() into something more readable
else:
print("Input not recognized, please type 'Local' or 'UTC'")
#If neither local or utc are inputed this prints
我认为问题可能是
newtime
,但事实并非如此。我最初有 newtime = input("Would you like to see Local or UTC time? ").lower
,因为我是编程新手,但也不是这样。
您需要在 if 语句中调用函数:
newtime = input("Would you like to see Local or UTC time? ")
if newtime.lower() == "utc":
...
elif newtime.lower() == "local":
...
else:
...
否则你只是在做:
if str.lower == 'utc':
...
这永远是
False
,因为函数永远不等于字符串