我正在尝试编写一个程序,该程序会尝试找出你输入的5个数字,就像某种AI一样。然而,当我运行代码时,遇到了以下错误:TypeError: 'int' object is not subscriptable
这是我的代码——我哪里做错了?
__author__ = '@隐藏人名'import randomdef get_num_code(): x1 = int(input("请依次输入5位数字代码:\n")) x2 = int(input("")) x3 = int(input("")) x4 = int(input("")) x5 = int(input("")) x = [x1, x2, x3, x4, x5] return xdef ai0(x): y = random.randrange(1, 10) if x[0] == y: print("找到第1位数字: {}".format(str(x[0]))) ai1(x) else: print("未找到第1位数字") ai0(x)def ai1(x): y = random.randrange(-1, 10) if x[1] == y: print("找到第2位数字: {}".format(str(x[1]))) ai2(x) else: print("未找到第2位数字") ai1(x)def ai2(x): y = random.randrange(-1, 10) if x[2] == y: print("找到第3位数字: {}".format(str(x[2]))) ai3(x) else: print("未找到第3位数字") ai2(x)def ai3(x): y = random.randrange(-1, 10) if x[3] == y: print("找到第4位数字: {}".format(str(x[3]))) ai4(x) else: print("未找到第4位数字") ai3(x)def ai4(x): y = random.randrange(-1, 10) if x[4] == y: print("找到第5位数字: {}".format(str(x[4]))) final(x) else: print("未找到第5位数字") ai3(4)def final(x): print("找到5位数字代码: {}".format(str(x)))def ai(): x = get_num_code() ai0(x)ai()
回答:
你可以使用以下代码实现类似的功能,
import randomx = input("请输入一个数字: ")for i in range(len(x)): randomGuess = random.randrange(1,10) while randomGuess != int(x[i]): print('第',i,'位数字未找到') randomGuess = random.randrange(1,10) print('第',i,'位数字找到:',x[i])
输出:
请输入一个数字: 123第 0 位数字未找到第 0 位数字未找到第 0 位数字找到: 1第 1 位数字未找到第 1 位数字未找到第 1 位数字找到: 2第 2 位数字找到: 3