python - 协助计数循环

时间:2014-03-31 01:36:30

标签: python

以下是我的代码部分:

 if again():
        print ('%s T: %s') % (m, hsh)
        count = 1
        m = 0.001
        amount = m / 0.01
        amount = int(amount)
        print ('Betting %s m') % m
        apply(amount, int(count))
    else:
        print ('%s T: %s') % (m, hsh)
        try:
            count = count * 2
        except:
            count = 1
            count = count * 2

        print count    
        m = 0.001 * count
        amount = m / 0.01
        amount = int(amount)
        print ('K %s m') % m
        apply(amount, int(count))

如果函数again()返回true,那么它所要做的部分就是打印计数,如果again()为真,则始终设置为1。

如果返回false,则打印count * 2

如果它返回true 3次,则会打印

1
1
1

如果它返回false 3次,则会打印

2
4
8

然而,它只是打印

2
2
2

如果第一次返回false,则try除了未分配的变量错误。

我没有指定变量计数甚至在其他地方使用它。

2 个答案:

答案 0 :(得分:1)

我不知道你的其余代码是什么样的,但是count应该是一个全局变量,你对try/catch块的破解是非常糟糕的做法和非标准。

count设为全局变量,然后您可以将if/else重构为函数,然后调用它:

count = 1

# the rest of your code, I'm guessing some loop

def my_function(m, hsh):
    if again():
        print ('%s T: %s') % (m, hsh)
        count = 1
        m = 0.001
        amount = m / 0.01
        amount = int(amount)
        print ('Betting %s m') % m
        apply(amount, int(count))
    else:
        print ('%s T: %s') % (m, hsh)
        count = count * 2
        print count    
        m = 0.001 * count
        amount = m / 0.01
        amount = int(amount)
        print ('K %s m') % m
        apply(amount, int(count))

答案 1 :(得分:1)

您需要在if / else语句之外定义count

count = 1 #This could be defined outside the method or class and accessed with global


global count
if again():
        print ('%s T: %s') % (m, hsh)
        count = 1 #this will access the count outside the if
        m = 0.001
        amount = m / 0.01
        amount = int(amount)
        print ('Betting %s m') % m
        apply(amount, int(count))
    else:
        print ('%s T: %s') % (m, hsh)
        count = count * 2

        print count    
        m = 0.001 * count
        amount = m / 0.01
        amount = int(amount)
        print ('K %s m') % m
        apply(amount, int(count))

不确定你想要做什么