Having trouble with def functions

Question:

I have been taking this class for a bit with python for a bit and I have stumbled into a problem where any time I try to "def" a function, it says that it is not defined, I have no idea what I am doing wrong and this has become so frustrating.

# Define main
def main():
    MIN = -100
    MAX = 100
    LIST_SIZE = 10
#Create empty list named scores
scores = []
# Create a loop to fill the score list
for i in range(LIST_SIZE):  
    scores.append(random.randint(MIN, MAX))
    #Print the score list
    print(scores) 
    print("Highest Value: " + str(findHighest(scores)))

Every time I try to test run this, I get

"builtins.NameError" name ‘LIST SIZE’ is not defined.

I cant take out the main function! It’s required for the assignment, and even if I take it out I still run into errors.

Asked By: Rin M

||

Answers:

Your MIN, MAX, and LIST_SIZE variables are all being defined locally within def main():

By the looks of it, you want the code below those lines to be part of main, so fix the indentation to properly declare it as part of main.

def main():
    MIN = -100
    MAX = 100
    LIST_SIZE = 10

    #Create empty list named scores
    scores = []

    # Create a loop to fill the score list
    for i in range(LIST_SIZE):  
        scores.append(random.randint(MIN, MAX))
        #Print the score list
        print(scores) 
        print("Highest Value: " + str(findHighest(scores)))
Answered By: Trooper Z
import random

# Define main
def main():
    MIN = -100
    MAX = 100
    LIST_SIZE = 10
    #Create empty list named scores
    scores = []
    # Create a loop to fill the score list
    for i in range(LIST_SIZE):  
        scores.append(random.randint(MIN, MAX))
        #Print the score list
        print(scores) 
        print("Highest Value: " + str(findHighest(scores)))
main()

Output:

[79]

NOTE: You will get another error message:

NameError: name 'findHighest' is not defined

Which I think findHighest should be a function in some part of your code.

Answered By: Jamiu Shaibu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.