首页 > 解决方案 > 尝试计算和打印整数时获取“int”对象不是可下标的错误

问题描述

我正在尝试编写一个简单的程序来计算 Collat​​z COnjecture 但我不断收到错误

    Traceback (most recent call last):
File "C:/Users/457700/Desktop/collatzconjecture.py", line 11, in <module>
if int(n[-1]) == "0" or int(n[-1]) == "2" or int(n[-1]) == "4" or int(n[-1]) == "6" or int(n[-1]) == "8":
TypeError: 'int' object is not subscriptable

我不确定为什么会发生这种情况,该网站上的其他类似帖子未能解决该问题。这是我其余的上下文代码。

#This program will calculate the Collatz Conjecture

repeat = "y"

while repeat[0].lower() == "y":

     n = int(input("Enter n: "))

     while n != 1:

         if n[-1] == "0" or n[-1] == "2" or n[-1] == "4" or n[-1] == "6" or n[-1] == "8":
             n = n/2
             print(n)
     else:
         n = n * 3
         n = n + 1
         print(n)

repeat = input("Repeat? (Y/N): ")

标签: pythonmathinteger

解决方案


问题在于它n是一个int,所以您只能n[]用于一般可订阅的数据类型,例如lists, 。tuplesiterables

因此,如果您只想匹配值:而不是n[-1] == '0'writen == 0等等。


推荐阅读