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

Python彩色文本循环切换报错:'str'对象不可调用问题求助

Fixing the "str object is not callable" Error in Your Color-Cycling Python Script

Hey Jake, let's break down why your script stops after one cycle and throws that error!

The core issue is a name collision inside your hello() function: you've used the same name hello for both your function and a string variable (hello = '''Hello!'''). When you do this, you overwrite the original reference to the hello() function. By the time you reach the final hello() call to restart the cycle, Python sees hello as a string instead of a function—hence the TypeError: 'str' object is not callable.

Quick Fixes & Improvements:

  • Rename the string variable: Pick a different name like greeting or message to avoid clashing with the function name.
  • Initialize colorama once: You don't need to run init() every time the function loops—move it to the top of your script since it only needs to run once.
  • Clean up the loop: Instead of repeating the same print/sleep code three times, use a list of colors and iterate over it for cleaner, more maintainable code.

Revised Working Code (Infinite Cycle):

import time, sys, os
from colorama import init
from termcolor import colored

# Initialize colorama once at startup
init()

def hello():
    greeting = '''Hello!'''
    # List of colors to cycle through
    color_list = ['green', 'blue', 'yellow']
    
    for color in color_list:
        os.system('cls')
        print(colored(greeting, color))
        time.sleep(1)
    
    # Restart the cycle by calling the function again
    hello()

hello()

Bonus: Add an Exit Option

For a more user-friendly version, use a while True loop (instead of recursion, which can hit Python's recursion limit after many cycles) and handle Ctrl+C to let the user exit cleanly:

import time, sys, os
from colorama import init
from termcolor import colored

init()

def hello():
    greeting = '''Hello!'''
    color_list = ['green', 'blue', 'yellow']
    
    while True:
        for color in color_list:
            os.system('cls')
            print(colored(greeting, color))
            time.sleep(1)

try:
    hello()
except KeyboardInterrupt:
    print("\nExiting the color cycle!")
    sys.exit(0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:20:11