Patterns in Nested For loop || match Case Statement 17th class

Python Pattern Printing Using Nested For Loops

1. Right Triangle Pattern

python

n = 5
for i in range(1, n+1):
    for j in range(1, i+1):
        print("*", end=" ")
    print()
"""
Output:
* 
* * 
* * * 
* * * * 
* * * * * 
"""

2. Inverted Right Triangle

python

n = 5
for i in range(n, 0, -1):
    for j in range(1, i+1):
        print("*", end=" ")
    print()
"""
Output:
* * * * * 
* * * * 
* * * 
* * 
* 
"""

3. Pyramid Pattern

python

n = 5
for i in range(1, n+1):
    # Print spaces
    for j in range(n - i):
        print(" ", end=" ")
    # Print stars
    for k in range(2 * i - 1):
        print("*", end=" ")
    print()
"""
Output:
        * 
      * * * 
    * * * * * 
  * * * * * * * 
* * * * * * * * * 
"""

4. Number Pattern

python

n = 5
for i in range(1, n+1):
    for j in range(1, i+1):
        print(j, end=" ")
    print()
"""
Output:
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
"""

5. Alphabet Pattern

python

n = 5
for i in range(65, 65+n):
    for j in range(65, i+1):
        print(chr(j), end=" ")
    print()
"""
Output:
A 
A B 
A B C 
A B C D 
A B C D E 
"""

6. Diamond Pattern

python

n = 5
# Upper half
for i in range(1, n+1):
print(" "*(n-i) + "* " * i)
# Lower half
for i in range(n-1, 0, -1):
print(" "*(n-i) + "* " * i)
"""
Output:
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
"""

More Python Pattern Examples Using Nested For Loops

1. Hollow Square Pattern

python

n = 5
for i in range(n):
    for j in range(n):
        if i == 0 or i == n-1 or j == 0 or j == n-1:
            print("*", end=" ")
        else:
            print(" ", end=" ")
    print()
"""
Output:
* * * * * 
*       * 
*       * 
*       * 
* * * * * 
"""

2. Right Arrow Pattern

python

n = 5
# Upper half
for i in range(n):
    print("  " * i + "* " * (n - i))
# Lower half
for i in range(2, n+1):
    print("  " * (n - i) + "* " * i)
"""
Output:
* * * * * 
  * * * * 
    * * * 
      * * 
        * 
      * * 
    * * * 
  * * * * 
* * * * * 
"""

3. Pascal’s Triangle

python

n = 5
for i in range(1, n+1):
    num = 1
    for j in range(1, i+1):
        print(num, end=" ")
        num = num * (i - j) // j
    print()
"""
Output:
1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
"""

4. Floyd’s Triangle

python

n = 5
num = 1
for i in range(1, n+1):
    for j in range(1, i+1):
        print(num, end=" ")
        num += 1
    print()
"""
Output:
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 
"""

5. Binary Number Pattern

python

n = 5
for i in range(1, n+1):
    for j in range(1, i+1):
        print((i + j) % 2, end=" ")
    print()
"""
Output:
0 
1 0 
0 1 0 
1 0 1 0 
0 1 0 1 0 
"""

6. Cross Pattern

python

n = 5
for i in range(n):
    for j in range(n):
        if i == j or i + j == n - 1:
            print("*", end=" ")
        else:
            print(" ", end=" ")
    print()
"""
Output:
*       * 
  *   *   
    *     
  *   *   
*       * 
"""

7. Heart Pattern

python

