0

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?

3
  • 1
    Because you are using the same identifier num_rows and num_cols for the previously befined variables and the ones used in the for loop. Rename the latest ones to something like row and col instead of num_rows and num_cols. Commented Oct 21, 2017 at 14:51
  • That's it, thank you. I was scouring my books and I didn't realize that was the error I was making. Commented Oct 21, 2017 at 14:56
  • 1
    Basically you were overwriting the original num_rows and num_cols in the loop. Commented Oct 21, 2017 at 15:00

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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 ''

Comments

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.