Loving Python so much .. but Number Triangles!


#1

Hey/Aweh/How are you all?
I’m writing this is in hopes to get a response soon. I will add some images…

I’m really batteling with the formats in Python. For example : nested if statements or for statements.

Example 1.

#prints out first 5 multiples of numbers 1 - 5.

for x in range(1, 6):
for y in range(1, 6):
print(’%d*%d=%d’ % (x,y,xy))
print.("")
=====================================Inui understand everything up till line 3. Where does %d come from, also why is there another % in the middle? Lastly I understand x
y but why (x,y,x*y)?

Now example 2
===≠===================================

see picture. I have to use nested for loops to create a table that reassembles this one.

After. hOURS of playing around I finally got to my code…
for I in range(1, 10):
for y in range(i + 1):
print(i*y, end= “\t”)
print("\n")

This works almost perfect except that it displays a " 0 " in front of each row, which I don’t want !

=======================================
I hope someone can assist and help me better understand.

Kind regards
Jay :slight_smile:


#2

OK, in example 1, you’re using the feature in Python where % indicates string substitution. The left-hand operand (before ‘%’) is the string pattern, including places to substitute actual values defined by %d for a number, %s for a string, etc. The right-hand operand (after ‘%’) is a tuple of numbers to substitute. Here you’ve supplied (x, y, xy). So the first one (x) goes in place of the first %d; the second one (y) goes in place of the second %d; and the last one (xy — which I think should have been x*y) goes in place of the last %d.

In example 2, the initial 0 on each row is because your inner loop uses range(i+1). When you use range() with a single argument in Python, it counts from 0 up to that number. So that’d be counting from 0 to i in this case. If you want to count from 1 to i you should instead use range(1, i+1).


#3