[英]How to print the variable inside the function
我的代碼如下。 試圖在函數內打印htmlStr
。 有什么辦法
import urllib.request
import re
url = 'http://dummy.restapiexample.com/api/v1/employees'
def testhtml(self):
response = urllib.request.urlopen(url)
htmlStr = response.read().decode('ISO-8859-1')
with open("html.csv","a+") as file:
file.write(htmlStr)
pdata = re.findall(r'"employee_name":"(\'?\w+)"', htmlStr)
return pdata
print(htmlStr) 我做的函數外拋出錯誤
當我print (htmlStr)
出現錯誤NameError: name 'htmlStr' is not defined
您收到錯誤是因為您試圖訪問其域之外的局部變量。
這是您的代碼中的樣子:
# 1. Begin creating your function
def testhtml(self):
# 2. This is a local environment.
# Any variables created here will not be accessible outside of the function
response = urllib.request.urlopen(url)
# 3. The local variable `htmlStr` is created.
htmlStr = response.read().decode('ISO-8859-1')
with open("html.csv","a+") as file:
# 4. Your local variable `htmlStr` is accessed.
file.write(htmlStr)
pdata = re.findall(r'"employee_name":"(\'?\w+)"', htmlStr)
return pdata
# 5. Your function is now complete. The local variable `htmlStr` is no longer accessible.
那有意義嗎? 如果你想打印你的函數(在調試時),你可以在函數中放置一個打印語句。 (只需確保最終將其刪除以防止雜亂無章的控制台讀數。)如果您需要訪問函數外部的變量,請考慮將其包含在輸出中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.