简体   繁体   中英

printing a right triangle in python starting with input n with rows n

I am printing a right triangle in python of numbers that is supposed to look like this:

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

I am able to print a right triangle using a nested loop but I cannot figure out how to print the numbers backwards I can only get it working from 0...n

Code:

for row in range(1, lastNumber):
    for column in range(1, row + 1):
        print(column, end=' ')
    print("")

From the python docs on range :

class range(start, stop[, step])

If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. If step is zero, ValueError is raised.

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.

In your case, you would want to say

for row in range(lastNumber, 1, -1):

You can see more about range at https://docs.python.org/3/library/stdtypes.html?highlight=range#range .

Check docs of range() , there's step argument, which allow you to pass increment of each step. So, correct way to use it in your code will be:

for row in range(lastNumber):
    for column in range(lastNumber, lastNumber - row - 1, -1):
        print(column, end=" ")
    print("")

There's also a couple one-liners, which do same:

print("\n".join(" ".join(map(str, range(5, 4 - n, -1))) for n in range(5)))
print(*(" ".join(map(str, range(5, 4 - n, -1))) for n in range(5)), sep="\n")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM