1

I keep getting the error: "UnboundLocalError: local variable 'Pitch' referenced before assignment" is there any way to fix this?

import winsound, random

Pitch = random.randint(1000, 10000)
Duration = random.randint(100, 500)

def random():
    winsound.Beep(Pitch, Duration)
    Pitch = random.randint(1000, 10000)
    Duration = random.randint(100, 500)
    winsound.Beep(Pitch, Duration)
    Pitch = random.randint(1000, 10000)
    Duration = random.randint(100, 500)
    winsound.Beep(Pitch, Duration)
    Pitch = random.randint(1000, 10000)
    Duration = random.randint(100, 500)
    winsound.Beep(Pitch, Duration)
    Pitch = random.randint(1000, 10000)
    Duration = random.randint(100, 500)
    winsound.Beep(Pitch, Duration)

random()
Mod_Punchtree
  • 13
  • 1
  • 5
  • You need to mark them as global: `global Pitch, Duration`. Also, don't name your function `random` if you're importing the module `random`! – senshin Dec 21 '15 at 19:01
  • 1
    Just delete the ones at global scope. Looks like they aren't used. – wim Dec 21 '15 at 19:02

2 Answers2

2

The Pitch and Duration variables in the winsound.Beep(Pitch, Duration) line have not been defined yet. They're distinct from the variables of the same name in the global scope.

In order to inform the interpreter that your Pitch and Duration variables are the same as those defined in the global scope, you need to use the global keyword in your function:

def random():
    global Pitch, Duration    # <<--- this resolves your scoping issue
    winsound.Beep(Pitch, Duration)
    Pitch = random.randint(1000, 10000)

Also, you should defintely rename your function and avoid naming your functions with the same names as those in the Python library.

code_dredd
  • 5,915
  • 1
  • 25
  • 53
0

Use global:

def random():
    global Pitch, Duration
    ...

But also please have a look that you re-define module random with the function random().

Please rename the function to, well, random_func()

You can also use loops:

import winsound, random

def rand_func():
    for _ in range(5):
        Pitch = random.randint(1000, 10000)
        Duration = random.randint(100, 500)
        winsound.Beep(Pitch, Duration)

rand_func()
baldr
  • 2,891
  • 11
  • 43
  • 61