如何查找在输入语句中选择了哪个数字参数?

时间:2019-02-06 17:33:18

标签: python python-3.x

变量或类型和成本:

pasta_types = "Lasagne, Spaghetti, Macaroni, Cannelloni, Ravioli, Penne, Tortellini, Linguine, Farfalle, Fusilli"
pasta_costs = "6.00, 4.00, 3.15, 8.50, 9.00, 3.15, 5.00, 4.00, 4.25, 4.75"

查看输入内容是否具有可变类型的面食的函数:

def inventory(pt):
    return(pt.title() in pasta_types)

输入:

type = input('What pasta would you like: Lasagne, Spaghetti, Macaroni, Cannelloni, Ravioli, Penne, Tortellini, Linguine, Farfalle, and Fusilli  ')

调用函数:

have = inventory(type)

如何找出选择了多少个参数?

1 个答案:

答案 0 :(得分:0)

这是一个类似的示例,该示例构建并使用字典将每种面食类型的名称与其成本相关联:

pasta_types = "Lasagne, Spaghetti, Macaroni, Cannelloni, Ravioli, Penne, Tortellini, " \
              "Linguine, Farfalle, Fusilli"
pasta_costs = "6.00, 4.00, 3.15, 8.50, 9.00, 3.15, 5.00, 4.00, 4.25, 4.75"

# Create a dictionary associating (lowercase) pasta name to its (float) cost.
inventory = dict(zip(pasta_types.lower().replace(' ', '').split(','),
                     map(float, pasta_costs.replace(' ', '').split(','))))

## Display contents of dictionary created.
#from pprint import pprint
#print('inventory dictionary:')
#pprint(inventory)

while True:
    pasta_type = input('What pasta would you like: ' + pasta_types + '?: ')
    if pasta_type.lower() in inventory:
        break  # Got a valid response.
    else:
        print('Sorry, no {!r} in inventory, please try again\n'.format(pasta_type))
        continue  # Restart loop.

print('{} costs {:.2f}'.format(pasta_type, inventory[pasta_type]))