1

In python I am writing a program to calculate a grade in a class, taking into account the types of course work, the weight of each, and scores. This is the code:

def get_initial_input():
    try:
        tests = int(input("How many tests are there? "))   #get number of tests
    except ValueError:
        print("Invalid number")
        get_initial_input()
    class_weight()

def class_weight():
    print("What is the weighted percent of the class?")
    if tests > 0:     #<-- this is where the error is
        try:
            tests_weight = float(input("Tests: "))
        except ValueError:
            print("Invalid weight")
            class_weight()

def main():
    get_initial_input()

main()

Whenever I run it I get a builtins.NameError occurred Message: name 'tests' is not defined error. It seems like the variable is defined earlier in the program, but it seems that it isn't defined properly for some reason. Any help would be appreciated!

2
  • 2
    tests is not known in class_weight as it's defined in get_initial_input, it's known only in the function's scope. Commented Nov 16, 2014 at 8:54
  • Having a function call itself when it gets bad input is not a good design strategy. See if you can re-write your functions to use while loops instead. Even better, try to avoid using input() in the inner functions of your program, as I discuss in the last paragraph of this answer. Commented Nov 16, 2014 at 12:37

1 Answer 1

2
def get_initial_input():
    try:
        tests = int(input("How many tests are there? "))   #get number of tests
    except ValueError:
        print("Invalid number")
        get_initial_input()
    class_weight(tests)

def class_weight(tests):
    print("What is the weighted percent of the class?")
    if tests > 0:     #<-- this is where the error is
        try:
            tests_weight = float(input("Tests: "))
        except ValueError:
            print("Invalid weight")
            class_weight()

def main():
    get_initial_input()

main()

Just pass tests and it will work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.