Python剪刀石头布游戏newround函数报错:'str' object is not callable
解决Python剪刀石头布游戏输入无效内容触发TypeError的问题
问题描述
在我开发的Python剪刀石头布游戏中,调用newround函数进行新回合确认的Yes/No输入环节时,若输入'test'这类不符合要求的内容,程序会先弹出无效输入提示,但紧接着触发TypeError: 'str' object is not callable错误。我已排查代码,未发现命名为str的变量,作为编程新手,寻求解决办法。
报错堆栈
Traceback (most recent call last): File "rock_paper_scissors.py", line 58, in <module> newround() File "rock_paper_scissors.py", line 49, in newround play_again = str(input("Would you like to play another round? (Yes/No): ")).lower() TypeError: 'str' object is not callable
完整代码
import random def determine_winner(player, computer): if player == computer: return "tie" elif (player == "rock" and computer == "scissors") or \ (player == "paper" and computer == "rock") or \ (player == "scissors" and computer == "paper"): return "player" else: return "computer" def play_round(): choices = ["rock", "paper", "scissors"] player_choice = input("Enter your choice (rock/paper/scissors): ").lower() while player_choice not in choices: print("Invalid choice! Please pick rock, paper, or scissors.") player_choice = input("Enter your choice (rock/paper/scissors): ").lower() computer_choice = random.choice(choices) print(f"Computer chose: {computer_choice}") result = determine_winner(player_choice, computer_choice) if result == "tie": print("It's a tie!") elif result == "player": print("You win!") else: print("You lose!") def newround(): while True: # 报错触发行 play_again = str(input("Would you like to play another round? (Yes/No): ")).lower() if play_again in ["yes", "y"]: play_round() elif play_again in ["no", "n"]: print("Thanks for playing!") break else: print("Invalid input! Please enter Yes or No.") # 启动游戏 play_round() newround()
排查与解决方法
问题根源
报错'str' object is not callable说明你代码的某个位置将内置函数str覆盖成了字符串变量——即使你没在newround函数里定义,全局范围内的覆盖也会导致这个错误。比如可能在游戏逻辑的某个环节,你不小心写了类似str = "some text"的代码,把原本的字符串转换函数变成了普通字符串。
排查步骤
- 全局搜索代码中的
str =,找到所有把str当作变量名的语句。 - 在
newround函数开头添加print(type(str)),运行程序输入无效内容后,若输出是<class 'str'>,则确认str被覆盖;正常情况下应该输出<class 'function'>。
解决办法
- 重命名覆盖
str的变量:把所有名为str的变量改成其他合法名称,比如game_label、choice_text等。 - 简化输入语句:
input()函数本身返回的就是字符串,不需要额外用str()包裹,直接修改代码为:
这不仅能避免不必要的函数调用,还能减少出错概率。play_again = input("Would you like to play another round? (Yes/No): ").lower()
内容的提问来源于stack exchange,提问作者Max Pearson
相关产品推荐
相关产品推荐

