Python缩进协助

2024-05-23 14:33:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在上Python编程课,我的编码问题有点问题

我得到的错误是

SyntaxError: expected an indented block (CTest.py, line 5) 
 5  muffin -= 1:

我试图再次缩进muffin-=1:但它仍然给了我同样的错误。所以我不知道问题出在哪里。我还尝试缩进muffin-=1下面的所有代码:

以下是我正在研究的问题:

You work for a bakery that sells two items: muffins and cupcakes. The number of muffins and cupcakes in your shop at any given time is stored in the variables muffins and cupcakes, which have been defined for you. Write a program that takes strings from standard input indicating what your customers are buying ("muffin" for a muffin, "cupcake" for a cupcake). If they buy a muffin, decrease muffins by one, and if they buy a cupcake, decrease cupcakes by 1. If there is no more of that baked good left, print ("Out of stock"). Once you are done selling, input "0", and have the program print out the number of muffins and cupcakes remaining, in the form "muffins: 9 cupcakes: 3" (if there were 9 muffins and 3 cupcakes left, for example).

buying = input()
while buying != "0":
    if buying == "muffin":
        while buying > 0:
        muffin -= 1:
    else print ("Out of stock"):
    elif buying == cupcake:
        if cupcake > 0:
        cupcake -= 1:
    else print ("Out of stock"):
        buying = input() 
        print("muffins:", muffins, "cupcakes:", cupcakes)

Tags: andoftheinforinputifthat
3条回答

这里有很多错误。首先,需要在whileif之后缩进块。e、 g:

    while buying > 0:
        muffin -= 1

我不确定您希望在while块中包含多少行,但正如所写的那样,while循环将永远不会退出,因为buying变量不会改变

接下来,在奇怪的地方有冒号。例如:

muffin -= 1:

应该是:

muffin -= 1

另外,您的else语法在两个位置都是错误的:

else print ("Out of stock"):

我假设你想要这样的东西:

else:
    print ("Out of stock")

最后,从未定义cupcake变量

我真的没有考虑它是否会做你想做的事情的逻辑。有太多的问题需要解决,无法理解您的尝试

while buying > 0:应该是if muffin > 0:。您需要缩进在这种情况下应该执行的语句,并且相应的else:需要缩进到与if相同的级别

else:应该在它自己的一行上,后面要执行的语句缩进

普通语句的末尾不应该有:,而应该只有启动块的语句(ifelsewhile

当与buying比较时,您需要引用cupcake

buying = input()

while buying != "0":
    if buying == "muffin":
        if muffin > 0:
            muffin -= 1
        else:
            print ("Out of stock")
    elif buying == "cupcake":
        if cupcake > 0:
            cupcake -= 1
        else:
            print ("Out of stock")
    buying = input() 

print("muffins:", muffins, "cupcakes:", cupcakes)

你的语法错了。例如:

while buying > 0:
muffin -= 1:

应该是

while buying > 0:
    muffin -= 1 # No ':' at the end, add one level of indentation to enter block

相关问题 更多 >