0

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.

1 Answers1

0
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
Gavin Wong
  • 1,254
  • 1
  • 6
  • 15
  • The last while loop will iterate over each pair of values (i.e 1 and 2, 2 and 3, 3 and 4...etc). Enter the percentage change formula inside the while loop and it will calculate each percentage change and append in to the percentages list. – Gavin Wong Aug 17 '20 at 11:34
  • Thank you for your quick and thorough reply. Easy and understandable. I have one more question, in line 12, what is the best way to choose the correct entries in value_list? [list_index + 1, list_index + 2]? Will this work? – T-StoneLeif Aug 17 '20 at 11:59
  • Just call the two values value_list[list_index] and value_list[list_index + 1]. – Gavin Wong Aug 17 '20 at 12:55
  • Please accept/upvote my answer if it works! Thanks :) – Gavin Wong Aug 17 '20 at 12:55
  • The program timeouts after I have entered how many values there are. I have tried different approaches, but the code always timeouts ("Enter value: " never appears). Any thoughts? – T-StoneLeif Aug 18 '20 at 07:20
  • Have you made sure that your code is indented exactly as the code I have provided? – Gavin Wong Aug 18 '20 at 07:23
  • It might occur if counter += 1 is outside the loop. Otherwise I don't see how the program can timeout – Gavin Wong Aug 18 '20 at 07:23
  • The problem was vscode, not the code itself. Thank you. – T-StoneLeif Aug 18 '20 at 11:34