如何在python的while循环中为if语句在一行中添加多个输入?

2024-06-16 09:35:52 发布

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

我正在创建一个简单的shell程序,它接受用户对餐厅的命令。但是我很困惑如何接受来自用户的多个输入,以便shell可以读取它,然后将其解释为与调用的函数一起使用。在

iinventory = {
    "apple": 0,
    "beets": 0,
    "carrots": 0}

total=20

def handle_commands():
    keep_going=True
    while keep_going:
        command=input("$ ").split()
        var1=input()
        var2=input()
        if command == var1 + var2:
            var1="loadrecipefile"
            var2=recipe_file
            loadrecipefile(recipe_file)
        elif command == "printrecipes":
            printrecipes()
        elif command == "printiinventory":
            printiinventory()
        elif command == "printmoney":
            printmoney()
        elif command == "preparedish ":
            command=input().split(" ")
            preparedish(recipe_name)
        elif command == "buyingredient ":
            command=input().split(" ")
            buyingredient(name, number)
        elif command == "quit":
            keep_going=False
            break
        else:
            print("Sorry that is not an acceptable command")
    return 

def loadrecipefile (recipe_file):
    infile=open(recipe_file)
    Linelist=infile.readlines()
    for line in Linelist:
        wordList=line.split()
        r1={'apple':int(wordList[1]),'beets':int(wordList[2]),'carrots':int(wordList[3])}
        cookbook={wordList[0]:r1}

def printrecipes():
    for name,ingred in cookbook.items():
        print(name + " " + str(ingred['apple']) + " " + str(ingred['beets']) + " " + str(ingred['carrots']))

def buyingredient(name, number:int):
    global total
    total_spent=0
    if number + total_spent > total:
        print("Not enough cash!")
    iinventory[name] += number
    total -= number

def printiinventory():
    print(iinventory['apple'],iinventory['beets'],iinventory['carrots'])

def printmoney():
    print(total)

def CanPrepareDish(recipe_name):
    recipe = cookbook[recipe_name]
    for ingred in recipe:
        if ingred not in iinventory:
            return False
        if iinventory[ingred] < recipe[ingred]:
            return False
    return True

def preparedish(recipe_name):
    if not CanPrepareDish(recipe_name):
        print("Not enough ingredients")
    else:
        recipe = cookbook[recipe_name]
        for ingred in recipe:
            iinventory[ingred] -= recipe[ingred]
        if recipe_name in iinventory:
            iinventory[recipe_name] +=1
        else:
            iinventory[recipe_name] = 1
            print("Dish prepared")

handle_commands()

例如,如果用户要执行:

^{pr2}$

程序应该能够接受所有3个不同的输入,然后按空格分割输入,然后执行函数buy component。我不知道如何在一行命令中接受多个输入。在

而且,对于printrecipes()函数,我希望它打印在loadrecipefile函数中创建的烹饪书,但是它说没有定义烹饪书,所以我如何使用loadrecipefile函数中的食谱来处理printrecipes()。烹饪书是一本字典,我试着在函数之外设置cookbook={},但是printrecipes()只是将其打印为空白,而不是打印在loadrecipe文件中创建的食谱

def loadrecipefile (recipe_file):
    infile=open(recipe_file)
    Linelist=infile.readlines()
    for line in Linelist:
        wordList=line.split()
        r1={'apple':int(wordList[1]),'beets':int(wordList[2]),'carrots':int(wordList[3])}
        cookbook={wordList[0]:r1}
        print(cookbook)

例如,使用上面的代码,它将打印食谱:

loadrecipefile("recipe_file.txt")
{'Recipe1': {'apple': 1, 'beets': 4, 'carrots': 3}}
{'Recipe2': {'apple': 0, 'beets': 2, 'carrots': 4}}
{'Recipe3': {'apple': 3, 'beets': 0, 'carrots': 1}}
{'Recipe4': {'apple': 2, 'beets': 1, 'carrots': 0}}

使用printrecipes()它应该打印出来

Recipe1 1 4 3
Recipe2 0 2 4
Recipe3 3 0 1
Recipe4 2 1 0

任何帮助都将不胜感激。在


Tags: nameappledefrecipecommandfiletotalprint
1条回答
网友
1楼 · 发布于 2024-06-16 09:35:52

这个

command=input("$ ").split()
var1=input()
var2=input()

要求3个用户输入。第一个是你想分的。在

if command == var1 + var2:
    var1="loadrecipefile"
    var2=recipe_file
    loadrecipefile(recipe_file)

不会发生,因为command是一个列表(由于拆分),而var1和{}是字符串。在


您可以创建一个从输入命令函数调用的映射,作为dict,检查是否有足够的参数并继续:

创建一些函数存根来完成需要完成的操作(只需在此处打印):

def buySomething(what, howMany):
    print(what,howMany) 

def listThem(ingredient):
    print("Listing: ", ingredient)

def searchRecepie(receipt):
    print("Searching for:", receipt)

def error(line):
    print ("An error occured, try again", line)

def qexit():
    exit(0)

创建解析和映射:

^{pr2}$

输出:

$ buy apple 5
apple 5
$ list 9
Listing:  9
$ search popsickle
Searching for: popsickle
$ buy nothing
An error occured, try again ['buy', 'nothing'] # wrong amount of params error
$ cook me
An error occured, try again ['cook', 'me'] # unmapped command error 
$ q 

您可能应该为“不在命令列表中”和“提供的参数不足/太多”创建不同的(更适合)错误函数


阅读这个伟大的Q/A中的用户输入验证:Asking the user for input until they give a valid response

相关问题 更多 >