How to fix TypeError: 'int' object is not subscriptable?

How to fix TypeError: ‘int’ object is not subscriptable

I was trying a simple piece of code, get someone’s name and age and let him/her know when they turn 21… not considering negatives and all that, just random.

I keep getting this ‘int’ object is not subscriptable error.

name1 = raw_input("What's your name? ")
age1 = raw_input ("how old are you? ")
x = 0
int([x[age1]])
twentyone = 21 - x
print "Hi, " + name1+ " you will be 21 in: " + twentyone + " years."
TypeError                                 Traceback (most recent call last)
Cell In[34], line 4
      2 age1 = input ("how old are you? ")
      3 x = 0
----> 4 int([x[age1]])
      5 twentyone = 21 - x
      6 print "Hi, " + name1+ " you will be 21 in: " + twentyone + " years."

TypeError: 'int' object is not subscriptable

Can anyone help me with the error.

Hi Mehta,

The issue in your code is with the line int([x[age1]]). To correctly convert the input age to an integer, you should use x = int(age1) instead. Also, ensure to convert the integer twentyone to a string for the output. Here’s the corrected code:

name1 = raw_input("What's your name? ")
age1 = raw_input("How old are you? ")
x = 0
x = int(age1)
twentyone = 21 - x
print("Hi, " + name1 + " you will be 21 in: " + str(twentyone) + " years.")

This code will prompt the user for their name and age, calculate the years until they turn 21, and then display the result along with their name.

You are right Richa!

Also, the error message ‘int’ object is not subscriptable means that you’re trying to treat an integer (int object) as if it were a list or a string, which you can access using an index or slice. In your code, the issue is with the line int([x[age1]]).

To fix this, you should remove the square brackets ([]) around x[age1], as you don’t need to subscript x (which is just an integer) at all. Instead, you should convert age1 to an integer using int() directly. Here’s the corrected code:

name1 = input("What’s your name? ") age1 = int(input("how old are you? ")) x = 0 twentyone = 21 - age1 print(“Hi, " + name1 + " you will be 21 in: " + str(twentyone) + " years.”)

This code will correctly calculate the number of years until the person turns 21 based on their current age and display the result.

1 Like

The error you’re encountering, “TypeError: ‘int’ object is not subscriptable,” is because you’re trying to use indexing on an integer, which is not allowed in Python. Here’s a corrected version of your code:

name1 = input("What's your name? ")
age1 = int(input("How old are you? "))
twentyone = str(21 - age1)
print("Hi, " + name1 + " you will be 21 in: " + twentyone + " years.")

In this code, age1 is already an integer after conversion using int(input(...)), so you don’t need to convert it again. Also, I corrected the print statement to concatenate strings correctly.

1 Like