0

I am trying to create a beginner level program to better understand programming in python. A simple while true loop that adds a value of 1 to X and prints "help" or "doing something" depending on if x is less than or greater than 10; and then breaks when x is greater than 20. Im also attempting to add in a keyboard interrupt as well to break the loop if its not too complicated.. Any tips help, I get an error

Traceback (most recent call last):
  File "so.py", line 23, in <module>
    help()
  File "so.py", line 11, in help
    x += 1
UnboundLocalError: local variable 'x' referenced before assignment

Code:

import time

x = 1

try:

    def help():

        print("Help.")
        time.sleep(2)
        x += 1


    def doStuff():

        print("Doing Stuff")
        time.sleep(2)
        x += 1

    while True:

        if x < 10:
            help()
        elif x < 20 and x > 10:
            doStuff()
        else:
            break

except KeyboardInterrupt:
    exit()
Prune
  • 76,765
  • 14
  • 60
  • 81
bbartling
  • 3,288
  • 9
  • 43
  • 88

1 Answers1

2

The problem is exactly what the error message says ... once you know how to interpret those words.

def help():

    print("Help.")
    time.sleep(2)
    x += 1

You are trying to change a variable x. This requires that x must already have a value. However, you cannot change a global variable unless you've declared your intention to refer to one outside your function. Therefore, Python expects that you have a local variable x -- which you haven't made. Simply declare the variable as required:

def help():
    global x

    print("Help.")
    time.sleep(2)
    x += 1

Now, your program will print Help. 10 times and quit.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • 1
    Note that you can use and mutate variables (if they are mutable) in the global scope without using the global keyword. The global keyword is only required when you wish to rebind the variable to a new object (which is what += does for int) – John La Rooy Sep 20 '18 at 21:13
  • Ok cool do you know how I can add something in for the key interrupt? – bbartling Sep 20 '18 at 21:14
  • (1) That's a separate question. (2) At Stack Overflow, we expect you to try to solve it on your own first. Look for the `keypress` method. – Prune Sep 20 '18 at 21:23
  • @JohnLaRooy -- quite correct; thanks for the addition. I was keeping it simple, but the rebinding detail is good to know for the OP's level. – Prune Sep 20 '18 at 21:24