![](/img/trans.png)
[英]Python | simple if/else statement inside for loop - not working
[英]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))
從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.