Tuesday 26 March 2024

Python pattern challenge - Day 9

 


def print_pattern():

    num = 1

    for i in range(1, 6):

        if i % 2 != 0:

            print(f"* {num} * {num + 1} *")

            num += 2

        else:

            print(f"{num} * {num + 1} * {num + 2}")

            num += 3


print_pattern()


Explanation: 

Let's break down the print_pattern() function step by step:

Initialization:

num = 1: This variable is initialized to 1. It will be used to generate the numbers in the pattern.
Looping:

for i in range(1, 6):: This loop iterates from 1 to 5 (inclusive). It controls the number of rows in the pattern.
Conditional Printing:

if i % 2 != 0:: This condition checks if the current row number i is odd.
If the row number is odd:
print(f"* {num} * {num + 1} *"): It prints a pattern where an asterisk ('*') is followed by num, then another asterisk, then num + 1, and finally an asterisk. This is repeated for each odd row.
num += 2: num is incremented by 2 because each number is two units apart in odd rows.
If the row number is even:
print(f"{num} * {num + 1} * {num + 2}"): It prints a pattern where num is followed by an asterisk, then num + 1, then an asterisk, and finally num + 2. This is repeated for each even row.
num += 3: num is incremented by 3 because each number is three units apart in even rows.
Output:

The function print_pattern() is called, resulting in the specified pattern being printed to the console.
Overall, this function generates and prints a pattern consisting of alternating rows with different structures: odd rows have asterisks surrounding consecutive numbers, while even rows have numbers separated by asterisks.

0 Comments:

Post a Comment

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (115) C (77) C# (12) C++ (82) Course (62) Coursera (178) coursewra (1) Cybersecurity (22) data management (11) Data Science (91) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (746) Python Coding Challenge (201) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses