On October 2022 I started my MSc in Data Science. I never coded before. My academical background is I achieved a Bachelor’s Degree of Economics five years ago.
The teacher of subject of Python put the following problem:
There’s an API called http://numbersapi.com . This API is about number-facts and you can check in this API a fact about any year i.e: http://numbersapi.com/1492/year.
In this example if you check this URL it will show "1492 is the year that Ferdinand and Isabella enter into Granada on January 6th."
The statement continues with:
Construct a function that has two years FY (first year) and LY (last year) as arguments. The function must collect the facts from the year FY to the year LY inclusive, and return a dictionary where the keys are the year and the values are the fact about this year.
Once I understood the APIs I coded this:
import requests
FY = 2015
LY = 2022
a = (f'http://numbersapi.com/{FY}/year')
url_1 = requests.get(a)
print(url_1.text)
while FY < LY:
b = (f'http://numbersapi.com/{FY+1}/year')
url_n = requests.get(b)
print(url_n.text)
FY += 1
if LY - FY <0:
print(AI)
elif LY - FY ==0:
break
I realized that my previous code is not inside a function neither have dictionaries.
Then, I tried to put this inside a function:
import requests
FY = 2015
LY = 2022
def query(url_1, url_n):
a = (f'http://numbersapi.com/{FY}/year')
url_1 = requests.get(a)
print(url_1.text)
while FY < LY:
b = (f'http://numbersapi.com/{FY+1}/year')
url_n = requests.get(b)
print(url_n.text)
FY += 1
if LY - FY <0:
print(FY)
elif LY - FY ==0:
break
return FY, LY
print(url_1, url_n)
Once I executed I got:
<Response [200]> <Response [200]>
And here is where I am stuck up.
2
Answers
The parameters of the function should be
FY
andLY
and when you want to execute the function, you have to call the function name with the set of required parameters.UPDATE
use
.replace()
to replace year with a space and use.strip()
to remove any surrounding space.However, your function can be shorter as below:
output:
In general functions take arguments from the user as parameters. So in your case, you want to keep the link as it is and change the years that you get as input.