Reputation: 181
I am trying to make a for double for-loop where the inner loop has the same range as the i in the outer loop. This would basically be what I want, but (obviously) it doesn't work:
num = 1
totalrow = range(5)
rownum = range(num)
for i in totalrow:
for x in rownum:
do stuff
num = num + 1
print (stuff)
So what I would like to happen, is to get 5 loops, where the first loop gives 1 result, second loop gives 2 results, etc. I don't know if it's needed for more clarification, but I am trying to create the drinking game ride the bus in python and I need this loop for the pyramid round. Is it possible like this or do need to find a different way to solve this problem? Thanks in advance.
EDIT
The result I was looking for was achieved by using this code:
for i in range(6):
for j in range(i):
card = random.choice(deck)
deck.remove(card)
print (card)
This gives me 15 cards from the deck of cards I generated. I wanted to have a double for-loop so I can tell the difference between each 'row' of cards. Right now I am not interested in the output yet, but for anyone who is, down below in the answers smarx shows a couple of nice ways to print the result.
Upvotes: 1
Views: 1388
Reputation: 60143
for i in range(5):
for j in range(i):
print(j)
EDIT
Given the game you're trying to replicate, you may want something like this:
for i in range(4):
for j in range(i + 1):
print(j, end=' ')
print()
# Output:
# 0
# 0 1
# 0 1 2
# 0 1 2 3
EDIT 2
Or perhaps this:
for i in range(4):
print(' ' * i, end='')
for j in range(4 - i):
print(j, end=' ')
print()
# Output:
# 0 1 2 3
# 0 1 2
# 0 1
# 0
Upvotes: 2
Reputation: 196
You compute rownum
only once, before entering the outer for
loop -- but you actually need rownum
to be different values during each iteration. That means you need to compute a new range inside the loop.
Do something like this:
for i in totalrow:
for j in range(i):
print(j)
This will loop in the pattern you are asking for.
Upvotes: 2