索引期间字符串转换为整数

问题描述 投票:0回答:1

我正在创建一个程序来检查用户输入的猜测是否正确(很像猪和公牛)。计算机生成正确的代码。

在检查用户输入的是否正确的过程中,字符串变量(或者我认为)被改变为int并且停止可迭代。我尝试用print(type())进行一些调试来检查变量的类型。直到它被迭代的那一刻,变量是一个String,但我得到一个TypeError:类型'int'的参数是不可迭代的。

这是代码:

def create_code(creator=list):
    creator = [random.randint(0, 9) for index in range(0, 4)]
    return creator

def guesses():
    state = True
    user_inputs = []
    while state:
        get_user_input = str(input('Please insert your 4 digit guess: '))
        user_inputs.append(get_user_input)
        for index in range(0,len(get_user_input)+1):
            touro(index, get_user_input[index]) #goes to touro to check if the number inputted is in the code and in the correct position

def touro(index, user_input):
    t = 0
    print(type(user_input[index]))#this returns str
    print(type(create_code))#this returns list
    if user_input[index] in create_code()[index]:
        print('th')
        t += 1
    else:
        pigs(index, user_input)#this function is just to check if the inputted number currently being iterated is even in the code
        print('ty')
    return t

错误:

    File "C:/Users/Miguel/PycharmProjects/untitled1/Trabalho1.py", line 14, in guesses
    touro(index, get_user_input[index])
  File "C:/Users/Miguel/PycharmProjects/untitled1/Trabalho1.py", line 27, in touro
    if user_input[index] in create_code()[index]:
TypeError: argument of type 'int' is not iterable

我不知道我做错了什么,我对类似的问题没有任何疑问,现在有人问我做错了吗?

python type-conversion
1个回答
1
投票

片段create_code()[index]执行以下操作:

  • 创建一个整数列表,即[7, 4, 7, 0]
  • 选择并返回位于索引处的整数,即索引等于2,这将返回7

in语句不能用于搜索整数中的字符串字符。

© www.soinside.com 2019 - 2024. All rights reserved.