简体   繁体   中英

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. If 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? I don't want to use sum = (n+1)*n // 2 this part because my TA actually made this part without explanation.

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:

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

of course you can do the summation using another for loop

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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