You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python程序输入语句执行后if语句未触发问题求助

问题分析与解决

你的代码核心问题是没有正确调用字符串的lower()方法,导致条件判断永远不成立。

错误原因

newtime.lower是对字符串lower方法的引用(它是一个方法对象),而不是执行该方法后得到的小写字符串。方法对象和字符串"utc"/"local"类型完全不同,自然永远不会相等,所以所有if/elif分支都不会触发,直接进入else。

修正方案

把所有newtime.lower改成newtime.lower(),或者在获取输入时就直接转成小写:

方式一:修改判断条件

import time

newtime = input("Would you like to see Local or UTC time? ")
#newtime stores user input
if newtime.lower() == "utc":
    print(time.strftime("The current time and date in UTC is: %c ", time.gmtime()))
elif newtime.lower() == "local":
    print(time.strftime("The current time and date in local is: %c", time.localtime()))
else:
    print("Input not recognized, please type 'Local' or 'UTC'")

方式二:输入时直接转小写(更简洁)

import time

newtime = input("Would you like to see Local or UTC time? ").lower()
#newtime stores user input in lowercase
if newtime == "utc":
    print(time.strftime("The current time and date in UTC is: %c ", time.gmtime()))
elif newtime == "local":
    print(time.strftime("The current time and date in local is: %c", time.localtime()))
else:
    print("Input not recognized, please type 'Local' or 'UTC'")

补充说明

字符串的lower()是实例方法,必须通过()调用才能执行,返回原字符串的小写版本。直接写变量名.lower只是拿到方法本身,不是执行结果,这是Python新手常犯的小错误。

内容的提问来源于stack exchange,提问作者Ledian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 04:35:19