我需要帮助来理解此代码。我无法理解循环。有人可以分解并解释吗? “ i = 0”在此程序中代表什么。这是示例代码。我的作业是为丢失和无效的数据添加错误处理。我非常感谢。谢谢!
import os
import urllib.request as ur
def process_file(link):
data = ur.urlopen(link)
fields = ["TITLE", "ARTIST", "COUNTRY", "COMPANY", "PRICE", "YEAR"]
title = []
artist = []
country = []
company = []
price = []
year = []
for line in data:
line = line.decode('utf-8')
line = line.lstrip()
line = line.rstrip()
tag = ""
value = ""
i = 0
while i < len(line):
if line[i] == '<':
i = i + 1
while i < len(line) and line[i] != '>':
tag += line[i]
i = i + 1
if tag not in fields:
break;
i = i + 1;
while i < len(line) and line[i] != '<':
value += line[i]
i = i + 1
break;
if tag == "TITLE":
title.append(value)
elif tag == "ARTIST":
artist.append(value)
elif tag == "COUNTRY":
country.append(value)
elif tag == "COMPANY":
company.append(value)
elif tag == "PRICE":
price.append(float(value))
elif tag == "YEAR":
year.append(int(value))
return title,artist,country,company,price,year
def display(title, artist, country, company, price ,year):
for i in range(len(title)):
print(title[i] , " - ", artist[i], " - ", country[i], " - ", company[i], " - ", price[i], " - ", year[i])
return
def calculate_average(price):
sum = 0.0
if len(price) == 0:
return sum
for value in price:
sum = sum + value
return sum/len(price)
if __name__ == '__main__':
link = "https://www.w3schools.com/xml/cd_catalog.xml"
title, artist, country, company, price ,year = process_file(link)
display(title, artist, country, company, price ,year)
print((len(title)), " items - $" , round(calculate_average(price),2), " average price")
我可以解释一下。
I = 0
这将创建一个名为I的新变量,并将其设置为零。
while I < Len (line)
这意味着在此循环中执行的所有代码将继续执行,直到我大于行数为止。如您所见,在循环中,它将i加1。这意味着直到循环结束还需要几秒钟。