Skip to content
Advertisement

Python 3: Calculating percentage change with n number of values

I have a function which should calculate percentage increase / decrease between two values. The parameters in the function are original_value and new_value.

Problem: I need the program to take n number of values, for example, six values, and then run the function on every pair of values. An example:

The values are 1, 2, 3, 4, 5 and 6. I then need the program to calculate the avg. percentage change between 1 and 2, 2 and 3, 3 and 4, 4 and 5, and 5 and 6.

I thought this would be best by making the aforementioned function, then running the function on every pair of values. The question is how should I get the program to run the function on every pair (the number of values / pairs varying)? The values are being entered by the user as keyboard input. The user first specifies how many values they want to enter, and then enters each value. The values are stored in a list atm.

Advertisement

Answer

def percentage_change():
    value_list = []
    number_of_values = int(input("How many values are there?"))
    counter = 0
    while counter < number_of_values:
        value = float(input("Enter value: "))
        value_list.append(value)
        counter += 1
    list_index = 0
    percentages = []
    while list_index < len(value_list) - 1:
        percentage_change = #execute whatever formula you want to use to calculate percentage change here
        percentages.append(percentage_change)
        list_index += 1
    #average percentages
    #print values
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement