小能豆

如何修复 TypeError:'int' 对象不可下标

py

我正在尝试一段简单的代码,获取某人的姓名和年龄,并让他/她知道他们何时年满 21 岁......不考虑负面因素和所有这些,只是随机的。

我一直收到这个'int' object is not subscriptable错误。

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

阅读 47

收藏
2024-09-29

共1个答案

小能豆

您遇到的错误是由于您尝试将年龄输入转换为整数的方式造成的。x您不应使用列表索引,而应直接转换age1为整数。以下是您的更正后的代码版本:

name1 = raw_input("What's your name? ")
age1 = raw_input("How old are you? ")
age1 = int(age1)  # Convert age1 to an integer
twentyone = 21 - age1  # Calculate the difference to 21
print "Hi, " + name1 + ", you will be 21 in: " + str(twentyone) + " years."

这段代码正确地将输入的年龄转换为整数,然后计算出用户还剩多少年才满 21 岁。

2024-09-29