Storing updated variables in a loop?
<p>I have written this program which asks the user about how many rectangles they wants to print out. It also asks for the width and height of each, and prints the triangles. After asking the height and width of each, it moves onto the next rectangle and so on. </p>

<p>This all works fine using the program I've made but at the end I want to print out the total area of all the rectangles that the user has created. How can I update my code and achieve this? How is it possible to store the area of the first rectangle and add the area of the second to this first area and so on?
Here is the code:</p>

<pre><code>size = input("How many rectangles?" ) #asks the number of rectangles 
i=1
n = 1
while i &lt;= size:
    w = input("Width "+str(n)+"? ") #asks for width of each rectangle
    h = input("Height "+str(n)+"? ") #asks for height of each rectangle
    n=n+1
    h1=1
    w1=1
    z = ""
    while w1 &lt;= w:
        z=z+"*"
        w1+=1
    while h1&lt;=h:
        print z
        h1+=1
    i+=1
</code></pre>

<p>This code should really use a for loop instead of a while loop to keep track of counters, keep numbers in variables instead of just "*" strings, and use += instead of x=x+1 in a few places, among other things, but here's a minimal step to solve the total area problem you specifically asked about:</p>

<pre><code>size = input("How many rectangles?" ) #asks the number of rectangles 
i=1
n = 1
area = 0
while i &lt;= int(size):
    w = float(input("Width "+str(n)+"? ")) #asks for width of each rectangle
    h = float(input("Height "+str(n)+"? ")) #asks for height of each rectangle
    n+=1
    h1=1
    w1=1
    z = ""
    while w1 &lt;= w:
        z=z+"*"
        w1+=1
    while h1&lt;=h:
        print(z)
        h1+=1
        area += len(z)
    i+=1
print('total area = ',area)
</code></pre>

python python-2.7