Built with Tutify.io

    AIStudyLabs

    Print Star Pattern

    Print Star Pattern

    Introduction

    This lesson will expand your understanding of loops by introducing nested loops to create visually appealing star patterns in Python. You'll learn how to control the layout of your output using the print function, explore the differences between for and while loops, and add user interactivity to customize the patterns you generate.

    Creating Basic Star Patterns with Nested Loops

    Star patterns provide a great way to understand nested loops. Let’s start with a simple triangle star pattern:

    # Simple star pattern
    rows = 5
    for i in range(1, rows + 1):
        for j in range(i):
            print("*", end=" ")
        print("")
    

    Explanation

    Using Print Statements for Output Formatting

    Python's print function can format output effectively:

    Experiment by adding spaces, aligning stars, and understanding the end parameter for output variations.

    Implementing User Input to Customize Patterns

    We can enhance our program by allowing user input to specify the number of rows:

    # User-customizable star pattern
    rows = int(input("Enter the number of rows: "))
    for i in range(1, rows + 1):
        for j in range(i):
            print("*", end=" ")
        print("")
    

    Explanation

    Exploring Alternative Patterns

    Try altering the loops to create different patterns. Example: an inverted triangle.

    # Inverted star pattern
    rows = 5
    for i in range(rows, 0, -1):
        for j in range(i):
            print("*", end=" ")
        print("")
    

    Explanation

    Summary / Key Takeaways

    In this lesson, you have learned:

    Master Python by Writing 50 Programs — Loops and Mathematical Programs

    Python Basics Programs

    Number-Based Programs

    Loops and Mathematical Programs

    String-Based Programs

    List-Based Programs

    Dictionary and Set Programs

    Chapter 7: File Handling and Real Programs

    Tutorial Not Found