Python:递增/递减全局变量(或替代方法)

时间:2013-10-14 14:38:25

标签: python global-variables increment decrement

这是我编写的模块中的两个函数:

def start():
    numberstr = raw_input("Enter a number to start ")
    global number
    number = int(numberstr)
    readline("data.csv", number)
    control()

def control():
    operation = raw_input("Repeat (R), Next (N), or Previous (P) ")
    if operation == "R":
        readline("data.csv", number)
        control()
    elif operation == "N":
        readline("data.csv", number + 1)
        control()
    elif operation == "P":
        readline("data.csv", number - 1)
        control()
    else:
        print "Incorrect command"
        control()

start()

我希望让它提示初始编号,运行readline函数然后控制函数。控制功能应以该初始编号开始,然后能够在每次运行readline功能后按提示递增/递减。

实际行为是它会增加一次然后保持不变。以前的控制不太可预测;我不确定那里发生了什么。

我已阅读以避免全局变量,我觉得它可能是问题的根源。我不确定如何实施替代方案。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

试试这个:

def operate():
    number = input("Enter a number to start: ")
    while True:
        readline("data.csv", number)
        op = raw_input("Repeat (R), Next (N), Previous (P), or Quit (Q) ")
        if op == "R": pass
        elif op == "N": number += 1
        elif op == "P": number -= 1
        elif op == "Q": break
        else: raise Exception("Incorrect command")

operate()

这使它保持本地,不需要全局变量,并将它放入一个应该减少开销的循环中。我还添加了Quit选项。

答案 1 :(得分:0)

没有尝试过,但为什么不将它作为参数传递?

像这样:

def start():
    numberstr = raw_input("Enter a number to start ")
    number = int(numberstr)
    readline("data.csv", number)
    control(number)

def control(number):
    operation = raw_input("Repeat (R), Next (N), or Previous (P) ")
    if operation == "R":
        readline("data.csv", number)
        control(number)
    elif operation == "N":
        number +=1
        readline("data.csv", number)
        control(number)
    elif operation == "P":
        number -=1
        readline("data.csv", number)
        control(number)
    else:
        print "Incorrect command"
        control(number)
start()

希望这有帮助!