How can I put this code inside a function?

Question:

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.

Asked By: Uri

||

Answers:

The parameters of the function should be FY and LY 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.

def get_year_fact(start_year, end_year):
    output_dict = {}
    url_1 = requests.get(f'http://numbersapi.com/{start_year}/year')
    output_dict[start_year] = url_1.text.replace(f'{start_year} is', '').strip()
    while start_year < end_year:
        url_n = requests.get(f'http://numbersapi.com/{start_year+1}/year')
        output_dict[start_year+1] = url_n.text.replace(f'{start_year+1} is', '').strip()
        start_year += 1
        if end_year - start_year <0:
            print(start_year)
        elif end_year - start_year ==0:
            break
    return output_dict

# call function
output_dict = get_year_fact(FY, LY)
output_dict

However, your function can be shorter as below:

def get_year_fact(start_year, end_year):
    output_dict = {}
    for year in range(start_year, end_year+1):
        url = requests.get(f'http://numbersapi.com/{year}/year')
        output_dict[year] = url.text.replace(f'{year} is', '').strip()
    return output_dict

output:

> output_dict

{2015: 'the year that the Voyager 1 space probe will reach the heliopause.',
 2016: 'the year that the II Winter Youth Olympic Games will be held in Lillehammer, Norway on February - March 6 26th.',
 2017: 'the year that the first possible government in Hong Kong elected by universal suffrage is scheduled to take office on July 1st.',
 2018: 'the year that we do not know what happened.',
 2019: 'the year that an annular solar eclipse will be visible from South Asia on December 26th.',
 2020: 'the year that the main segment of track extending from San Francisco to Anaheim of the California High Speed Rail system is expected to be completed.',
 2021: 'the year that Earliest expected date for the first manned Orion mission.',
 2022: "the year that FIFA's World Cup will be hosted by Qatar."}
Answered By: JayPeerachai

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.

import requests

def query(FY, LY):
    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


query(2015,2022)
Answered By: needHelpToCode
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.