Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.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 为什么会出现错误,列表索引超出显示范围?_Python - Fatal编程技术网

Python 为什么会出现错误,列表索引超出显示范围?

Python 为什么会出现错误,列表索引超出显示范围?,python,Python,numPizza变量来自代码中的另一个输入 def Receipt(): print("Receipt:") print("\n") print(Customer_name, "ordered:") if numPizza == 1: print("%s" % str(order[0])) elif numPizza == 2: print("%s" % str(order[0])) print("%s" %

numPizza变量来自代码中的另一个输入

def Receipt():
    print("Receipt:")
    print("\n")
    print(Customer_name, "ordered:")
    if numPizza == 1:
        print("%s" % str(order[0]))
    elif numPizza == 2:
        print("%s" % str(order[0]))
        print("%s" % str(order[1]))
    elif numPizza == 3:
        print("%s" % str(order[0]))
        print("%s" % str(order[1]))
        print("%s" % str(order[2]))
    elif numPizza == 4:
        print("%s" % str(order[0]))
        print("%s" % str(order[1]))
        print("%s" % str(order[2]))
        print("%s" % str(order[3]))
    elif numPizza == 5:
        print("%s" % str(order[0]))
        print("%s" % str(order[1]))
        print("%s" % str(order[2]))
        print("%s" % str(order[3]))
        print("%s" % str(order[4]))
这是它打印的错误:

numPizza = input("Enter number of pizzas wanted (Max 5):  ")

原因是,订单列表中没有项目,或者只有一个项目

注意,列表是基于零的索引,所以要访问第一项,请使用order[0]

要签入代码,检查列表变量是否有足够的项,可以在其中添加

    print("%s" % str(order[1]))
IndexError: list index out of range
这应在声明试图使用给定索引1之前的开发过程中完成

如果不满足此前提条件,它将抛出异常


您的numPizza可能没有指定正确的值。检查一下。

在Python中,您不必单步浏览这样的列表;取而代之的是考虑如下:

 assert len(order) >= 2
现在,不管订单上有多少比萨饼,它们都会被打印出来。通过加入结果列表,可以进一步缩短代码:

def receipt():  # method names should be lower case
    print("Receipt:\n")
    print('{} ordered:\n'.format(Customer_name))
    for item in order:
       print('{}'.format(item))
但请记住,如果您的列表包含一个数字,这将不起作用:

>>> '\n'.join(['a','b','c'])
'a\nb\nc'

您的订单列表中没有超过1个元素?我可能是瞎子,但是。。。什么是秩序?你可能只有一个元素。它显示一个比萨菜单,你选择你的比萨,它将把比萨添加到订单中,你最多可以要求5个比萨!顺便说一句,通过使用for循环,可以在代码中进行大量重构,但这不是问题所在……根据错误,他有并且只有一个元素。它不可能是0。这就是我正在做的,但应该有顺序,因为当他们选择一个比萨饼时,它会添加使用顺序的比萨饼。附加比萨饼名称它似乎不会将比萨饼放在列表中,因为如果我只选择1个比萨饼,它工作正常并打印收据,但一旦我选择2个比萨饼,它就不能在屏幕上显示第二个比萨饼带有打印“{}”的列表。formatitem我该如何处理它?它与打印“%s”%strorder[0]相同,只是它不会引发索引器,所以请在同一位置使用它。
>>> '\n'.join(['a','b',1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 2: expected string, int found