python金字塔1 222 333 4444 55555,我如何在Python中创建一个递减的numberPyramid(num)?...

I'm trying to create a pyramid that looks like the picture below(numberPyramid(6)), where the pyramid isn't made of numbers but actually a black space with the numbers around it. The function takes in a parameter called "num" and which is the number of rows in the pyramid. How would I go about doing this? I need to use a for loop but I'm not sure how I implement it. Thanks!

666666666666

55555 55555

4444 4444

333 333

22 22

1 1

解决方案

First the code:

max_depth = int(raw_input("Enter max depth of pyramid (2 - 9): "))

for i in range(max_depth, 0, -1):

print str(i)*i + " "*((max_depth-i)*2) + str(i)*i

Output:

(numpyramid)macbook:numpyramid joeyoung$ python numpyramid.py

Enter max depth of pyramid (2 - 9): 6

666666666666

55555 55555

4444 4444

333 333

22 22

1 1

How this works:

Python has a built-in function named range() which can help you build the iterator for your for-loop. You can make it decrement instead of increment by passing in -1 as the 3rd argument.

Our for loop will start at the user supplied max_depth (6 for our example) and i will decrement by 1 for each iteration of the loop.

Now the output line should do the following:

Print out the current iterator number (i) and repeat it itimes.

Figure out how much white space to add in the middle.

This will be the max_depth minus the current iterator number, then multiply that result by 2 because you'll need to double the whitespace for each iteration

Attach the whitespace to the first set of repeated numbers.

Attach a second set of repeated numbers: the current iterator number (i) repeated itimes

When your print characters, they can be repeated by following the character with an asterisk * and the number of times you want the character to be repeated.

For example:

>>> # Repeats the character 'A' 5 times

... print "A"*5

AAAAA

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值