简体   繁体   English

尝试计算和打印整数时,获取“int”对象不是可下标的错误

[英]Getting an 'int' object is not subscriptable error when trying to calculate and print an integer

I'm trying to write a simple program to calculate the Collatz COnjecture but I keep getting the error我正在尝试编写一个简单的程序来计算 Collat​​z 猜想,但我不断收到错误消息

    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

I'm not sure why this is happening, other similar posts on the site failed to resolve the issue.我不确定为什么会发生这种情况,网站上的其他类似帖子未能解决该问题。 here's the rest of my code for context.这是我的上下文代码的其余部分。

#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): ")

The problem is that n is an int , so you can only use n[] for data types that are subscritable like lists , tuples , iterables in general.问题是n是一个int ,因此您只能将n[]用于可订阅的数据类型,例如liststuplesiterables一般。

So if you just want to match the value: instead of n[-1] == '0' write n == 0 and so on.所以如果你只想匹配值:而不是n[-1] == '0'n == 0等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeError: &#39;int&#39; 对象不可下标,尝试解决可下标错误但无法解决 - TypeError: 'int' object is not subscriptable, trying to solve subscriptable error but not able to solve it 尝试运行 keras fit() 时,出现错误“函数”object 不可下标 - When trying to run keras fit(), getting error 'function' object is not subscriptable &#39;int&#39;对象不是下标错误 - 'int' object is not subscriptable error &#39;int&#39;对象不可下标错误 - 'int' object not subscriptable error 收到错误:尝试打印数字的素数时,float对象无法解释为整数 - Getting the error: float object cannot be interpreted as an integer, when trying to print the prime factors of a number 获取 TypeError: 'int' object 不可订阅 - Getting a TypeError: 'int' object is not subscriptable 尝试对数据进行分类时,“ int”对象不是下标错误 - 'int' object is not subscriptable error while trying to classify my data TypeError:“ int”对象不可下标-尝试创建csv文件时 - TypeError: 'int' object is not subscriptable - when trying to create csv files 我收到登录路由错误 TypeError: &#39;int&#39; object is not subscriptable - I am getting error for the login route TypeError: 'int' object is not subscriptable 我一直在 python 中收到错误消息 &#39;TypeError: &#39;int&#39; object is not subscriptable&#39; - I keep getting the error message 'TypeError: 'int' object is not subscriptable' in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM