How would you print number 1,2,3,4,5,6,7,8,18,19,20,21,22,23,24 in python?

Viewed 681

I had knowledge about java so I tried writing an if block within the for block saying,

for i in range(25):
    if i == 9:
        i = 18
    print(i)

This code logic works in java but not in python. What should I do?

4 Answers

Use two ranges and the power of itertools.

import itertools

for i in itertools.chain(range(1, 9), range(18,25)):
    print(i)

Using a while loop instead worked

i = 1
while i < 25:
    if i == 9:
        i += 9
    print(i)
    i += 1

Output

1
2
3
4
5
6
7
8
18
19
20
21
22
23
24

A better way to print the above sequence is through a while loop:

max_num = 25
i = 1
while i < max_num:
    if i == 9:
        print(18)
        i == 19
    else:
        print(i)
        i += 1

Use two loops

for i in range(1, 9):
    print(i)
    
    
for i in range(18,25):
    print(i)
Related