python для-l oop с 2 счетчиками - PullRequest
1 голос
/ 04 мая 2020

Я хотел бы создать сингл для l oop, используя 2 переменные вместо a для l oop и внешней переменной.

Есть ли способ сделать что-то, распаковывая кортежи с диапазоном ?

Вот что у меня есть:

space = height
for h in range(height):
    # code using both h & space

Вот код, который я пытаюсь улучшить:

# 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

1 Ответ

4 голосов
/ 04 мая 2020

Вы можете использовать второй range объект (от height до 0), а затем zip, чтобы выполнить итерации обоих диапазонов одновременно:

# 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
...