简体   繁体   中英

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

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?

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)

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