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

Python代码凭空出现多余输出 未打印却返回inp_a分段内容

Python时间计算脚本异常输出问题排查

问题现象

运行编写的Python时间计算脚本时,未编写对应打印逻辑的前提下,控制台无故输出变量inp_a的第二部分内容,自行排查无法定位问题根源。

复现代码

inp_a = input("What`s the time you want to start from? ")
military_time = input("is it AM or PM: ").upper()
inp_b = input("How long would you like to wait? ")
day = input("What`s the day today?
The day must be one of the weekdays ")


inp_a = inp_a.split(":")
inp_b = inp_b.split(":")
day = day.lower()

if military_time == "AM":
  inp_a[0] = inp_a[0]
elif military_time == "PM":
  inp_a[0] = int(inp_a[0]) + 12
  inp_a[0] = str(inp_a[0])



try:
  convert_a1 = int(inp_a[0])
  convert_a2 = int(inp_a[1])
  convert_b1 = int(inp_b[0])
  convert_b2 = int(inp_b[1])
except:
  print("-"*50)
  print("One of the inputs is incorrect, try again")
  


while True:
  if day == "sunday":
    break
  elif day == "monday":
    break
  elif day == "tuesday":
    break
  elif day == "wednsday":
    break
  elif day == "thursday":
    break
  elif day == "friday":
    break
  elif day == "saturday":
    break
  else:
    print(day,"is not one of the weekdays try again")
    quit()

rl_time = int(inp_a[0])*60 + int(input(inp_a[1]))
time2add = int(inp_b[0]*60) + int(input(inp_b[1]))

result = rl_time + time2add
hh = result // 60
mm = result % hh

问题根因

异常输出的直接原因是代码中两处错误使用了input()函数:

  • 计算总起始分钟的行:rl_time = int(inp_a[0])*60 + int(input(inp_a[1]))
  • 计算总等待时长的行:time2add = int(inp_b[0]*60) + int(input(inp_b[1]))

input()函数的执行逻辑是:将传入的字符串参数作为提示文本打印到控制台,再阻塞等待用户输入内容。本来需要直接读取inp_a[1]、inp_b[1]中已经拆分好的分钟值转成整数计算,却误把这两个值传给了input()当提示参数,所以控制台会直接打印这两个值,看起来像是"无故输出"。

其他现存代码问题

除了导致异常输出的核心错误,代码还有几处会引发运行异常的逻辑问题:

  • inp_b[0]*60运算顺序错误:inp_b[0]是字符串类型,直接和60做乘法会把字符串重复60次,后续转int会直接报错,需要先把inp_b[0]转成整数再乘60
  • 分钟计算逻辑错误:mm = result % hh没有实际意义,总分钟数对总小时数取余得不到正确的分钟结果,应该对60取余
  • 输入校验逻辑不完整:try-except捕获到输入格式错误后,打印提示没有终止程序,后续代码会继续执行触发更多报错
  • 冗余的while循环:星期判断部分写了死循环结构,但所有合法分支都直接break,没有循环输入的逻辑,和普通分支判断没有区别,属于无效代码

修复参考

把错误的input()调用去掉,修正其他逻辑问题后的核心计算部分示例:

# 去掉错误的input调用,直接读取拆分后的值
rl_time = int(inp_a[0])*60 + int(inp_a[1])
# 先转int再做乘法
time2add = int(inp_b[0])*60 + int(inp_b[1])

result = rl_time + time2add
hh = result // 60
# 对60取余算分钟
mm = result % 60

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 00:21:38