python - 尝试计算和打印整数时获取“int”对象不是可下标的错误
问题描述
我正在尝试编写一个简单的程序来计算 Collatz 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): ")
解决方案
问题在于它n
是一个int
,所以您只能n[]
用于一般可订阅的数据类型,例如lists
, 。tuples
iterables
因此,如果您只想匹配值:而不是n[-1] == '0'
writen == 0
等等。
推荐阅读
- java - 如何使用 Firebase 身份验证和 Cloud Firestore 进行会话
- arrays - 过滤某些特定值后,如何在特定索引处删除嵌套数组中的整个字典
- docker - 如何将谷歌实例设置保存为 docker 镜像?
- java - 如何从 servlet 的列表中打开文件
- python - 如何获得新价格?
- python - 如何在程序生命周期内只运行一次 Python 方法?
- angular - 如何使角度材质输入看起来类似于按钮?
- json - 有没有办法随机化 get[] myJson 中的 jsonPath 数组编号?
- ruby-on-rails - Rails/SimpleForm:如何在表单中嵌套 has_many 关联的字段?
- php - 使用子进程从默认的 Ubunty Python 调用它时出现 Anaconda 权限错误