I want to print a pyramid pattern of string in python, but with user inputs of starting character and the no. of rows. I have wrote this code below so far,
c = input("Enter a character - ")
def pattern(n):
a = ord(c)
for i in range(0, n):
for j in range(0, i 1):
ch = chr(a)
print(ch, end=" ")
a = a 1
print("\r")
n = int(input("Enter the no. of rows - "))
pattern(n)
But the output is:
Enter a character - A
Enter the no. of rows - 7
A
B C
D E F
G H I J
K L M N O
P Q R S T U
V W X Y Z [ \
Instead I want that after it's execution till the character 'z', it starts printing from character entered by the user for the same line only. And I want to make it work for both uppercase and lowercase alphabets.
CodePudding user response:
so this sounded interesting so I tried working around this code and this is what I came up with. I edited your original code and tried making two separate functions for upper and lowercase. The thing is that the range of the ASCII codes had to be specified in the if block and I couldn't condition both ranges at once so I tried making separate functions.
c = input("Enter a character - ")
def pyramid_caps(char):
a= ord(c)
b =ord(c)
for i in range(0, n):
for j in range(0, i 1):
ch = chr(a)
if a not in range(65,91):
a=b
continue
print(ch, end=" ")
a = a 1
print("\r")
def pyramid_lower(char):
a= ord(c)
b =ord(c)
for i in range(0, n):
for j in range(0, i 1):
ch = chr(a)
if a not in range(97,123):
a=b
continue
print(ch, end=" ")
a = a 1
print("\r")
n = int(input("Enter the no. of rows - "))
a=ord(c)
if a in range(65,90):
pyramid_caps(a)
elif a in range(97,122):
pyramid_lower(a)
CodePudding user response:
You could advance the current letter by 1, starting from c, until Z/z is reached, then reset to the initial letter:
def pattern(first,count):
letter = first
for row in range(count):
for _ in range(row 1):
print(letter,end=" ")
letter = first if letter in "Zz" else chr(ord(letter) 1)
print("")
Sample runs:
Enter a character - A
Enter the no. of rows - 7
A
B C
D E F
G H I J
K L M N O
P Q R S T U
V W X Y Z A B
Enter a character - p
Enter the no. of rows - 5
p
q r
s t u
v w x y
z p q r s
If you want an actual pyramid, you can add an indentation at the beginning of each row:
def pattern(first,count):
letter = first
for row in range(count):
print(" "*(count-row-1),end="") # indent for pyramid shape
for _ in range(row 1):
print(letter,end=" ")
letter = first if letter in "Zz" else chr(ord(letter) 1)
print("")
Enter a character - A
Enter the no. of rows - 7
A
B C
D E F
G H I J
K L M N O
P Q R S T U
V W X Y Z A B