Python Forum
Nested for Loops - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Nested for Loops (/thread-31911.html)



Nested for Loops - sammay - Jan-09-2021

Hey everybody,
Hope everything goes well,
As I am a newcomer in Python, I have difficulty in understanding the way Python calculate nested loops.

Here is my exact question:
I'm trying to print triangle with stars,

line 1: for num in range (6):
line 2: stars = ' '
line 3: for x in range(num):
line 4: stars += '*'
line 5: print(stars)

Output:

line 1: null
line 2: *
line 3: **
line 4: ***
line 5: ****
line 6: *****
--------------------------------------------------------------------
What I've found is that when I write line 1, the Python considers 6 row, and for line 3, Python considers 5 columns. when num=0 , x=null, and for num=1 , x=0, and so on.
why for num=0 Python collect x=null?

Thank you so much in advance for your consideration


RE: Nested for Loops - deanhystad - Jan-09-2021

I think this is your program
for num in range (6):
    stars = ' '
    for x in range(num):
        stars += '*'
    print(stars)
When I run this program it does not print "null". The first line is blank (actually it has one space). Is that what you mean by null?

The reason the first line is blank is because num = 0. Since num is the number of '*' appended to stars, appending zero '*' should give you a zero stars. Right?

Is your confusion about the for loops starting at 0? This is the fault of the range function, not the for loop. range(6) will return 0, 1, 2, 3, 4, 5. If you want range to start with something other than 0 you need to specify the starting value in the call. To always print at least 1 star you can change your code to look like this:
for num in range (1,7):
    stars = ' '
    for x in range(num):
        stars += '*'
    print(stars)
Output:
* ** *** **** ***** ******
The reason I use range(1, 7) is because I want 1 to be the first number in my range and 7 to be the first number not in my range.