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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.