0

I want to save the result of my while loop every time it runs to an array. Then once all conversions have been run, the array that stores all the values will be summed.

raw_user_age = input("Number: ")

x = int(raw_user_age)

g=0

while g < x :
    if __name__ == "__main__":
        
        YOUR_ACCESS_KEY = ''
        url = 'https://api.exchangerate-api.com/v4/latest/USD'
        c = Currency_convertor(url)
        from_country = input("From Country: ")
        to_country = input("TO Country: ")
        amount = int(input("Amount: "))
        
        returnedamount=c.convert(from_country, to_country, amount)
        g += 1
        print(returnedamount)

2 Answers 2

1

First create your array before the beginning of the loop:

values_returned = []

You can use the append method to add an element to the array every time the loop runs:

values_returned.append(returnedamount)

After the loop is done, you can use the sum() function to get the sum of all values in the array:

sum(values_returned)
Sign up to request clarification or add additional context in comments.

4 Comments

Ok thank you very much this will make life much easier.
You're welcome.
When I ran the sum(values_returned) command and then print(values_returned) it didn't return the sum of the 2 values rather it printed both values instead of their sum. How do I fix this?
sum(values_returned) returns the sum, so you would have to rather print(sum(values_returned)).
1

You can simply append the value to the array (list) like so:

list_ = []

value1 = 1
value2 = 2

list_.append(value1)
list_.append(value2)

2 Comments

To get the sum of the list_ just use the in-built function sum()
Where exactly would I put this in terms of the code? and what should I change value1 or value 2 to for it to append.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.