简体   繁体   中英

How to avoid double iteration, and printing the statement 2 times

I have this piece of code, where it prints the numbers from 0-24 and it prints you need a break when time is equal to 8, 16, 24, now the point is when time is 8, 16 and 24 it prints the time and the statement '8 you need to take a break', but also after it iterates the code, beneath the time and statement it print the time again, can you please explain how to avoid this?

time=0
while time!=25:
    if time%8==0 and time!=0:
        print (time,'you need to take a break')
    if time == 25:
        time=0
    print (time)
    time+=1

This is the result i get.
0
1
2
3
4
5
6
7
8 you need to take a break
8
9
10
11
12
13
14
15
16 you need to take a break
16
17
18
19
20
21
22
23
24 you need to take a break
24

And this is want i want to get
0
1
2
3
4
5
6
7
8 you need to take a break
9
10
11
12
13
14
15
16 you need to take a break
17
18
19
20
21
22
23
24 you need to take a break
time=0
while time!=25:
    if time%8==0 and time!=0:
        print(time,'you need to take a break')
    else:
        print(time)
    if time == 25:
        time=0
    time+=1

you always print time , you have to branch this decision, and do it only if you didn't print the "take a break part"...

to be even more concise, you can always print time, but choose a suffix (empty or "take a break"

time=0
while time!=25:
    print(time,'you need to take a break' if time%8==0 and time!=0 else '')
    if time == 25:
        time=0
    time+=1

One liner for the same can be implemented as below:

print(*["{} you need to take a break".format(time) if time%8==0 and time!=0 else time for time in range(25)], sep="\n")

FYI: Use for loop if you are sure of number of iterations!!

Use else in a first if statement and print time in else statement that will give you a required output.

time=0
while time!=25:
    if time%8==0 and time!=0:
         print (time,'you need to take a break')
    else:
         print(time)
    if time == 25:
         time=0
#        print (time)
    time+=1

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