hn_03
hn_03

Reputation: 97

Making pattern in Python using nested loop

I was trying to making a simple pattern that allows the user to decide the numer of rows and columns, for example:

How many rows: 5
How many columns: 5
>>>
*****
*****
*****
*****
*****

So my code is like this:

row = int(input('How many rows: '))
col = int(input('How may columns: '))
for row in range(row):
    for col in range(col):
        print ('*', end='')

But the result is this:

*****
****
***
**
*

I realized that I assigned the variable name for the variable of the for loop the same as the variable for my input. I, however, don't understand the logic for that code. It would be great if you guys can explain to me something like a flowchart.

Upvotes: 0

Views: 1128

Answers (1)

Dan D.
Dan D.

Reputation: 74655

This loops col times and then results in col being set to col - 1

for col in range(col):

Due to range(col) looping over 0 to col - 1 and due to the fact that after a loop finishes the loop variable is at that time set to the value from the iteration when the loop exited.

You should use different names for the loop indexes.

row = int(input('How many rows: '))
col = int(input('How may columns: '))
for row_ in range(row):
    for col_ in range(col):
        print ('*', end='')

Upvotes: 2

Related Questions