Reputation: 25
I'd like to create a single for loop using 2 variables, instead of a for loop and an external variable.
Is there a way to do something unpacking tuples with range?
Here is what I have:
space = height
for h in range(height):
# code using both h & space
Here is the code I'm trying to improve:
# Get positive integer between 1 - 8
while True:
height = int(input("Height: "))
if height > 0 and height < 9:
break
space = height # Control space count
# Build the pyramid
for h in range(height):
print(" " * (space - 1),"#" * (h + 1), end="")
print(" ", end="")
print( "#" * (h + 1), " " * (space - 1), end="")
space -= 1
print() # Get prompt on \n
Upvotes: 1
Views: 659
Reputation: 81594
You can use a second range
object (from height
to 0
) and then zip
to iterate both ranges at once:
# Get positive integer between 1 - 8
while True:
height = int(input("Height: "))
if height > 0 and height < 9:
break
# Build the pyramid
for h, space in zip(range(height), range(height, 0, -1)):
print(" " * (space - 1),"#" * (h + 1), end="")
print(" ", end="")
print( "#" * (h + 1), " " * (space - 1), end="")
print() # Get prompt on \n
Upvotes: 4