QNA > P > Perché Viene Mostrato Questo Errore In Una Funzione Python 'Object Is Not Subscriptable'?

Perché viene mostrato questo errore in una funzione Python 'object is not subscriptable'?

This mainly happens with functions return different data types according to the parameters given

The best way to avoid this is to use type() function to determine the return value’s data type and act accordingly

  1. x = fun() #function whose return data type is unknown 
  2. if type(x) == int:#if the return value is an integer 
  3. #do this 
  4. elif type(x) == str:#if the return value is a string 
  5. #do this 

If the error is occurred inside the function you need to check your code to ensure it’s working properly.

Più sull'errore non sottoscrivibile (TypeError)

Python lancia un TypeError se si cerca di accedere ad un oggetto non sottoscrivibile in un modo in cui si accede ad un oggetto stringa o array (o qualsiasi altro tipo di oggetto sottoscrivibile).

here a string object subscripted

  1. >>> x = 'this is subscriptable' 
  2. >>> x[0] 
  3. >>> 't' 

some common non-subscriptable object types are int, float, bool and NoneType

  1. >>> y = 123 #an integer 
  2. >>> y[0] # will result an error 
  3. Traceback (most recent call last): 
  4. File "", line 1, in  
  5. y[0] 
  6. TypeError: 'int' object is not subscriptable 
  7. >>> 

This type of errors happen when you use the same variable to store different data types throughout your code and you eventually lost track of the data type the variable currently has.

Solution is either to check the variable carefully throughout the code or to use different variables to store values with different data types if memory usage is not an issue.

example:

  1. >>> x = '10' #x is a string 
  2. >>> print(x) 
  3. 10 
  4. >>> x = int(x) #x is now a int 
  5. >>> print(x) 
  6. 10 
  7. >>> x[0] # will result an error 
  8. Traceback (most recent call last): 
  9. File "", line 1, in  
  10. y[0] 
  11. TypeError: 'int' object is not subscriptable 
  12. >>> 

Di Favien Houchen

Come risolvere lo schermo nero sul mio PC Lite PUBG :: Qual è la migliore piattaforma per fare reddito per gli sviluppatori di app, iOS o Android?
Link utili