Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我一直得到缩进错误:未缩进不匹配任何外部缩进级别_Python_Python 3.x - Fatal编程技术网

Python 我一直得到缩进错误:未缩进不匹配任何外部缩进级别

Python 我一直得到缩进错误:未缩进不匹配任何外部缩进级别,python,python-3.x,Python,Python 3.x,下面是我的代码,我很新,所以我确信这只是我这方面的一个业余错误 def availability(): r = requests.get('https://planet54.com/products/strappy-casual-dress-black.json') blackdress =json.loads((r.text))['product']['title'] productname = blackdress for blackdress in p

下面是我的代码,我很新,所以我确信这只是我这方面的一个业余错误

def availability():
    r = requests.get('https://planet54.com/products/strappy-casual-dress-black.json')
    blackdress =json.loads((r.text))['product']['title']
    productname = blackdress

      for blackdress in productname:

       if productname == 'Strappy Casual Dress - Black':
            producturl = 'https://planet54.com/products/strappy-casual-dress-black'

          return producturl

    return False 

与其他忽略空白的语言不同,它在python中有一个非常特殊的函数。Python语言使用缩进来嵌套和定义代码结构和代码块。因此,您需要确保缩进在代码中是一致的

def可用性():
r=请求。获取('https://planet54.com/products/strappy-casual-dress-black.json')
blackdress=json.load((r.text))['product']['title']
productname=blackdress
对于productname中的blackdress:
如果productname=='Strappy休闲连衣裙-黑色':
producturl=https://planet54.com/products/strappy-casual-dress-black'
返回产品URL
返回错误

这似乎正是您想要的

def availability():
  r = requests.get('https://planet54.com/products/strappy-casual-dress-black.json')
  blackdress =json.loads((r.text))['product']['title']
  productname = blackdress

  for blackdress in productname:
    if productname == 'Strappy Casual Dress - Black':
      producturl = 'https://planet54.com/products/strappy-casual-dress-black'
      return producturl

  return False 

但是请注意,如果找到条件,if语句中的返回将导致for循环提前退出。

python使用缩进定义代码块。因此,您不能混合和匹配缩进,它需要一致性。您的for循环似乎是无缘无故缩进的。此外,
if
语句中的缩进不一致。此外,根据if块中的语句,您的第一次返回的位置不正确。Python依靠适当的缩进来避免像在其他语言中那样使用{}或end if语句。如果没有适当的缩进,Python就不知道如何处理代码。在这一点上,我假设您希望检查每个产品名称,看看它是否与您在if语句中提出的条件相匹配。如果是这样的话,请检查我的答案。我建议(1)查看(2)使用编辑器或IDE检测并显示代码上可能的缩进错误(甚至在运行之前),无论条件如何,这都将在第一次循环后“返回”。我不认为这是OP想要的,他们可能想要遍历整个
productname
变量,看看是否有匹配某个名称的变量,而不仅仅是第一个产品。很好。在if中缩进退货