[Python] Python: Drawing asterisk pattern based on input number within a range

Discussão em 'Python' iniciado por Stack, Abril 9, 2025.

  1. Stack

    Stack Membro Participativo

    help me with this problem

    enter image description here

    def validate_input():
    while True:
    try:
    n = int(input("Enter a number between 4 and 8: "))
    if 4 <= n <= 8:
    return n
    else:
    print("Error: the number must be between 4 and 8.")
    except ValueError:
    print("Error: you must enter an integer.")

    def generate_pattern(n):
    rows = n * n
    columns = 11 # You can adjust this if you want a wider pattern

    # Print column headers
    print(" ", end="")
    for col in range(1, columns + 1):
    print(f"{col:<3}", end="")
    print()

    for row in range(1, rows + 1):
    print(f"{row:<5}", end="") # row number

    for col in range(1, columns + 1):
    # Calculate which block of n rows we're in
    block = (row - 1) // n
    pos = (row - 1) % n

    # The two diagonal conditions to generate the pattern
    draw = False

    # Downward diagonal ↘️
    if col == block + pos + 1:
    draw = True

    # Upward diagonal ↙️
    if col == (2 * n - 1) - (block + pos):
    draw = True

    print("* " if draw else " ", end="")

    print()

    # Run the program
    n = validate_input()
    generate_pattern(n)

    Continue reading...

Compartilhe esta Página