繁体   English   中英

python 中的 IndentationError - 我的代码有什么问题?

[英]IndentationError in python - what is wrong in my code?

import requests
import json

url='https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY'    
headers= {'user-agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Safari/537.36',
"accept-language":"en-US,en;q=0.9","accept-encoding":"gzip, deflate"} 
def fetch_oi():  
r=requests.get(url,headers=headers).json()
print(r)
with open("oidata.json","w") as files:
    files.write(json.dumps(r,indent=4, sort_keys=True))

def main():
    fetch_oi()


if __name__=='__main__':
    main()

** 在这段代码中,我在 r=requests.get(url,headers=headers).json() 中遇到错误 ^ IndentationError: expected an indented block

我在做什么错? 请帮忙

函数定义中的代码需要缩进。

import json

url='https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY'    
headers= {'user-agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Safari/537.36',
"accept-language":"en-US,en;q=0.9","accept-encoding":"gzip, deflate"} 

def fetch_oi():  
    r=requests.get(url,headers=headers).json()
    print(r)
    with open("oidata.json","w") as files:
        files.write(json.dumps(r,indent=4, sort_keys=True))

def main():
    fetch_oi()


if __name__=='__main__':
    main()

Python 在很大程度上依赖于正确的缩进,请参阅: https : //www.w3schools.in/python-tutorial/concept-of-indentation-in-python/

在你def fetch_oi():你应该缩进r=requests.get(url,headers=headers).json()因为它是一个函数

def fetch_oi():  
    r=requests.get(url,headers=headers).json()
    print(r)

然后根据您的功能结束的位置,您应该继续缩进

我相信很明显你需要

def fetch_oi():  
    r=requests.get(url,headers=headers).json()
    print(r)
    with open("oidata.json","w") as files:
        files.write(json.dumps(r,indent=4, sort_keys=True))

而不是你所拥有的(在 fetch_io 中又多了一个标签)。 在 python 中,你必须小心使用标签。 每个函数后都需要一个标识级别。 看看这里: https : //docs.python.org/2.0/ref/indentation.html

函数fetch_oi的主体是无缩进的。

import requests
import json

url='https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY'    
headers= {'user-agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Safari/537.36', "accept-language":"en-US,en;q=0.9","accept-encoding":"gzip, deflate"} 

def fetch_oi():  
    r=requests.get(url,headers=headers).json()
    print(r)

    with open("oidata.json","w") as files:
        files.write(json.dumps(r,indent=4, sort_keys=True))

def main():
    fetch_oi()

if __name__=='__main__':
    main()

def fetch_oi() 之后的意图行:

问题在正文中

def fetch_oi(): 

为身体留出空间

我的建议是使用 sublime IDE。 因此,当您选择内容时,您可以看到已使用空格或标签的内容。 同样使用制表符是好方法而不是空格

我已经看到你使用了空间。 所以从长远来看,调整和使用空间会让你很麻烦。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM