[英]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我正在尝试编写一个简单的程序来计算 Collatz 猜想,但我不断收到错误消息
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[]
用于可订阅的数据类型,例如lists
、 tuples
、 iterables
一般。
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.