[英]How do I end a for-loop without printing numerous times in an if-else statement after parsing information from a JSON URL
我设置了我的代码,用户可以通过用户输入从 JSON URL 中提取信息。 但是,我想添加一个条件,在找不到用户输入的信息时告诉用户“无记录”。 这是我的代码:
import datetime
from datetime import date
import requests
import simplejson as json
response = requests.get("https://api.covidtracking.com/v1/states/daily.json")
json_test = response.json()
print("Enter the state for which the COVID data should be retrieved (e.g. TX): ")
user_state = input()
print("Enter the date for which the COVID data should be retrieved (e.g. 20201219): ")
user_date = input()
count = 0
for i in json_test:
i = count
count = count + 1
state = (json_test[i]['state'])
dates = (json_test[i]['date'])
death = (json_test[i]['death'])
positive = (json_test[i]['positive'])
positiveIncrease = (json_test[i]['positiveIncrease'])
deathIncrease = (json_test[i]['deathIncrease'])
if state == user_state and str(dates) == user_date:
cv_state = state
cv_date = dates
cv_death = death
cv_positive = positive
cv_positiveIncrease = positiveIncrease
cv_deathIncrease = deathIncrease
print("===============")
print("State: " + str(cv_state))
print("Date: " + str(cv_date))
print("Positive Cases: " + str(cv_positive))
print("Death(s): " + str(cv_death))
print("===============")
else:
print("No Record")
该代码有效如果我输入了正确的信息,但即使找到了记录,它仍然会多次输出“No Records”。 这是 output:
===============
State: AK
Date: 20200315
Positive Cases: None
Death(s): 0
===============
No Record
No Record
No Record
No Record
No Record
No Record
No Record
No Record
No Record
No Record
No Record
No Record
No Record
No Record
No Record
它输出“无记录”的方式更多,但我如何解决这个问题,它只显示一次无记录,并且只有在找不到记录的情况下
这可能工作正常:
import datetime
from datetime import date
import requests
import simplejson as json
response = requests.get("https://api.covidtracking.com/v1/states/daily.json")
json_test = response.json()
print("Enter the state for which the COVID data should be retrieved (e.g. TX): ")
user_state = input()
print("Enter the date for which the COVID data should be retrieved (e.g. 20201219): ")
user_date = input()
status = False
count = 0
for i in json_test:
i = count
count = count + 1
state = (json_test[i]['state'])
dates = (json_test[i]['date'])
death = (json_test[i]['death'])
positive = (json_test[i]['positive'])
positiveIncrease = (json_test[i]['positiveIncrease'])
deathIncrease = (json_test[i]['deathIncrease'])
if state == user_state and str(dates) == user_date:
status = True
cv_state = state
cv_date = dates
cv_death = death
cv_positive = positive
cv_positiveIncrease = positiveIncrease
cv_deathIncrease = deathIncrease
print("===============")
print("State: " + str(cv_state))
print("Date: " + str(cv_date))
print("Positive Cases: " + str(cv_positive))
print("Death(s): " + str(cv_death))
print("===============")
if(status==False):
print("No Records")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.