嵌套循环Python [英] Nested Loop Python

查看:183
本文介绍了嵌套循环Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

count = 1
for i in range(10):
    for j in range(0, i):
        print(count, end='')
        count = count +1
    print()
input()

我正在编写一个程序,其输出应如下所示.

I am writing a program that should have the output that looks like this.

1

22

333

4444

55555

666666

7777777

88888888

999999999   

使用上面的代码,我已经很接近了,但是我的计数工作方式实际上是不断增加的.我只需要帮助,使其仅计数到9,但显示如上.谢谢.

With the above code I am pretty close, but the way my count is working it just literally counts up and up. I just need help getting it to only count to 9 but display like above. Thanks.

推荐答案

您正在内部循环中递增count,这就是为什么在您想要获得更大的数字之前

You're incrementing count in the inner loop which is why you keep getting larger numbers before you want to

您可以这样做.

>>> for i in range(1, 10):
        print str(i) * i


1
22
333
4444
55555
666666
7777777
88888888
999999999

或者如果您出于某些原因想要嵌套循环

or if you want the nested loop for some reason

from __future__ import print_function

for i in range(1, 10):
    for j in range(i):
        print(i, end='')
    print()

这篇关于嵌套循环Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