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

Python调用randint循环时报TypeError: 'int' object is not callable求修复

报错信息

运行代码第二轮循环触发如下报错:

randint = randint(1, 2)
TypeError: 'int' object is not callable

第一轮问答流程可正常执行,第二次循环启动时直接抛出上述错误。

问题原因
  • 代码开头通过from random import randint导入了随机整数生成函数,此时全局作用域内的randint是可调用的函数对象。
  • 第一次执行while循环内的randint = randint(1, 2)时,等号右侧的randint仍指向原始函数,调用后返回1或2的整数结果,随即这个整数被赋值给等号左侧同名的randint变量,这是触发报错的核心原因:同名变量直接把全局作用域里原本指向函数的randint覆盖成了整数类型。
  • 第二次循环执行到randint(1, 2)时,randint已经是上一轮存储的整数值,整数不属于可调用对象,因此抛出“int对象不可调用”的类型错误。
  • 原代码还存在冗余逻辑问题:每次循环会同时调用两次make_question,仅靠函数内部的数值判断决定是否展示题目,变量被覆盖后这段判断逻辑也会完全失效。
修复方法

核心是避免变量名和导入的函数名重名,同时简化冗余的选题判断逻辑:

  • 将存储随机选题编号的变量重命名为不和函数冲突的名称,比如question_id
  • 把题目匹配的判断逻辑移到循环层,根据生成的随机数直接调用对应题目的问答逻辑,去掉函数内不必要的参数和判断

修复后的可运行代码:

from random import randint

score = 0
print('\n\n\n\nyour score right now is ', score, 'if it drops below zero you lose')

def make_question(italian, answer):
    global score
    user_ans = input('\nWhat does ' + str(italian) + ' mean? ')
    if user_ans == str(answer):
        score += 1
        print('\ncorrect your score is: ', score)
    else:
        score -= 1
        print('\nincorrect your score is now: ', score)

while True:
    question_id = randint(1, 2)
    if question_id == 1:
        make_question('ripetere', 'repeat')
    else:
        make_question('puoi/potere ripetere', 'can you repeat that')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 16:45:46