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

打字速度测试器:如何引用作用域外的变量?

问题分析与修正

核心问题

  • 同步阻塞:原代码中start_timer()是同步执行的,调用后程序会先跑完60秒倒计时,才会执行输入逻辑,导致用户完全没有输入时间。
  • 逻辑判断错误:while not start_timer和if start_timer里的start_timer是函数对象,不是函数返回的布尔值,这部分判断完全不生效。

修正后的代码

import time
import threading

# 全局变量标记时间是否结束
time_over = False

def start_timer():
    """启动计时器,时间到后将time_over设为True"""
    global time_over
    for secs in range(60, -1, -1):
        time.sleep(1)
        if secs == 30:
            print('剩余时间:', secs)
        elif secs == 10:
            print('剩余时间:', secs)
        elif secs == 0:
            time_over = True
            print('@@@ 叮咚!时间到了,伙计! @@@')

def counter(some_string):
    """统计输入字符串的字符总数"""
    total_chars = len(some_string)
    print(f'你总共输入了{total_chars}个字符,厉害!')

print('你有1分钟时间尽可能多地输入内容')
start_question = input('准备好输入y开始,输入n退出:').lower()
if start_question == 'y':
    # 启动计时器线程,后台运行不阻塞输入
    timer_thread = threading.Thread(target=start_timer)
    timer_thread.start()
    
    text = ''
    # 时间未结束时持续接收输入
    while not time_over:
        try:
            # 把每次输入的内容追加到总文本中
            user_input = input()
            text += user_input + ' '
        except EOFError:
            break
    
    # 等待计时器线程执行完毕
    timer_thread.join()
    counter(text)

关键改动说明

  • 多线程并行:用threading.Thread将计时器放到后台线程运行,让主线程可以同时处理用户输入,解决了同步阻塞的问题。
  • 共享状态标记:通过全局变量time_over让计时器和输入逻辑共享时间结束的状态,保证两者逻辑同步。
  • 输入逻辑优化:在循环中持续收集用户输入,把所有输入内容拼接成完整字符串后传给统计函数。
  • 异常处理:添加try-except捕获时间结束后输入可能触发的异常,避免程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:10:27