我在python上相当新,我在尝试一些想法时遇到了以下问题: 我希望用户为蛋糕输入5种成分并将其存储在列表中并将列表返回给用户。 我告诉用户告诉我5种成分。 现在我想要python检查用户是否真的给了我5个成分或者给他们一个错误信息。 这是我到目前为止所做的。
def recipe():
#create a list to store the recipe ingredients.
print "Enter 5 ingredients that could possibly go into a cake: "
recipeList = []
ingredients = raw_input("> ")
recipeList = recipeList.append(ingredients)
recipeList = [ingredients]
print recipeList
if len(ingredients) = 5:
print "Thanks"
elif len(ingredients) > 5:
print "That's too much"
elif len(ingredients) < 5:
print "That's too little"
else:
print "There's something wrong!"
recipe()
答案 0 :(得分:2)
很多这些线都是多余的。你只需要这样的东西*:
def recipe():
"""Create a list to store the recipe ingredients."""
print "Enter 5 ingredients that could possibly go into a cake: "
ingredients = raw_input("> ").split()
print ingredients
if len(ingredients) == 5:
print "Thanks"
elif len(ingredients) > 5:
print "That's too much"
elif len(ingredients) < 5:
print "That's too little"
else:
print "There's something wrong!"
recipe()
这里最重要的一点是:
ingredients = raw_input("> ").split()
它基本上做了两件事:
答案 1 :(得分:0)
如果你的所有成分都是一个单词,它们将在逻辑上用空格分隔,所以你需要做的就是split
每个空间的输入字符串。或者您可以指定每个成分需要用逗号或某种分隔符分隔split(",")
print "Enter 5 ingredients that could possibly go into a cake: "
recipeList = raw_input("> ").split(" ")
等于运算符是==
if len(recipeList ) == 5:
答案 2 :(得分:0)
您需要使用split
函数,因为raw_input不会按空格或任何其他分隔符分隔输入。
recipeList = ingredients.split()
此外,这个比较应该是双等于,否则它是一个赋值。此外,它应该比较列表的长度,而不是用户输入。
if len(recipeList) == 5:
答案 3 :(得分:0)
这就行了:
def recipe():
#create a list to store the recipe ingredients.
print "Enter 5 ingredients that could possibly go into a cake: "
recipeList = []
line = raw_input("> ") # changed line
ingredients = line.split() # changed line, converts the input in an array
# (input separated by spaces)
recipeList = recipeList.append(ingredients)
recipeList = [ingredients]
print recipeList
if len(ingredients) == 5: # added the double equal
print "Thanks"
elif len(ingredients) > 5:
print "That's too much"
elif len(ingredients) < 5:
print "That's too little"
else:
print "There's something wrong!"
recipe()