尝试使用范围

时间:2015-07-08 12:27:14

标签: python python-2.7

在我运行以下代码时,它会显示TypeError

a = int(input("Enter the iteration value:"))

b=[]

for c in range[0,a]:
    d=int(input("Enter:"))
    b.append(d)

f=0    
for e in b:
    f = f + e

print f

显示以下错误

Enter the iteration value:5
Traceback (most recent call last):
  File "/var/app/eclipse/plugins/org.python.pydev_3.5.0.201405201709/pysrc/pydevd.py", line 1845, in <module>
    debugger.run(setup['file'], None, None)
  File "/var/app/eclipse/plugins/org.python.pydev_3.5.0.201405201709/pysrc/pydevd.py", line 1373, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/opt/odoo/v7.0_cust_mod/Python/print.py", line 68, in <module>
    for c in range[0,a]:
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

1 个答案:

答案 0 :(得分:4)

您使用了range()函数的错误语法:

for c in range[0,a]:

注意方括号,您应该使用括号:

for c in range(0, a):

方括号用于 subscriptions ,这意味着Python将尝试在__getitem__函数对象上使用range方法。没有这样的方法,这就是你得到追溯的原因。