ElMassas
ElMassas

Reputation: 407

String converted to integer during indexation

I'm creating a program to check if a user's inputted guess is correct(much like pigs and bulls). The correct code is generated by the computer.

During the process of checking if the user inputted is correct a string variable is changed(or so I think) to an int and stops being iterable. I've tried doing some debugging with print(type()) to check for the type of the variable. Right up until the moment it's being iterated, the variable is a String, yet I get a TypeError: argument of type 'int' is not iterable.

here's the code:

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

Error:

    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

I don't get what i'm doing wrong, and I haven't any questions with similar problems, does anybody now what I'm doing wrong?

Upvotes: 0

Views: 82

Answers (1)

E. Ducateme
E. Ducateme

Reputation: 4238

The snippet create_code()[index] does the following:

  • creates a list of integers, i.e. [7, 4, 7, 0]
  • selects and returns the integer located at index i.e. at index equals 2, which would return a 7

The in statement cannot be used to search for a string character in an integer.

Upvotes: 1

Related Questions