Python 中输入后是否会被代码忽略语句? [已关闭]

问题描述 投票:0回答:1

我是 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
,因为我是编程新手,但也不是这样。

python if-statement user-input
1个回答
1
投票

您需要在 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
,因为函数永远不等于字符串

© www.soinside.com 2019 - 2024. All rights reserved.