reverse upside down asterisk triangle in python

2019-01-29 04:43发布

I am trying to use nested for loops to ask the user for an integer and then the program will output a reverse, upside down triangle, with the base of it having the number of asterisks and working its way down. It's supposed to look like this:

*****
 ****
  ***
   **
    *

The code I have:

def pattern():
  integer = requestInteger("Please enter a number")
  for number in range(0, integer):
    for variable in range(integer, 0, -1):
      if variable - 1 > number:
        sys.stdout.write(' ')
      else:
        sys.stdout.write('*')
  sys.stdout.write('\n')

Outputs this:

    *
   **
  ***
 ****
*****

I'm not really sure how to go about changing my for loops around to make this work, and I've been trying for a while, so help would be much appreciated. Thank you

3条回答
祖国的老花朵
2楼-- · 2019-01-29 05:16

I know it's been such a lang time, but i want to share my approach to the question.

def pattern(size):
    for i in reversed(range(1, size+1)):
        print("*" * i)
查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-29 05:38

My take would be something like this:

def pattern():
    integer = int(raw_input("Please enter a number"))
    for number in range(0, integer):
        print " " * number + "*" * (integer - number)

Is this homework (nested loops are mandatory)? Hint: the * operator can be easily replaced by a for loop.

查看更多
该账号已被封号
4楼-- · 2019-01-29 05:41

You can use reversed range:

u=int(raw_input('Number:'))
for i in reversed(range(1,u)):
    print ' '*(u-i),'*'*i
查看更多
登录 后发表回答