Print a simple triangle using list and loops in python - python

Given n = 5
My triangle should look like this :
*
*+*
*+++*
*+++++*
*********
What i have tried :
n = 5
for x in range(0, n):
for y in range(0, n-x-1):
print(end = "")
for z in range(0,x+1):
print("*", end = "")
print()
but the result is like this :
*
**
***
****
*****
Thanks for help and maybe some explanations

def print_triangle(n):
print(" "*(n+1)+"*")
for x in range(0, n):
for y in range(0, n-x):
print(end=" ")
print("*+", end="")
for z in range(0,x):
print("++", end = "")
print("*")
print((1+2*(n+1))*"*")
print_triangle(5)

Try this function:
def tr(n):
print(" "*(n-1)+"*")
for x in range(1, n-1):
print(" "*(n-x-1), end="")
print('*', end="")
num = ((x-1)*2) +1
print("+"*num + "*")
print(((2*n)-1) *"*")
>>tr(5)
*
*+*
*+++*
*+++++*
*********

Related

Write a program that prompts the user to enter an integer number from 1 to 9 and displays two pyramids

I have the code for the 1st and the second pyramid, I just don't know how to put it together like how the question is asking. The first code below is for pyramid 1 and second is for the 2nd pyramid.
`
rows = int(input("Enter number of rows: "))
k = 0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k = 0
print()
`
`
rows = int(input("Enter number of rows: "))
k = 0
count=0
count1=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1
while k!=((2*i)-1):
if count<=rows-1:
print(i+k, end=" ")
count+=1
else:
count1+=1
print(i+k-(2*count1), end=" ")
k += 1
count1 = count = k = 0
print()
`
You just need to run the second loop after the first loop. Also your code for the second pyramid is incorrect so I changed that.
rows = int(input("Enter number of rows: "))
k = 0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k = 0
print()
k = 0
count=0
count1=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1
for k in range(i,0,-1):
print(k, end=' ')
for k in range(2,i+1):
print(k, end=' ')
count = 0
print()
Since the algorithm for constructing both pyramids is similar, it is better to make a function
def pyramid(n_rows, s_type='*'):
max_width = n_rows * 2 - 1
for i in range(0, n_rows):
stars = i * 2 + 1
side = (max_width - stars) // 2
if s_type == '*':
print(f"{' ' * side}{'* ' * stars}")
else:
side_nums = ' '.join(f'{x+1}' for x in range(0,i+1))
print(f"{' ' * side}{side_nums[1:][::-1]}{side_nums}")
rows = int(input("Enter number of rows: "))
pyramid(rows)
pyramid(rows, s_type='0')
You only need to input the row count once. You may also find using str.rjust easier for formatting.
rows = int(input('Enter a number from 1 to 9: '))
assert rows > 0 and rows < 10
output = [None] * (rows*2)
stars = '*' * (rows * 2 - 1)
for i in range(rows):
output[i] = stars[:i*2+1].rjust(rows+i)
s = ''.join(map(str, range(1, i+2))) + ''.join(map(str, range(i, 0, -1)))
output[i+rows] = s.rjust(rows+i)
print(*output, sep='\n')
Output:
Enter a number from 1 to 9: 6
*
***
*****
*******
*********
***********
1
121
12321
1234321
123454321
12345654321

Printing with reversed range

I want to print the following:
*
**
***
****
But both
for i in range(5):
for j in reversed(range(5)):
if j < i:
print('*', end='')
print()
and
for i in range(5):
for j in range(5):
if j < i:
print('*', end='')
print()
gives the same answer.
isn't the code with reversed supposed to give this?
*
**
***
****
You need to understand what is happening when you run those codes.
for i in range(5): # 0,1,2,3,4
for j in range(5): # 0,1,2,3,4
if j < i:
# when i = 0, no stars printed. j is never less than 0:
# when i = 1, one star printed. when j is 0, print a star.
# when i = 2, two starts printed. when j is 0,1 print stars.
print('*', end='')
print()
for i in range(5): # 0,1,2,3,4
for j in reversed(range(5)): # 4,3,2,1,0
if j < i:
# when i = 0, no stars printed. j is never less than 0:
# when i = 1, on last iteration when j = 0 one start printed.
# when i = 2, two starts printed. when j is 1,0 print stars.
print('*', end='')
print()
So basically both of the for loops are doing the same thing.
you are just printing stars. If you want to print spaces,
you have to tell the program to print spaces.
for i in range(5): # 0,1,2,3,4
for j in reversed(range(5)): # 4,3,2,1,0
if j < i:
print('*', end='')
else:
print(' ', end='') # telling to print the spaces.
print()
You can use ljust and rjust to help:
x = 5
for i in range(x):
print(('*'*i).ljust(x, ' '))
# Output:
*
**
***
****
for i in range(x):
print(('*'*i).rjust(x, ' '))
# Output:
*
**
***
****
Reversing the range doesn't work because it still prints the asterisks the same amount of times in the same way since you are not doing anything with the numbers. As the comments have said, the correct way to do this would be to print spaces before your asterisks. Here is a way to do this:
for i in range(5):
print(" "*(5-i) + "*" * i)

