【问题标题】:how to properly setup python counter? and what is wrong with current logic?如何正确设置python计数器?当前的逻辑有什么问题?
【发布时间】:2021-05-27 23:15:14
【问题描述】:
def some_func():
  success_count = 0
  fail_count = 0
  try:
    do_this_thing()
    success_count += 1
    fail_count = 0
    print(f"success count is {success_count}.")

  except this_error:
    fail_count += 1
    success_count = 0
    print(f"retrying. retried {fail_count} times.")

这是我的代码的结构。除了success_count和fail_count之外,其他一切都很好。 id期望每次运行try函数都会重置success_count,当遇到异常时会重置success_count,输出如下所示。

success count is 1.
success count is 2.
success count is 3.
retrying. retried 1 times.
retrying. retried 2 times.
success count is 1.
success count is 2.

但我得到了:

success count is 1.
success count is 2.
success count is 3.
retrying. retried 1 times.
retrying. retried 2 times.
success count is 4.
success count is 5.

目前的逻辑有什么问题?为什么success_count没有被重置。

编辑: 以下代码用于重现问题,并且测试代码以某种方式完美运行。然而我的真实代码,使用相同的结构却没有。现在我更困惑了。

import time
import random
def randomly_raise_except_func():
  k = random.randint(1,2)
  if k == 1:
    pass
  if k == 2:
    raise ValueError("this is a error to recreate the problem")

def some_func():
  success_count = 0
  fail_count = 0
  while True:
    try:
        randomly_raise_except_func()
        success_count += 1
        fail_count = 0
        print(f"success count is {success_count}.")
        time.sleep(2)
    except ValueError:
        fail_count += 1
        success_count = 0
        
        print(f"retrying. retried {fail_count} times.")
        time.sleep(2)
        continue
      
some_func()

【问题讨论】:

  • 您正在打印{success_counter} 而不是{success_count}。是错字吗?
  • 是的。 @meowulf,我将其编辑为正确的内容。
  • 看来您正在使用循环,但在哪里?是在some_func() 函数之外还是在some_func() 函数内部?
  • 如果您可以将代码重写为可复制的最低限度的代码,我们可以将其复制到我们自己的环境中运行和调试,这将更容易回答。我的第一个猜测是问题出在您提供的代码之外。
  • @meowulf 如果循环在some_func 的外部,则每次调用该函数时计数器都会重置为 0,因此我们永远不会看到大于 1 的值。

标签: python python-3.x counter


【解决方案1】:

我添加了这一行:

random.seed(22)  # set a seed, so that results are reproducible

之前

some_func()

所以我得到了输出:

success count is 1.
success count is 2.
success count is 3.
retrying. retried 1 times.
success count is 1.
success count is 2.
retrying. retried 1 times.
success count is 1.
success count is 2.
...

这对我来说看起来不错:每次发生异常时,成功计数器都会重置为 0。您的代码似乎按照您的要求执行。如果不是,请提供说明。

【讨论】:

    猜你喜欢
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 2016-05-07
    • 2019-03-05
    • 1970-01-01
    相关资源
    最近更新 更多