问题
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.
回答1:
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.
回答2:
You can use reversed range
:
u=int(raw_input('Number:'))
for i in reversed(range(1,u)):
print ' '*(u-i),'*'*i
回答3:
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)
来源:https://stackoverflow.com/questions/19034814/reverse-upside-down-asterisk-triangle