首页 > 解决方案 > Python & API 用户输入

问题描述

我的代码是

import requests
from pprint import pprint

from pip._vendor.distlib.compat import raw_input

recipe_ingredients = input("What is the recipe ingredients? ")
number_recipes = input("How many recipes do you want? ")
url = 'https://api.spoonacular.com/recipes/findByIngredients?ingredients={}&number={}&'.format(recipe_ingredients,number_recipes)

response = requests.get(url)
print(response)

但是,当我以(两种成分)奶酪和土豆的格式输入多个成分时,它会返回第一个变量的结果,或者告诉我and存在语法错误。

有什么方法可以让我的搜索功能接受显示这两个词的所有结果,因为用户很可能会在搜索多个成分时输入“和”。

(我正在使用pycharm顺便说一句)

标签: pythonapiinputsyntax

解决方案


您只向用户请求一个字符串。每当您尝试输入以 分隔的 2Enter个字符串时,第二个字符串将无法保存,因此会出现异常。

您可以像这样修复它:

n = int(input("Number of ingredients: "))
recipe_ingredients = []

print("Enter " + str(n) + " recipe ingredients")

for i in range(n):
    recipe_ingredients.append(input())

推荐阅读