【问题标题】:Python & API user inputPython & API 用户输入
【发布时间】:2020-04-30 00:24:19
【问题描述】:

我的代码是

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 顺便说一句)

【问题讨论】:

  • 请提供MRE 否则很难理解您在问什么。听起来您在字符串之外放入“and”,在这种情况下,Python 会将其解释为布尔运算的关键字“and”
  • @ch4rl1e97,python 不会将"and" 字符串解释为关键字and
  • 不是我的意思@HarshalParekh 我的意思是and"and" 对于Python 来说是两个不同的东西。因此,我说“听起来你正在将字符串放入和 之外......”

标签: python api input syntax


【解决方案1】:

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

你可以像这样修复它:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 2019-10-13
    • 2022-01-06
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多