ahap13
ahap13

Reputation: 1

For loop not iterating completely through

I am working on a project that consists of calling an API and returning per diem rates that are given when on company travel. Since travel rates change by month, I must account for if the travel goes across months. When this occurs, I am compiling the rates into an array and then returning that. However, whenever I run the for loop that produces the array, it only returns the first value. Any help is greatly appreciated! I have the section of my code below:

    if month1 != month2:
        per_diem_rates = []
        if int(month2) < int(month1):
            months = list(range(int(month1), 13))
            months2 = list(range(1, int(month2) + 1))
            months += months2
        else:
            months = list(range(int(month1), (int(month2) + 1)))

        for i in months:
            rate = r["rates"][0]["rate"][0]["months"]["month"][i - 1]["value"]
            per_diem_rates.append(rate)
            return per_diem_rates
    else:
        return per_diem_rate

The dates I am querying span from Sep to Nov, which means I should be getting three different rates for each month. Thank you!

Upvotes: 0

Views: 24

Answers (1)

johnny b
johnny b

Reputation: 862

Your indentation is wrong. The function will return after the first iteration in the loop. Change it like that:

        for i in months:
            rate = r["rates"][0]["rate"][0]["months"]["month"][i - 1]["value"]
            per_diem_rates.append(rate)
        return per_diem_rates

Upvotes: 1

Related Questions