【问题标题】:How to avoid double iteration, and printing the statement 2 times如何避免重复迭代,并打印语句 2 次
【发布时间】:2019-06-21 13:22:15
【问题描述】:

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

【问题讨论】:

  • else 与您的if 一起使用?
  • 仅供参考:if time == 25: 处的死代码因为您正在使用 time != 25 并且增量始终为 1

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


【解决方案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

【讨论】:

    【解决方案2】:

    你总是打印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
    

    【讨论】:

    • 另请注意:您的另一个 if time == 25:while time!=25: 内没有任何意义(在 if 之后完成增量)。
    【解决方案3】:

    一个相同的衬垫可以实现如下:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-18
        • 2020-09-19
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-11
        相关资源
        最近更新 更多