0

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.

1 Answer 1

2

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='')
Sign up to request clarification or add additional context in comments.

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.