簡體   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