如何避免两次迭代,并将语句打印两次

时间:2019-06-21 13:22:15

标签: python python-3.x function loops if-statement

我有这段代码,它在0到24之间打印数字,并且在时间等于8、16、24时打印需要休息一下,现在的关键是当时间是8、16和24时打印时间和语句“您需要休息一下8”,但是在迭代代码之后,在时间下方又声明它再次打印时间,请您说明如何避免这种情况?

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

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您始终打印time,您必须分支此决定,并且仅当您不打印“请休息一下”时才这样做。

为了更加简洁,您可以随时打印时间,但可以选择后缀(空或“稍作休息”

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

答案 2 :(得分:0)

可以使用一个相同的衬纸,如下所示:

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")

仅供参考:如果您确定迭代次数,请使用for循环!

答案 3 :(得分:0)

在第一个if语句中使用else,并在else语句中使用打印时间,这将为您提供所需的输出。

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