How to put full stops at the end of each line

How do I put full stops (.) at the end of each line in the code below?
num = 0
for i in range(0, 3):
for j in range(0, 5):
print(num, end=",")
num = num + 1
print("\r")
Current output:
0,1,2,3,4,
5,6,7,8,9,
10,11,12,13,14,
Output I want:
0,1,2,3,4.
5,6,7,8,9.
10,11,12,13,14.
Thank you in advance for any help!
num = 0
for i in range(0, 3):
for j in range(0, 5):
if j == 4:
print(num, end=". ")
else:
print(num, end=", ")
num = num + 1
print("\r")
num = 0
for i in range(0, 3):
for j in range(0, 5):
print(num, end=", ")
print('.')
num = num + 1
print("\r")
This should work. As the end of your variable 'num' when printed has been set to a comma and a space, printing the full stop should work in this way
You can do such like this. Hope this will work on your side
i_range = 3
j_range = 5
num = 0
for i in range(0, i_range):
for j in range(0, j_range):
ends_ = '.' if j_range - j == 1 else ','
print(num , end=ends_)
num +=1
print('\r')
You can build a dynamic list with the second range, then print it using *. This allows you to put the , character as separator, and also the . character as end in the same line.
num = 0
step = 5
for i in range(0, 3):
print(*range(num, num + step), sep=", ", end=". ")
num = num + step
print("\r")

the pattern i m getting in my output have the extra star at the end which is not required

The pattern I'm getting in my output have the extra star at the end which is not required, this is what I tried my self:
n=int(input("enter no"))
for i in range(1,n+1):
for j in range(i):
print("*",end="")
for k in range(1,(2*n)-2*i):
print(" ",end="")
for l in range(i):
print("*", end="")
print("")
I don't want extra star at the end.
You need to stop your loop at n - 1, and after the loop, print 2*n - 1 "*":
n=int(input("enter no"))
for i in range(1, n):
for j in range(i):
print("*", end="")
for k in range(1, 2*n - 2*i):
print(" ", end="")
for l in range(i):
print("*", end="")
print()
print("*" * (2*n - 1))
Output (for n = 5):
* *
** **
*** ***
**** ****
*********
Output (for n = 6):
* *
** **
*** ***
**** ****
***** *****
***********

Can't get output to rotate 180 degrees

I need to make a nested triangle of hash symbols. But I can't get it to rotate 180 degrees like I need it to, I am also not getting the 12 rows like I need to.
This is my code.
n = int(input("Enter a number: "))
for i in range (0, n):
for j in range(0, i + 1):
print("#", end='')
print("")
for i in range (n, 0, -1):
for j in range(0, i -1):
print("#", end='')
print("")
The Input value is 6.
Enter a number:6
#
##
###
####
#####
######
######
#####
####
###
##
#
But I keep getting this:
Enter a number: 6
#
##
###
####
#####
######
#####
####
###
##
#
How do I fix this?
You can use the str.rjust method to align a string to the right:
n = int(input("Enter a number: "))
for i in range(2 * n):
print(('#' * (n - int(abs(n - i - 0.5)))).rjust(n))
Demo: https://ideone.com/27AM7a
A bit late
def absp1(x):
if (x < 0):
return -x - 1
return x
n = int(input("Enter a number: "))
for i in range(-n, n):
for j in range(absp1(i)):
print(' ', end='')
for k in range(n-absp1(i)):
print('#',end='')
print()
You can use this (manually calculating number of spaces and hashtags):
n = int(input("Enter a number: "))
for i in range (1, n + 1):
print(" "*(n - i) + "#"*i)
for i in range (n, 0, -1):
print(" "*(n - i) + "#"*i)
Or use rjust:
n = int(input("Enter a number: "))
for i in range (1, n + 1):
print(("#"*i).rjust(n))
for i in range (n, 0, -1):
print(("#"*i).rjust(n))
Also this works fine
num = 6
sing = "#"
for i in range(1, num * 2):
if i > num:
spaces = " " * (i - num)
signs = sign * (2 * num - i)
line = "{0}{1}".format(spaces, signs)
elif i == num:
spaces = " " * (num - i)
signs = sign * i
line = "{0}{1}\n{0}{1}".format(spaces, signs)
else:
spaces = " " * (num - i)
signs = sign * i
line = "{0}{1}".format(spaces, signs)
print(line)

Categories