b13rg
b13rg

Reputation: 490

Python variable Name.Error

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!

Upvotes: 1

Views: 1021

Answers (1)

vks
vks

Reputation: 67968

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.

Upvotes: 2

Related Questions