How to Print Diamond Pattern in Python using range function?
In this python program, we will explain a step-by-step rule to print Diamond shape utilizing the Python range() function. It also involves a working example for help.
Range() function to Print Diamond Pattern
We have shown various procedures to print diamond patterns in this post. Kindly peruse and assess them individually.
Diamond pattern program requirement
The goal of this activity is to deliver a diamond pattern like the one provided underneath. The pattern is utilizing the star image and prints across 9 lines.
You need to foster a program that uses a number and prints, utilizing stars, a complete diamond of the given length. let see Example, if the line size is 9, the code have to print:
* *** ***** ******* ********* *********** ************* *************** ***************** *************** ************* *********** ********* ******* ***** *** *
Additionally, you should utilize the Python range strategy for navigating through the loop.
Example – 1
In this technique, we will utilize the Python string field to repeat itself by a number specified along with the multiplication given symbol.
T_lines=9
for iter in range (T_lines-1):
print ((T_lines-iter) * ' ' + (2*iter+1) * '*')
for iter in range (T_lines-1, -1, -1):
print ((T_lines-iter) *' ' + (2* iter+1) * '*')
The above code delivers a similar diamond shape, as displayed in the past for example.
Output:
Example -2
Presently, we’ll utilize the code that prints the diamond pattern with only one loop statement.
In this example, we use Python 3.6 f-string highlight, a blend of the reversed(), and range() functions.
lines = 9 for x in list (range(lines)) +list(reversed(range (lines-1))): print(f" {'': <{ lines - x - 1}}{'':*<{ x * 2 + 1}}")
At the point when you run the above code, it prints the diamond pattern as indicated by our essential.
Output:
Related Posts
- How to compare dates in java|algorithm with source code
- Java roll dice 10000 times with algorithm and source code
- Write a Java program that displays the number of characters, lines, and words in a text
- Write a Java program that reads a file and displays the file on the screen with a line number before each line
- Write a Java program that reads a file name from the user, then displays information about whether the file exists, readable, writable, type of file, and the length of the file in bytes
- Java program to make frequency count of vowels, consonants, special symbols, digits, words in a given text
- Write a Java program for sorting a given list of names in ascending order
- Get Salesforce Answers