0

I'm fairly new to programming, i have to start learning it for Uni.

I have to make a pattern as follow:

5 4 3 2 1
4 3 2 1
3 2 1
2 1
1

I have found ample examples of code for these patterns, just not for mine.

I cannot seem to get the numbers to line up vertically, only underneath each other:

5
4
3
2
1

4
3
2
1

what am i Missing ? I can't seem to find the exact function that other people are using to make their code act like this.


# Question 4.
import random

num1 = random.choice([5, 6, 7, 8, 9, 10])

def print_triangle():
    for row in range(num1, 0, -1):
        for space in range(num1 - row):
            print ('')

        for col in range(row, 0, -1):
            print (col)

print_triangle()

Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30
Ducky
  • 1

3 Answers3

1

Edit by Ducky:

import random

num1 = random.choice([5, 6, 7, 8, 9, 10])


def print_triangle():
for row in range(num1, 0, -1):
    for num in range(row, 0, -1):
        print(str(num) + " ", end="")
    print()

print_triangle()

My answer:

def print_triangle():
    for row in range(10, 4, -1):
        for num in range(row, 0, -1):
            print(str(num) + " ", end="")
        print()


print_triangle()

Output:

10 9 8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1 
7 6 5 4 3 2 1 
6 5 4 3 2 1 
5 4 3 2 1 

Or use:

def print_triangle(max_val, min_val):
    for row in range(max_val, min_val - 1, -1):
        for num in range(row, 0, -1):
            print(str(num) + " ", end="")
        print()


print_triangle(10, 5)
Spherical Cowboy
  • 565
  • 6
  • 14
  • Sorry for hijacking your answer, I could find any other way to put up my new code. I used yours and made a small edit. Now it calls a random number and completes the pyramid till 1. Thank you for the help. got some learning to do with my loops. – Ducky Mar 06 '17 at 12:24
0
for j in range(5, 0, -1):
    line = ''
    for i in range(j, 0, -1):
    line += str(i) + ' '
    print line
Dan Ionescu
  • 3,135
  • 1
  • 12
  • 17
0

The print statement puts each output on a new line.

Try

s = "" #make a string
s = s + " " + str(the number you want to print)

And then print s when each line is done.

James Wilson
  • 852
  • 13
  • 29