简体   繁体   中英

why does this function always give me an error

i wanna try and make quick sort on my own but the functions always give me an error when trying to execute them

the code for now:

import random
pivot = 0
mop = 0
vop = 0
bobl = 0
lista = [2, 5, 1, 7, 9, 4, 6, 3, 8]
def mopcom():
    if lista.index(mop)>lista.index(pivot):
        mop = random.choice(lista)
        mopcom()
def vopcom():
    if lista.index(vop)<lista.index(pivot):
        vop = random.choice(lista)
        vopcom()
pivot = random.choice(lista)
mop = random.choice(lista)
vop = random.choice(lista)
mopcom()

the 2 functions that are causing issues:

def mopcom():
    if lista.index(mop)>lista.index(pivot):
        mop = random.choice(lista)
        mopcom()
def vopcom():
    if lista.index(vop)<lista.index(pivot):
        vop = random.choice(lista)
        vopcom()

the error:

Traceback (most recent call last):
  File "C:/Users/antem/OneDrive/Radna površina/pametno.py", line 22, in <module>
    mopcom()
  File "C:/Users/antem/OneDrive/Radna površina/pametno.py", line 11, in mopcom
    if lista.index(mop)>lista.index(pivot):
UnboundLocalError: local variable 'mop' referenced before assignment

please dont tell me that im doing quick sort wrong, as I want to try to do this on my own. just tell me why this is giving me errors

summary: Use function parameters.

Those global variables aren't doing you any favors.

You wrote:

def mopcom():
    if lista.index(mop)>lista.index(pivot):
        mop = random.choice(lista)
    ...

Line 2 reads mop , and line 3 writes to it. Well, it writes to a different mop , it writes to a newly created local variable of that name. Then you exit the function, the local goes out of scope, and it is garbage collected.

You could use the global keyword. But it would be much much better to pass the relevant variables as formal parameters, or to make this a class and refer to self.mop .

In python, variables are scoped by default. Consider this snippet:


x = 3

def foo():
    x = 4 # This is a new, different variable also called x

foo()
print(x) # Prints 3

Because of this, mop inside of mopcom is treated as a different value. To fix this, add the line global mop . This tells python that mop is actually a global value.

import random
pivot = 0
mop = 0
vop = 0
bobl = 0
lista = [2, 5, 1, 7, 9, 4, 6, 3, 8]
def mopcom():
    global mop
    global pivot
    global lista
    if lista.index(mop)>lista.index(pivot):
        mop = random.choice(lista)
        mopcom()
def vopcom():
    global vop
    global lista
    global pivot
    if lista.index(vop)<lista.index(pivot):
        vop = random.choice(lista)
        vopcom()
pivot = random.choice(lista)
mop = random.choice(lista)
vop = random.choice(lista)
mopcom()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM