简体   繁体   English

我对 python for 循环 if 语句和多个 for 循环有疑问

[英]I have question about python for loop if statement and multiple for loop

So if I get input number "n" and what I want to do is print 1~n like this.所以如果我得到输入数字“n”,我想做的是像这样打印 1~n 。 If n = 10如果 n = 10

1

23

456

78910

and my code is this我的代码是这样的

x = int(input())
n=1
for i in range(1, x+1):
    sum = (n+1)*n // 2
    print(i , end = ' ')
    if(sum == i):
        print()
        n+=1

I solved this question with my TA but is there a way to solve using multiple for statements other than this one?我用我的助教解决了这个问题,但有没有办法解决使用多个 for 语句以外的语句? I don't want to use sum = (n+1)*n // 2 this part because my TA actually made this part without explanation.我不想使用sum = (n+1)*n // 2这部分,因为我的助教实际上没有解释就做了这部分。

I guess this is what you were thinking about:我想这就是你在想的:

x = int(input())
n = 1
for i in range(1, x+1):
    for j in range(1, i):
        if n <= x:
            print(n, end=' ')
        n += 1
    print()
    if n >= x:
        break

If you're worried about needlessly looping too often on j for very large x , you could change:如果您担心对于非常大的xj上不必要地循环太频繁,您可以更改:

        if n <= x:
            print(n, end=' ')
        else:
            break

of course you can do the summation using another for loop当然,您可以使用另一个 for 循环进行求和

sum = 0
for j in range(1,n+1):
    sum += j

you cold also do sum = sum(range(n+1)) , but (n + 1) * n // 2 is the best way of getting the summation of n你也感冒了sum = sum(range(n+1)) ,但是(n + 1) * n // 2是获得 n 总和的最佳方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM