pattern-programs-in-python

“`html

Python pattern programs serve as an excellent method to enhance your understanding of conditionals, loops, and logical structures. By creating various shapes like triangles, pyramids, diamonds, and others, you can sharpen your problem-solving capabilities and prepare for technical interviews. This article will discuss a range of Python patterns, from Pascal’s triangle to a basic star pattern.

Table of Contents:

What are Pattern Programs?

Pattern programs are designed to generate various shapes or uniquely crafted forms with characters like asterisks, digits, or letters. These programs utilize nested loops, either using for or while constructs.

Pattern programs assist in grasping nested loops, conditional statements, string formatting, and functions like print(), range(), chr(), and ord().

Pattern Programs in Python

Here are several pattern programs in Python.

1. Right-Angled Triangle Pattern in Python

The right-angled triangle pattern is among the simplest and most commonly employed patterns in programming. It begins with one asterisk (*) in the first row, and each subsequent row adds one more asterisk (*), creating a right-angled triangle.

Logic:

  • The number of rows dictates the height of the triangle.
  • Each row must have a specific count of stars.
  • The star count for a row corresponds to its row number. For instance, Row 1 -> 1 star, Row 2 -> 2 stars, and so forth.
  • Utilize nested for loops, where the outer loop governs the rows, and the inner loops manage the columns.

Code:

Python

Code Copied!

var isMobile = window.innerWidth “);

editor82530.setValue(decodedContent); // Set the default text editor82530.clearSelection();

editor82530.setOptions({ maxLines: Infinity });

function decodeHTML82530(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard82530() { const code = editor82530.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor82530 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor82530 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode82530() { var code = editor82530.getSession().getValue();

jQuery(“#runBtn82530 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “python”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output82530”).html(“

"+data+"");
            jQuery(".maineditor82530 .code-editor-output").show();
            jQuery("#runBtn82530 i.run-code").hide();
        }
    });
}

function closeoutput82530() {	
    var code = editor82530.getSession().getValue();
    jQuery(".maineditor82530 .code-editor-output").hide();
}

// Attach event listeners to the buttons
document.getElementById("copyBtn82530").addEventListener("click", copyCodeToClipboard82530);
document.getElementById("runBtn82530").addEventListener("click", runCode82530);
document.getElementById("closeoutputBtn82530").addEventListener("click", closeoutput82530);


Output:

1. Right-Angled Triangle Pattern

The above program utilizes a nested loop to produce a right-angled triangle. The outer loop iterates from 1 to the number of rows, and for each outer loop iteration, the inner loop executes i times to print * horizontally on a new line for each row.

2. Left-Aligned Triangle Pattern in Python

A left-aligned triangle pattern is a configuration where the triangle shifts to the left by inserting spaces before the stars (*) on each line. This results in a triangle that appears left-slanted.

Logic:

  • Each row should consist of a specified number of stars (*).
  • The count of stars in a row is equal to the row number.
  • Before displaying the stars, introduce spaces to reposition the stars to the right.
  • The number of spaces in a row equals (total rows – current row number).
“““html – current row index).

Snippet:

Python
Code Duplicated!

Result:

2. Left Aligned Triangle Pattern

The program above displays a left-aligned triangle by preceding spaces (rows – i) before adding stars on each line.

3. Pyramid Pattern in Python

A pyramid pattern resembles a balanced triangle with a centered triangular shape on each line. The breadth grows as it progresses downward, creating a flawless pyramid shape.

Concept:

  • The quantity of stars printed in each row will increase according to the current row index.
  • Before displaying stars, insert spaces for a centered pyramid.
  • The amount of preceding spaces corresponds to (total rows – current row index).

Snippet:

Python
Code Duplicated!
``````html "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1]; jQuery(".output74899").html("
"+data+"");
                                    jQuery(".maineditor74899 .code-editor-output").show();
                                    jQuery("#runBtn74899 i.run-code").hide();
                                    
                                }
                            })
                    

                        }
                        
                        
        function closeoutput74899() {    
        var code = editor74899.getSession().getValue();
        jQuery(".maineditor74899 .code-editor-output").hide();
        }

    // Set up event listeners for the buttons
    document.getElementById("copyBtn74899").addEventListener("click", copyCodeToClipboard74899);
    document.getElementById("runBtn74899").addEventListener("click", runCode74899);
    document.getElementById("closeoutputBtn74899").addEventListener("click", closeoutput74899);
 
    



Output:

3. Pyramid Pattern

The above program displays a pyramid pattern. The first inner loop generates spaces to align the stars centrally, while the second inner loop outputs (2*i-1) stars for each row, establishing the width. Subsequently, the print() function proceeds to the next line.

4. Inverted Right-Angled Triangle in Python

An inverted right-angled triangle is the mirror image of a right-angled triangle. It begins with the highest number of stars in its first row and decreases by 1 in each subsequent row.

Logic:

  • The outer loop iterates in reverse, counting down from the total number of rows to 1.
  • For each row, the number of stars printed corresponds to the row number.
  • Each row contains one fewer star than the prior row.

Code:

Python
Code Copied!

Output:

4. Inverted Right-Angled Triangle

The preceding code produces an inverted right triangle, where the count of stars in each row diminishes from “rows” to 1, utilizing a reverse outer loop.

Master Python. Achieve Certification. Advance Your Career
Enroll now!
quiz-icon

5. Inverted Pyramid Pattern in Python

An inverted ``````html

An inverted pyramid pattern can be understood as a pyramid turned upside-down. The row containing the most stars is row 1, and each following row reduces the number of stars while increasing the spaces in front of them.

Concept:

  • The outer loop counts down from the total number of rows to 1.
  • The first inner loop adds leading spaces, moving the stars to the right.
  • The second inner loop outputs an odd quantity of stars, reducing by each row (2*i-1).

Code:

Python
Code Copied!

function closeoutput11640() { var code = editor11640.getSession().getValue(); jQuery(".maineditor11640 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn11640").addEventListener("click", copyCodeToClipboard11640); document.getElementById("runBtn11640").addEventListener("click", runCode11640); document.getElementById("closeoutputBtn11640").addEventListener("click", closeoutput11640);

Output:

5. Inverted Pyramid Pattern

The program above generates a pattern of an inverted pyramid. This is accomplished by employing a reverse loop to reduce the stars (2 * i – 1) and increase spaces (rows – i) in each row, while ensuring that it remains centered.

6. Diamond Pattern in Python

A diamond pattern integrates both a pyramid and an inverted pyramid. First, create the pyramid (upper section), followed by the inverted pyramid (lower section) to form a diamond shape.

Concept:

1. The upper part (standard pyramid):

  • The stars grow from 1 to the total rows.
  • Spaces are added before the stars to align the pattern centrally.

2. The lower section (inverted pyramid):

  • The stars diminish from (rows – 1) to 1.
  • It is also aligned centrally with spaces preceding the stars.

Code:

Python

Code Copied!

var isMobile = window.innerWidth "");

editor15685.setValue(decodedContent); // Set the default text editor15685.clearSelection(); editor15685.setOptions({ maxLines: Infinity }); ``````html Infinity });

function decodeHTML15685(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to duplicate code to clipboard function copyCodeToClipboard15685() { const code = editor15685.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code duplicated to clipboard!");

jQuery(".maineditor15685 .copymessage").show(); setTimeout(function() { jQuery(".maineditor15685 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Issue duplicating code: ", err); }); }

function executeCode15685() {

var code = editor15685.getSession().getValue();

jQuery("#runBtn15685 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output15685").html("

"+data+"");
									jQuery(".maineditor15685 .code-editor-output").show();
									jQuery("#runBtn15685 i.run-code").hide();
									
								}
							})
					

						}
						
						
		function hideOutput15685() {	
		var code = editor15685.getSession().getValue();
		jQuery(".maineditor15685 .code-editor-output").hide();
		}

    // Attach event listeners to the buttons
    document.getElementById("copyBtn15685").addEventListener("click", copyCodeToClipboard15685);
    document.getElementById("runBtn15685").addEventListener("click", executeCode15685);
    document.getElementById("closeoutputBtn15685").addEventListener("click", hideOutput15685);
 
    



Outcome:

6. Diamond Pattern

The program above generates a diamond shape by forming a standard pyramid followed by an inverted pyramid, using spaces for centering stars in both sections.

7. Hollow Square in Python

A hollow square pattern consists of a square made of stars (*) where only the edges are filled, leaving the interior empty.

Logic:

  • Utilize two loops, with an outer one for rows and an inner for columns.
  • Display a star (*) solely if on the first or last row or column.
  • Present a space for all interior positions.

Code:

Python
Code Duplicated!

Outcome:

7. Hollow Square

The program above leverages conditional evaluations within nested loops to position stars on the bordering locations and spaces inside to create a hollow square.

8. Repeating Number Rows Pattern in Python

The repeating number rows pattern features a uniform number, which corresponds to the row. ``````html

number, reiterated in every row.

Reasoning:

  • Every row number is displayed i times.
  • Using nested loops, where the outer loop governs the row number, while the inner loop replicates the row number.

Script:

Python
Code Duplicated!

Result:

8. Repeating Number Rows Pattern

The program depicted above generates a pattern where each row displays its corresponding number the exact number of times as its row designation.

9. Floyd’s Triangle in Python

Floyd’s Triangle showcases a numerical arrangement created by arranging numbers in a manner that forms a right-angled triangle. The i-th row contains an additional number compared to the previous row (i-1).

Reasoning:

  • The initial number is 1, increasing num by 1 each time.
  • Each row i outputs i number of values.

Script:

Python

Code Duplicated!

var isMobile = window.innerWidth ");

editor72952.setValue(decodedContent); // Establish the preset text editor72952.clearSelection();

editor72952.setOptions({ maxLines: Infinity });

function decodeHTML72952(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to duplicate code to clipboard function copyCodeToClipboard72952() { const code = editor72952.getValue(); // Obtain code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor72952 .copymessage").show(); setTimeout(function() { jQuery(".maineditor72952 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error duplicating code: ", err); }); } ``````html copying code: ", err); }); }

function runCode72952() {

var code = editor72952.getSession().getValue();

jQuery("#runBtn72952 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output72952").html("

"+data+"");
									jQuery(".maineditor72952 .code-editor-output").show();
									jQuery("#runBtn72952 i.run-code").hide();
									
								}
							})
					

						}
						
						
		function closeoutput72952() {	
		var code = editor72952.getSession().getValue();
		jQuery(".maineditor72952 .code-editor-output").hide();
		}

    // Attach event listeners to the buttons
    document.getElementById("copyBtn72952").addEventListener("click", copyCodeToClipboard72952);
    document.getElementById("runBtn72952").addEventListener("click", runCode72952);
    document.getElementById("closeoutputBtn72952").addEventListener("click", closeoutput72952);
 
    



Output:

9. Floyd’s Triangle

The earlier program displays Floyd’s Triangle utilizing two nested loops that employ a counter variable while incrementing that variable progressively for each row.

10. Pascal’s Triangle in Python

A triangular arrangement of binomial coefficients is referred to as Pascal’s Triangle. Each number in the prior row is the aggregate of the two numbers directly above it.

Logic:

  • Implement the formula for binomial coefficients: C(n, k) = n!/k!(n-k)!
  • Each row has i + 1 elements.
  • The triangle is center-aligned through spaces.

Code:

Python
Code Copied!

Output:

10. Pascal’s Triangle

This code generates Pascal’s Triangle by determining binomial coefficients through factorials and structuring the output into a centered triangle.

11. Mirror Number Pattern in Python

The Mirror Number Pattern displays numbers in an ascending order for each row, but right-aligned using spaces, resembling a right-angled triangle reflected over a vertical axis.

Logic:

  • Leading spaces diminish with each row to shift numbers to the right.
  • Numbers begin from 1 and increase to the current row index.

Code:

Python
``````html Duplicate Code
Code Successfully Copied!

Result:

11. Mirror Number Pattern

This code generates a right-aligned number triangle by merging decreasing spaces and ascending numbers per row.

12.  Number Pyramid Pattern in Python

The number pyramid pattern includes a pyramid-shaped layout of numbers with spaces between displaying an ascending sequence of numbers.

Logic: 

  • Each row possesses an increasing count of elements, (2 * i – 1).
  • Additionally, (rows-i) will represent the leading spaces.
  • Every row begins from 1 and increments by 1.

Code:

Python
Code Successfully Copied!

Result:

12. Number Pyramid Pattern

This code generates a center-aligned number pyramid, displaying each row with an increasing total of numbers, specifically (2*i-1) numbers on the ith row. Leading spaces are added before the numbers in each row to maintain centering and symmetry of the pyramid.

13. Inverted Number Pyramid Pattern in Python

This is an inverted number pyramid pattern. It starts with the widest row and proceeds to the narrowest. The rows will exhibit symmetry and remain centered.

Concept:

  • Every row will output (2*i-1) numbers commencing from 1, where i represents the row number.
  • The leading space will increase for each row to ensure the numbers are centered.
  • The size of the pattern diminishes as the row number reduces.

Code:

Python
Code Copied!

Result:

13. Inverted Number Pyramid Pattern

The code generates an inverted number pyramid commencing with the maximum count of numbers in the first row and reducing the count by one for subsequent rows. While the number count diminishes, leading spaces prior to the numbers in each row increase. This keeps the pattern centered and maintains the pyramid shape as the width shrinks on the way down.

14. Number Diamond Pattern in Python

The number diamond pattern is a symmetrical design shaped like a diamond that is achieved through increasing and decreasing numerical sequences.

Concept:

  • The upper section forms a number pyramid with ascending rows numbered from 1 to the total rows.
  • The lower section is an inverted number pyramid, descending to 1.
  • Each row will print numbers from 1 to (2*i-1) and also contains leading spaces for centering.

Code:

Python

Code Copied!

var isMobile = window.innerWidth ");

editor985.setValue(decodedContent); // Initialize the default text editor985.clearSelection();

editor985.setOptions({ maxLines: Infinity });

function decodeHTML985(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function for copying code to clipboard function copyCodeToClipboard985() { const code = editor985.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!"); jQuery(".maineditor985 .copymessage").show(); setTimeout(function() { jQuery(".maineditor985 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode985() { var code = editor985.getSession().getValue();

jQuery("#runBtn985 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action: "compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output985").html("

" + data + "

"); jQuery(".maineditor985 .code-editor-output").show(); jQuery("#runBtn985 i.run-code").hide(); } }); }

function closeoutput985() { var code = editor985.getSession().getValue(); jQuery(".maineditor985 .code-editor-output").hide(); }

// Add event listeners to the buttons document.getElementById("copyBtn985").addEventListener("click", copyCodeToClipboard985); document.getElementById("runBtn985").addEventListener("click", runCode985); document.getElementById("closeoutputBtn985").addEventListener("click", closeoutput985);

Result:

14. Number Diamond Pattern

This program generates a diamond structure by centering the sequential numbers in each row, creating a pyramid shape, followed by an inverted pyramid. In this snippet, spaces are utilized to center the sequential numbers and realize the diamond design.

15. Butterfly Pattern in Python

The butterfly pattern is formed by two symmetrical right triangles, one situated in the upper portion and the other in the lower segment. In the center, gaps exist between the two triangles to achieve a butterfly-like appearance.

Concept:

  • The upper segment will fan out the stars from left to right while reducing the central gap for a balanced appearance.
  • The lower part will mirror the movements of the upper section in reverse order.
  • The center spaces are calculated as 2 * (rows – i) for balance.

Snippet:

Python

Code Copied!

var isMobile = window.innerWidth ");

editor97522.setValue(decodedContent); // Initialize the default text editor97522.clearSelection();

editor97522.setOptions({ maxLines: Infinity });

function decodeHTML97522(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function for copying code to clipboard function copyCodeToClipboard97522() { const code = editor97522.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!"); jQuery(".maineditor97522 .copymessage").show(); setTimeout(function() { jQuery(".maineditor97522 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode97522() { var code = editor97522.getSession().getValue();

jQuery("#runBtn97522 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action: "compilerajax" }, success: function(response) { // Handling response logic here... } }); }
``````javascript
function(response) {
var myArray = response.split(""~"");
var data = myArray[1];

jQuery("".output97522"").html("<pre>" + data + "</pre>");
jQuery("".maineditor97522 .code-editor-output"").show();
jQuery(""#runBtn97522 i.run-code"").hide();
}
})

}

function closeoutput97522() {
var code = editor97522.getSession().getValue();
jQuery("".maineditor97522 .code-editor-output"").hide();
}

// Assign event listeners to the buttons
document.getElementById(""copyBtn97522"").addEventListener(""click"", copyCodeToClipboard97522);
document.getElementById(""runBtn97522"").addEventListener(""click"", runCode97522);
document.getElementById(""closeoutputBtn97522"").addEventListener(""click"", closeoutput97522);

Result:

15. Butterfly Pattern

This code generates a butterfly pattern using stars (*) on both sides of each row, concurrently modifying the space in the center. The gaps between the stars decrease in the upper half and increase in the lower portion of the design, resulting in a symmetrical butterfly shape.

Sign up for Free and obtain your Python certification from anywhere, anytime!
Register now!
quiz-icon

16. Hollow Butterfly Design in Python

A Hollow Butterfly Design refers to a butterfly pattern that features only the outer edges of the wings (stars), leaving the inner part empty with spaces.

Logic:

  • This motif can be divided into two sections: the upper and lower halves.
  • Each "wing" or side of the butterfly displays stars for the wing outlines (j == 1 or j == i), while the remaining elements remain vacant with spaces.
  • A central gap exists between the wings, which expands or contracts as you progress through the rows to achieve the full butterfly configuration.

Code:

Python

Code Copied!

var isMobile = window.innerWidth ");

editor1579.setValue(decodedContent); // Set initial text editor1579.clearSelection();

editor1579.setOptions({ maxLines: Infinity });

function decodeHTML1579(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard1579() { const code = editor1579.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { jQuery("".maineditor1579 .copymessage"").show(); setTimeout(function() { jQuery("".maineditor1579 .copymessage"").hide(); }, 2000); }).catch(err => { console.error(""Error copying code: ", err); }); }

function runCode1579() {

var code = editor1579.getSession().getValue();

jQuery(""#runBtn1579 i.run-code"").show(); jQuery("".output-tab"").click();

jQuery.ajax({ url: ""https://intellipaat.com/blog/wp-admin/admin-ajax.php"", type: ""post"",

data: { language: ""python"", code: code, cmd_line_args: """, variablenames: """, action: ""compilerajax"" }, success: function(response) { var myArray = response.split(""~""); var data = myArray[1];

jQuery("".output1579"").html("<pre>" + data + "</pre>"); jQuery("".maineditor1579 .code-editor-output"").show(); jQuery(""#runBtn1579 i.run-code"").hide(); } }) }

function closeoutput1579() { var code = editor1579.getSession().getValue(); jQuery("".maineditor1579 .code-editor-output"").hide(); }

// Assign event listeners to the buttons document.getElementById(""copyBtn1579"").addEventListener(""click"", copyCodeToClipboard1579); document.getElementById(""runBtn1579"").addEventListener(""click"", runCode1579); document.getElementById(""closeoutputBtn1579"").addEventListener(""click"", closeoutput1579);

Result:

``````html
16. Hollow Butterfly Pattern

This script outputs a symmetrical empty butterfly formation by displaying two triangular wings adjacent to one another. It places stars (*) solely along the outer edges of each wing, encompassing the left and right borders, while the inner regions are filled with blank spaces to maintain the hollow structure.

17. Zig-Zag Number Pattern in Python

The zigzag number arrangement alternates between rows of digits that are organized from left to right and then from right to left.

Logic:

  • Identify which row the digit will occupy by cycling through the columns from left to right and applying the modulus operator.
  • Arrange the numbers in a zigzag formation that cycles from the top to the middle and then to the bottom.
  • A two-dimensional array storing the pattern will be generated and displayed row by row.

Code:

Python

Code Copied!

var isMobile = window.innerWidth ");

editor84484.setValue(decodedContent); // Set the default text editor84484.clearSelection();

editor84484.setOptions({ maxLines: Infinity });

function decodeHTML84484(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard84484() { const code = editor84484.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor84484 .copymessage").show(); setTimeout(function() { jQuery(".maineditor84484 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode84484() { var code = editor84484.getSession().getValue();

jQuery("#runBtn84484 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action: "compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1]; jQuery(".output84484").html("

"+data+"

"); jQuery(".maineditor84484 .code-editor-output").show(); jQuery("#runBtn84484 i.run-code").hide(); } }); }

function closeoutput84484() { var code = editor84484.getSession().getValue(); jQuery(".maineditor84484 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn84484").addEventListener("click", copyCodeToClipboard84484); document.getElementById("runBtn84484").addEventListener("click", runCode84484); document.getElementById("closeoutputBtn84484").addEventListener("click", closeoutput84484);

Output:

17. Zig-Zag Number Pattern

This script employs the index value of each column to establish the row position, producing a zigzag pattern of digits, ensuring numbers align diagonally to create a zigzag effect.

18. Alternating Binary Pattern in Python

The alternating binary pattern generates a grid of alternating 1s and 0s, commencing with 1, while the leading digit shifts with every subsequent row.

Logic:

  • To alternate between 1s and 0s, utilize (i + j) % 2.
  • If the indices are even, row + column = 0, or odd row + column = 1.
  • This method automatically manages the transition of the starting digit for each row.

Code:

Python

Code Copied!

var isMobile = window.innerWidth "");

editor73399.setValue(decodedContent); // Assign the initial text editor73399.clearSelection();

editor73399.setOptions({ maxLines: Infinity });

function decodeHTML73399(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard73399() { const code = editor73399.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor73399 .copymessage").show(); setTimeout(function() { jQuery(".maineditor73399 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode73399() {

var code = editor73399.getSession().getValue();

jQuery("#runBtn73399 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action: "compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output73399").html("

"+data+"");
        jQuery(".maineditor73399 .code-editor-output").show();
        jQuery("#runBtn73399 i.run-code").hide();
    }
});
}

function closeoutput73399() { var code = editor73399.getSession().getValue(); jQuery(".maineditor73399 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn73399").addEventListener("click", copyCodeToClipboard73399); document.getElementById("runBtn73399").addEventListener("click", runCode73399); document.getElementById("closeoutputBtn73399").addEventListener("click", closeoutput73399);

Output:

18. Alternating Binary Pattern

This code produces a checkerboard-style binary arrangement by alternating between using 1 and 0 for each square in the grid. It determines if each square in the grid will display a 1 or a 0 by summing the row index and the column index. If the resulting value is even, it presents a 1; conversely, if it's odd, it presents a 0.

19. Cross Pattern in Python

The cross pattern creates a design of stars (*) or another symbol in a cross configuration using both diagonals of a square grid.

Logic: 

  • The first diagonal is defined where i == j.
  • The second diagonal is defined where i + j == size &ndash; 1.
  • These two conditions account for each arm of the &ldquo;X&rdquo;.

Code:

Python

Code Copied!

var isMobile = window.innerWidth "");

editor55638.setValue(decodedContent); // Initialize with default text editor55638.clearSelection();

editor55638.setOptions({ maxLines: Infinity });

function decodeHTML55638(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard55638() { const code = editor55638.getValue(); // Extract code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor55638 .copymessage").show(); setTimeout(function() { jQuery(".maineditor55638 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode55638() {

var code = editor55638.getSession().getValue();

jQuery("#runBtn55638 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action: "compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output55638").html("

"+data+"");
        jQuery(".maineditor55638 .code-editor-output").show();
        jQuery("#runBtn55638 i.run-code").hide();
    }
});
}

function closeoutput55638() { var code = editor55638.getSession().getValue(); jQuery(".maineditor55638 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn55638").addEventListener("click", copyCodeToClipboard55638); document.getElementById("runBtn55638").addEventListener("click", runCode55638); document.getElementById("closeoutputBtn55638").addEventListener("click", closeoutput55638); ``````html runCode55638); document.getElementById("closeoutputBtn55638").addEventListener("click", closeoutput55638);

Result:

19. Cross Pattern in Python

This script presents a cross resembling an X by placing stars (*) in locations where the row and column indices align (on the principal diagonal) and at spots where the sum of the row index and column index equals n + 1 (on the counter-diagonal). All other spots are occupied by spaces.

20. Plus Pattern in Python

The plus pattern represents a symmetrical &ldquo;+&rdquo; figure created with stars (*); it constructs stars along the central row and column of a square matrix.

Concept:

  • The central row (i == mid row) forms the horizontal line.
  • The central column (j == mid col) forms the vertical line.
  • Odd-sized dimensions offer the most balanced appearance.

Script:

Python

Script Copied!

var isMobile = window.innerWidth ");

editor83550.setValue(decodedContent); // Set the default text editor83550.clearSelection();

editor83550.setOptions({ maxLines: Infinity });

function decodeHTML83550(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy script to clipboard function copyCodeToClipboard83550() { const code = editor83550.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor83550 .copymessage").show(); setTimeout(function() { jQuery(".maineditor83550 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying script: ", err); }); }

function runCode83550() {

var code = editor83550.getSession().getValue(); jQuery("#runBtn83550 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output83550").html("

"+data+"");
        jQuery(".maineditor83550 .code-editor-output").show();
        jQuery("#runBtn83550 i.run-code").hide();
    }
})

}

function closeoutput83550() { var code = editor83550.getSession().getValue(); jQuery(".maineditor83550 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn83550").addEventListener("click", copyCodeToClipboard83550); document.getElementById("runBtn83550").addEventListener("click", runCode83550); document.getElementById("closeoutputBtn83550").addEventListener("click", closeoutput83550);

Result:

20. Plus Pattern

This script produces a plus (+) shape by positioning stars (*) along the central row and column of a square array. The script calculates the index corresponding to the center of the array based on its dimensions, printing a star only when either the row or column is aligned with the center. The other parts will consist of spaces, forming a balanced plus (+) shape.

Conclusion

Pattern scripts serve as fundamental tools to grasp essential programming concepts such as nested loops, conditional logic, and output formatting. By tackling both minor and substantial challenges, alongside creating forms like triangles, pyramids, diamonds, butterflies, and zig-zags, programmers enhance their logical thinking and coding skills. These patterns represent a fantastic opportunity for practice, especially for beginners, laying a solid groundwork for more complex programming challenges. Comprehending these programming blueprints thus enhances coding fluency, ultimately fortifying the understanding of loop dynamics and conditionals for organized output.

Pattern Scripts in Python &ndash; FAQs

Q1. How do nested loops aid in printing patterns?

Nested loops enable the printing of rows and columns; the outer loop iterates over the rows while the inner loop processes the columns or specific characters for each row.

Q2. What is the method for generating a right-angled triangle pattern?

The count of stars in a row corresponds to the row number, employing nested for loops where the outer loop governs rows and the inner loop handles columns.

Q3. How do you construct a pyramid pattern using Python's loops?
``````html

Utilizing spaces and stars allows for the printing of fewer spaces, decreasing from a specific amount (e.g., 4 spaces) and incrementally increasing stars (e.g., 1 star) in each line until the configuration is balanced.

Q4. What is the principle behind forming a standard pyramid versus an inverted pyramid pattern?

A standard pyramid begins with a smaller number of stars at the peak and gradually increases, while an inverted pyramid starts with the maximum number of stars at the summit and subsequently reduces.

Q5. What are pattern scripts in Python?

Pattern scripts are programs that generate a shape or configuration of any sort (using stars, numbers, or letters) according to the defined logic of loops.

The article Pattern Programs in Python first appeared on Intellipaat Blog.

```


Leave a Reply

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

Share This