Question

These are two functions in a module I have written:

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()

I am looking to have it prompt for an initial number, run the readline function and then the control function. The control function should start with that initial number and then be able to increment/decrement it as it prompts after each time the readline function is run.

The actual behavior is that it will increment once and then remain the same. The previous control is less predictable; I am not sure what is happening there.

I have read to avoid global variables, and I feel that it may be the root of the issue. I am unsure on how to implement the alternatives.

Thank you for any help!

Was it helpful?

Solution

Try this:

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()

This keeps it local, no need for globals, and it puts it into a loop which should reduce overhead. I also added a Quit option.

OTHER TIPS

Haven't tried it, but why not pass it as an argument?

Like this:

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()

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top