Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python for循环遍历数组以显示其内容_Python_Arrays_Python 3.x_For Loop_Indexoutofboundsexception - Fatal编程技术网

Python for循环遍历数组以显示其内容

Python for循环遍历数组以显示其内容,python,arrays,python-3.x,for-loop,indexoutofboundsexception,Python,Arrays,Python 3.x,For Loop,Indexoutofboundsexception,该程序根据用户输入的数字计算从0到12的乘法表。 我试图通过循环显示数组的内容和结果。但是,它只显示从0到11的表,而不显示第12个表,即使第12个数据存在 以下是我的想法: def multiplicationTable(): nb = int(input("Please enter a number between 1 and 12 : \n")) table = array('i') for i in range(0,12): table.append(i * nb)

该程序根据用户输入的数字计算从0到12的乘法表。 我试图通过循环显示数组的内容和结果。但是,它只显示从0到11的表,而不显示第12个表,即使第12个数据存在

以下是我的想法:

def multiplicationTable():
 nb = int(input("Please enter a number between 1 and 12 : \n"))

 table = array('i')
 for i in range(0,12):
     table.append(i * nb)

 for i in range(len(table)):
     print(str(nb) + "x" + str(i) + " = " + str(table[i]))
输出如下所示:

4x0 = 0
4x1 = 4
4x2 = 8
4x3 = 12
4x4 = 16
4x5 = 20
4x6 = 24
4x7 = 28
4x8 = 32
4x9 = 36
4x10 = 40
4x11 = 44
是什么原因造成的?来自VB和C,所以我可能会将I误认为是索引,而它是数组中的一个值,但我真的不知道如何解决这个问题。 谢谢大家!

范围函数不包含上限。所以当你说范围0,12时,你只能得到[0,11]。如果需要[0,12],则必须执行范围0,13。请注意,range0,13相当于range13,因为默认下限为0。
请参见。

范围0,12从0到11。这就是为什么i值永远不会达到12。如果您希望for循环从0变为12,只需使for循环使用range0,13您应该将范围修改为range1,13为什么代码中有数组?我认为python没有这个功能,除非它自己声明函数。