繁体   English   中英

简单的打印语句不适用于python中的if语句的方法

[英]simple print statement is not working inside method with if statement in python

我最近开始学习Python代码,自最近4天以来,一个简单的打印语句就给我带来了麻烦。

问题:对于if语句,print语句在validatePostcode(postcode)方法中不起作用。 分配的值是200(状态代码),可以在没有if语句的情况下正常打印。 另外,当我与该API的True(结果值)进行比较时,如果没有if语句,它也可以正常工作,为什么在应用if并尝试进行比较之后它不起作用?

错误:

  File "./py_script3.py", line 32
    print ("Congrats")
        ^
IndentationError: expected an indented block

    #!/usr/bin/env python3


    import os,re,sys


    import urllib.request as req
    import json

    def loadJsonResponse(url):
        #return json.loads(req.urlopen(url).read().decode('utf-8'))['result']
        #return json.loads(req.urlopen(url).read().decode('utf-8'))['status']
        print ("I am in loadJsonResponse before returning string")
        string = json.loads(req.urlopen(url).read().decode('utf-8'))
        return string
        print ("I am in loadJsonResponse after returning string")

    def lookuppostcode(postcode):
        url = 'https://api.postcodes.io/postcodes/{}'.format(postcode)
        return loadJsonResponse(url)

    def validatePostcode(postcode):
        url = 'https://api.postcodes.io/postcodes/{}/validate'.format(postcode)
        #return loadJsonResponse(url)
        string = json.loads(req.urlopen(url).read().decode('utf-8'))
        Value = str(string['status'])
        print (Value)
        if Value == 200 :
        print ("Congrats")

    def randomPostcode():
        url = 'https://api.postcodes.io/random/postcodes'
        return loadJsonResponse(url)

    def queryPostcode(postcode):
        url = 'https://api.postcodes.io/postcodes?q={}'.format(postcode)
        return loadJsonResponse(url)

    def getAutoCompletePostcode(postcode):
        url = 'https://api.postcodes.io/postcodes/{}/autocomplete'.format(postcode)
        return loadJsonResponse(url)

    #Input = input("Enter the postcode : ")
    #print(lookuppostcode('CB3 0FA'))
    validatePostcode('CB3 0FA')
    #print(queryPostcode('HU88BT'))
    #print(randomPostcode(Input))

您应该像这样缩进打印语句:

if Value == 200 :
   print ("Congrats")

您可以在此处了解更多信息!

https://docs.python.org/2.0/ref/indentation.html

逻辑行开头的前导空格(空格和制表符)用于计算行的缩进级别,而缩进级别又用于确定语句的分组。

通过做

if Value == 200:
print ("Congrats")

Python将这两行解释为两组不同的语句。 您应该做的是:

if Value == 200:
    print ("Congrats")

这段代码(正在生成错误):

if Value == 200 : 
print ("Congrats")

应该

if Value == 200 : 
    print ("Congrats")

因为python在条件之后期望缩进块,就像消息错误对您说的那样

需要在if语句后添加缩进。 您可以在输入冒号后按回车键

暂无
暂无

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

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