Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何避免重复,并将语句打印两次_Python_Python 3.x_Function_Loops_If Statement - Fatal编程技术网

Python 如何避免重复,并将语句打印两次

Python 如何避免重复,并将语句打印两次,python,python-3.x,function,loops,if-statement,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:

我有一段代码,它打印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

您总是打印
时间
,您必须将此决定分支,并且仅当您没有打印“休息部分”时才执行此操作

为了更简洁,您可以随时打印时间,但请选择后缀(空或“休息一下”)

time=0
而时间!=25:
打印(时间,如果时间%8==0,则“您需要休息”,如果时间!=0,则为其他“”)
如果时间=25:
时间=0
时间+=1

相同的一个衬里可按如下方式实现:

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循环!!

在第一个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

使用
else
和你的
if
一起使用
FYI:dead code at
if time==25:
因为你在
time!=25的时候使用,增量总是按
1
递增所以注意:如果time==25:
你的另一个
while time!=25:
内没有任何意义(增量在if之后完成)。
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