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

时间:2018-10-11 00:29:57

标签: python python-3.x

最近我开始学习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))

4 个答案:

答案 0 :(得分:0)

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

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

您可以了解有关此here的更多信息!

答案 1 :(得分:0)

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

  

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

这样做

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

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

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

答案 2 :(得分:0)

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

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

应该是

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

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

答案 3 :(得分:0)

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

相关问题