David Scott II
David Scott II

Reputation: 3

Using a nested for loop in python to print a rectangle

I saw my same question asked but I want to know why what I'm trying isn't working. This is from a Zybook challenge question.

Here is the exercise:

Write nested loops to print a rectangle. Sample output for given program:

* * *  
* * *

This is the code I built:

num_rows = 2
num_cols = 3

for num_rows in range(0,num_rows):
    for num_cols in range(0,num_cols):
        print('*', end=' ')
    print('')

The output is:

* * *
* * 

Question: Why doesn't the nested for loop print statement iterate for the third time? When I set the nested loop to:

for num_cols in range(0,3):  

I receive my desired output of the 3x2 asterisk rectangle. If the num_cols variable is declared as 3, shouldn't the output statement equal my desired output?

Upvotes: 0

Views: 7111

Answers (2)

BoltzmannBrain
BoltzmannBrain

Reputation: 5412

Following up @Karthik's reasoning of why your code is incorrect, here's a solution with misc. improvements:

num_rows = 2
num_cols = 3

for _ in xrange(num_rows):       # xrange for efficient iteration
    for _ in xrange(num_cols):   # no need to unpack iteration variable
        print '*',               # for Python 2, but use the function syntax for 3+
    print ''

Upvotes: 0

Karthik
Karthik

Reputation: 36

You are overwriting the num_cols variable by using it as the looping variable as well as the number of columns value. It gets set to 2 during the end of the first iteration of the outer loop. You can replace it with num_col. Same applies for num_rows as well

Upvotes: 1

Related Questions