Home 05. Print Function
Post
Cancel

05. Print Function

Problem: Print Function

Solution 1: Using for loop

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

Solution 2: Using while loop

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

Solution 3: Using list comprehension

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

Solution 4: Using map() function

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

Solution 5: Using generator expression

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

Solution 6: Using generator function

1
2
3
4
5
6
7
def gen_numbers(n):
    for i in range(1, n+1):
        yield i

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

Solution 7: Using one-liner

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if __name__ == '__main__':
    print(*[i for i in range(1, int(input())+1)], sep='')

# or

if __name__ == '__main__':
    print(*range(1, int(input())+1), sep='')

# or
if __name__ == '__main__':
    print(''.join(map(str,range(1, int(input())+1))))

# or

if __name__ == '__main__':
    list(map(lambda x:print(x + 1, end=''), range(int(input()))))
This post is licensed under CC BY 4.0 by the author.

05. Loops

07. Write a function