0

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

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 函数,然后运行 ​​control 函数。控制功能应该以该初始数字开始,然后能够在每次运行 readline 功能后根据提示增加/减少它。

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

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

感谢您的任何帮助!

4

2 回答 2

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选项。

于 2013-10-14T14:51:45.820 回答
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()

希望这可以帮助!

于 2013-10-14T14:46:13.627 回答