简体   繁体   中英

Beginner trying to debug an easy program

I'm a student and am just beginning to learn code. Right now I'm working with Python and have a program I think should work, but just returns some errors that I don't understand:

Traceback (most recent call last): File "C:\\Program Files\\Notepad++\\1913lab3.py", line 23, in print(most(odd, []))

File "C:\\Program Files\\Notepad++\\1913lab3.py", line 9, in most N = S[i] UnboundLocalError: local variable 'i' referenced before assignment

I don't understand what the first error tells me, but the I think I understand the second one, but I don't understand why I'm getting it. I don't think i is a local variable as I defined it right away in the beginning. Here's the code:

t = 0
f = 0
i = 0

def odd(N):
    return N % 2 != 0

def most(P, S):
    N = S[i]
    if P == True:
        t += 1
    else:
        f += 1
    i += 1
    if i < len(S):
        most(P, S)
    else:
        if t > f:
            return 'True'
        else:
            return 'False'

print(most(odd, []))
print(most(odd, [0]))
print(most(odd, [1]))
print(most(odd, [1, 2]))
print(most(odd, [1, 2, 3]))

The assignment is to define a recursive function (most()). The function takes one function and one list as its arguments (P and S). I can't use loops or local variables. Here's a quote from the assignment:

"P is a function of one argument that returns either True or False, and S is a list. The function most calls P on each element of S. It must return True if P returns True more often than it returns False. It must return False otherwise."

The 5 print commands are just 5 examples that I need to work for credit, but this program needs to work for all lists. If anyone can help me fix these errors, that'd be great. (Also, any general Python tips would be welcome.)

By default any variable that is modified within a function is assumed to be local to that function. So if you have i += 1 , i must be defined within the function first. Or you have to declare i as a global first ( global i ) so that python knows it is refering to the i you have defined (first) outside the function. But beware with globals, they are often dangerous (as they make it hard to keep track what is going on) and should be avoided if possible.

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