我是python中OOP的初学者,在cod中得到了“没有足够的值来解包”

2024-10-04 05:32:27 发布

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

class Fruits:
    def __init__(self,name,colour,taste,hasColour): 
        self.name = name
        self.colour = colour
        self.taste = taste
        self.hasColour = hasColour
    def hasAlternateColour(self):
        return self.hasColour

if __name__== "__main__":
    fruitList = []
    print("Enter name, colour, taste of the fruit")
    for itr in range(2):
        name,colour,taste = input().split()
        hasColour = input("Does it have another colour")
        fruitList.append(Fruits(name,colour,taste,hasColour))

    for fruit in fruitList:   
        print(fruit.name,fruit.colour,fruit.taste,fruit.hasAlternateColour(),sep="\t")

输出:

Enter name, colour, taste of the fruit
apple red sweet
Does it have another colour yes

错误:

> Traceback (most recent call last):   File
> "E:/Programs/pyoop/Fruitclass.py", line 15, in <module>
>     name,colour,taste = input().split() ValueError: not enough values to unpack (expected 3, got 0)

Tags: ofnameinselfinputdefprintenter
1条回答
网友
1楼 · 发布于 2024-10-04 05:32:27

我猜您在循环的第二次迭代中按了Enter,只是因为程序没有任何消息就死机了。您可以将print替换为input并将其放入循环中,因此程序将始终停止并显示以下消息:Enter name, colour, taste of the fruit

if __name__== "__main__":
    fruitList = []
    for itr in range(2):
        name, colour, taste = input("Enter name, colour, taste of the fruit ").split()
        hasColour = input("Does it have another colour ")
        fruitList.append(Fruits(name, colour, taste, hasColour))

相关问题 更多 >