How to print a plus pattern using Python

Nested for loops are used to display patterns by using asterisks (*), numbers, and letters. We can display a plus pattern in Python. This is shown in the figure below:

Plus pattern

Example

The asterisk symbol (*) prints the plus shape pattern in the following code below:

#function for print plus pattern
def plusplattern(number):
for x in range(1, number * 2):
for y in range(1, number * 2):
if (x==number) or (y==number):
print('*', end='')
else:
print(' ', end='')
print()
#driver code
plusplattern(3)

Explanation

  • Line 2: We define a pluspattern()function which accepts a number. We display the pattern have number stars in each segment of the pattern.
  • Lines 3-9: We use a nested for loop to print the pattern. The outer loop is used for the number of rows while the inner loop is used for the columns in the pattern.
  • Line 5: We use if statement (x==number) or (y==number). If it is true, we display the *, otherwise ' '.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved