Home 05. Loops
Post
Cancel

05. Loops

Problem: Loops

Solution 1: Using for loop

1
2
3
4
if __name__ == '__main__':
    n = int(input())
    for i in range(n):
        print(i**2)

Solution 2: Using while loop

1
2
3
4
5
6
if __name__ == '__main__':
    n = int(input())
    i = 0
    while i < n:
        print(i**2)
        i += 1

Solution 3: Using list comprehension

1
2
3
if __name__ == '__main__':
    n = int(input())
    print(*[i**2 for i in range(n)], sep='\n')

Solution 4: Using map() function

1
2
3
if __name__ == '__main__':
    n = int(input())
    print(*map(lambda x: x**2, range(n)), sep='\n')

Solution 5: Using generator expression

1
2
3
if __name__ == '__main__':
    n = int(input())
    print(*list(i**2 for i in range(n)), sep='\n')

Solution 6: Using generator function

1
2
3
4
5
6
7
def gen_squares(n):
    for i in range(n):
        yield i**2

if __name__ == '__main__':
    n = int(input())
    print(*gen_squares(n), sep='\n')

Solution 7: Using power() function and one-liner

1
2
3
4
from math import pow

if __name__ == '__main__':
    print(*[int(pow(i, 2)) for i in range(int(input()))], sep='\n')
This post is licensed under CC BY 4.0 by the author.

04. Python Division

05. Print Function