python中outside loop,使用Python,我怎样才能使用for循环金字塔?

本文指导如何编写一个仅使用一个print命令的Python程序,以在for循环中输出指定的'YYYYYYYYYYYYYYYYYYYYY'格式。通过简单示例和解释range函数及字符串操作,帮助读者理解并完成这道附加信用问题。
摘要由CSDN通过智能技术生成

I've been having trouble in one of my classes with this problem, I can't quite figure it out. This is what we were asked to do.

"Write a program that only has one print command AND ONLY ONE PRINT COMMAND in a FOR loop to provide the following output. You may use another PRINT command outside the FOR/NEXT loop. The letter ‘Y’ can be used only one time in your program."

And it is supposed to look like this

Y

YY

YYY

YYYY

YYYYY

YYYYYY

I would love to know how to do this, it's been bugging me all week but it was only an extra credit question so my teacher never explained how to do it!! :(

Help is greatly appreciated!

-Alex

解决方案

You could do something simple like this.

def create_pyramid(rows):

for i in range(rows):

print('Y' * ( i + 1))

create_pyramid(6)

Basically you set up a for loop with the number of rows you want. If you use range(number_of_rows) you will get a loop that starts at 0 and goes to 1, 2 etc until it has looped 6 times. You then use this by multiplying the number of Y characters you want in on each line using 'Y' * i, but keep in mind that the for loop starts counting from zero so you need to add + 1 to your i variable. Last you output the number of Y characters for each line to your screen using print.

The output of this would be:

Y

YY

YYY

YYYY

YYYYY

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值