'int' object is not subscriptable. Lists in Python

0

Good afternoon, I'm doing a simple didactic program that is responsible for reaching an X number with certain operations. My code is as follows:

##Los numeros de la persona
numeroP1 = [0,0,0,0]
numeroP2 = [0,0,0,0]
##Los numeros de la computadora
numeroC1 = [0,0,0,0]
numeroC2 = [0,0,0,0]
numeroC3 = [0,0,0,0]

primerNumero = int(input("Ingresa un numero de 4 digitos "))


if primerNumero >= 1111 and primerNumero <= 9999: ##len() no funciona para int
    numeroP1[0] = primerNumero[0]
    numeroP1[1] = primerNumero[1]
    numeroP1[2] = primerNumero[2]
    numeroP1[3] = primerNumero[3]

    print ("El primer numero es: " , numeroP1[0])
    print ("El segundo  numero es: " , numeroP1[1])
    print ("El tercer numero es: " , numeroP1[2])
    print ("El cuarto numero es: " , numeroP1[3])

    numeroC2[0] = 9 - numeroP1[0]
    print ("La resta da: " , numeroC2[0])



else:
    print ("No has ingresado un numero de 4 digitos")

I need to get the number of C2 [0] saved and the result of (9 - numberP1 [0]) shown. This is where I get the error "TypeError: 'int' object is not subscriptable." It is in this line

numeroP1[0] = primerNumero[0]

Try this way but it did not work either:

numeroP1[0] = int(primerNumero[0])
    
asked by Lucas. D 22.10.2016 в 20:26
source

2 answers

2

The problem is that you are treating the entire primerNumero as a list. To take the digits, you must use the module and entire divisions between 10.

numeroP1[3] = primerNumero % 10
numeroP1[2] = primerNumero // 10 % 10
numeroP1[1] = primerNumero // 100 % 10
numeroP1[0] = primerNumero // 1000 % 10
    
answered by 22.10.2016 / 20:37
source
1

The previous answer is valid, you also have the option of converting the entered integer to array by listas in the following way

if primerNumero >= 1111 and primerNumero <= 9999: ##len() no funciona para int
    lst = [int(i) for i in str(primerNumero)]##cnvert input to list
    numeroP1= lst ##asigna la lista a NumeroP1
    print ("El primer numero es: " , numeroP1[0])
    print ("El segundo  numero es: " , numeroP1[1])
    
answered by 22.10.2016 в 20:49