n = 6
for i in range(n//2, n, 2):
    for j in range(1, n-i, 2):
        print(" ", end=" ")
    for j in range(1, i+1):
        print("*", end=" ")
    for j in range(1, n-i+1):
        print(" ", end=" ")
    for j in range(1, i+1):
        print("*", end=" ")
    print()

for i in range(n, 0, -1):
    print("  " * (n - i) + "* " * (2 * i - 1))
"""
Output:
  * * *     * * *   
* * * * * * * * * * 
  * * * * * * * * * 
    * * * * * * * 
      * * * * * 
        * * * 
          * 
"""

8. Hollow Diamond

python

n = 5
# Upper half
for i in range(1, n+1):
for j in range(n - i):
print(" ", end=" ")
for k in range(2 * i - 1):
if k == 0 or k == 2 * i - 2:
print("*", end=" ")
else:
print(" ", end=" ")
print()
# Lower half
for i in range(n-1, 0, -1):
for j in range(n - i):
print(" ", end=" ")
for k in range(2 * i - 1):
if k == 0 or k == 2 * i - 2:
print("*", end=" ")
else:
print(" ", end=" ")
print()
"""
Output:
*
* *
* *
* *
* *
* *
* *
* *
*
"""

Python match Case Statement with Number-to-Month Example

The match statement (introduced in Python 3.10) is a powerful feature that provides pattern matching capabilities similar to switch-case statements in other languages, but more flexible.

Basic Syntax of match Case

python

match subject:
    case pattern1:
        # action1
    case pattern2:
        # action2
    case _:
        # default action

Number to Month Name Program

Here’s a complete example that converts a month number (1-12) to its corresponding month name using match case:

python

def number_to_month(month_num):
    match month_num:
        case 1:
            return "January"
        case 2:
            return "February"
        case 3:
            return "March"
        case 4:
            return "April"
        case 5:
            return "May"
        case 6:
            return "June"
        case 7:
            return "July"
        case 8:
            return "August"
        case 9:
            return "September"
        case 10:
            return "October"
        case 11:
            return "November"
        case 12:
            return "December"
        case _:  # Default case (like 'else')
            return "Invalid month number"

# Test the function
print(number_to_month(3))   # Output: March
print(number_to_month(8))   # Output: August
print(number_to_month(13))  # Output: Invalid month number

Key Features of match Case:

  1. Direct Value Matching: Compares the subject directly with values (like in this month example)
  2. Wildcard Pattern_ acts as a catch-all/default case
  3. No Fall-through: Unlike C-style switch statements, Python doesn’t fall through to the next case
  4. No Break Needed: Each case automatically breaks after execution

Advanced Example with Patterns

You can also use more complex patterns:

python

def describe_number(num):
    match num:
        case 0:
            return "Zero"
        case 1 | 2 | 3:  # Multiple values in one case
            return "Small number"
        case n if 4 <= n <= 9:  # With guard condition
            return "Medium number"
        case n if n >= 10:
            return "Large number"
        case _:
            return "Negative number"

print(describe_number(2))   # Output: Small number
print(describe_number(5))   # Output: Medium number
print(describe_number(15))  # Output: Large number

When to Use match Case:

  • When you have multiple conditions to check against a single value
  • When the conditions are based on value equality (like our month example)
  • When you want cleaner code than multiple if-elif-else statements

Note: The match statement requires Python 3.10 or later. For earlier versions, you would need to use if-elif-else chains or dictionary lookups for similar functionality.

Similar Posts

  • Raw Strings in Python

    Raw Strings in Python’s re Module Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences. path = ‘C:\Users\Documents’ pattern = r’C:\Users\Documents’ .4.1.1. Escape sequences Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according…

  • Examples of Python Exceptions

    Comprehensive Examples of Python Exceptions Here are examples of common Python exceptions with simple programs: 1. SyntaxError 2. IndentationError 3. NameError 4. TypeError 5. ValueError 6. IndexError 7. KeyError 8. ZeroDivisionError 9. FileNotFoundError 10. PermissionError 11. ImportError 12. AttributeError 13. RuntimeError 14. RecursionError 15. KeyboardInterrupt 16. MemoryError 17. OverflowError 18. StopIteration 19. AssertionError 20. UnboundLocalError…

  • String Alignment and Padding in Python

    String Alignment and Padding in Python In Python, you can align and pad strings to make them visually consistent in output. The main methods used for this are: 1. str.ljust(width, fillchar) Left-aligns the string and fills remaining space with a specified character (default: space). Syntax: python string.ljust(width, fillchar=’ ‘) Example: python text = “Python” print(text.ljust(10)) #…

  • file properties and methods

    1. file.closed – Is the file door shut? Think of a file like a door. file.closed tells you if the door is open or closed. python # Open the file (open the door) f = open(“test.txt”, “w”) f.write(“Hello!”) print(f.closed) # Output: False (door is open) # Close the file (close the door) f.close() print(f.closed) # Output: True (door is…

  • Special Character Classes Explained with Examples

    Special Character Classes Explained with Examples 1. [\\\^\-\]] – Escaped special characters in brackets Description: Matches literal backslash, caret, hyphen, or closing bracket characters inside character classes Example 1: Matching literal special characters python import re text = “Special chars: \\ ^ – ] [” result = re.findall(r'[\\\^\-\]]’, text) print(result) # [‘\\’, ‘^’, ‘-‘, ‘]’] # Matches…

  • Alternation and Grouping

    Complete List of Alternation and Grouping in Python Regular Expressions Grouping Constructs Capturing Groups Pattern Description Example (…) Capturing group (abc) (?P<name>…) Named capturing group (?P<word>\w+) \1, \2, etc. Backreferences to groups (a)\1 matches “aa” (?P=name) Named backreference (?P<word>\w+) (?P=word) Non-Capturing Groups Pattern Description Example (?:…) Non-capturing group (?:abc)+ (?i:…) Case-insensitive group (?i:hello) (?s:…) DOTALL group (. matches…

Leave a Reply

Your email address will not be published. Required fields are marked *