My function is not defined properly, can anyone tell me why?

Question:

I have a main function, and a getDogYears function that contains the variable dogYears. I have tried moving getDogYears above the main function, and I have tried initializing dogYears in the main function. I know dogYears is outside the scope of the main function, so can anyone tell me how I can make my main function be able to display information found in getDogYears? I’m sure it’s something silly, but it would be a great lesson for me. Thank you!

The error: Traceback (most recent call last):
line 38, in
main()
line 21, in main
format(dogYears, ",.1f"), "in dog years.")
NameError: name ‘dogYears’ is not defined. Did you mean: ‘getDogYears’?

FIRST_YEAR_EQUIV = 15
SECOND_YEAR_EQUIV = 9
THREE_PLUS_YEARS_MULTIPLIER = 5

def main():
    print("This program calculate's a dog's approximate age in "dog years" based on human years.n")

    humanYears = float(input("Dog's age in human years? "))

    while humanYears < 0:
        print("nHuman age must be a positive number.")
        humanYears = float(input("Dog's age in human years? "))
    else:
        getDogYears(humanYears)

        # end if
    print("nA dog with a human age of", format(humanYears, ",.1f"), "years is", 
    format(dogYears, ",.1f"), "in dog years.")


def getDogYears(humanYears):
    if humanYears <= 1:
        dogYears = FIRST_YEAR_EQUIV * humanYears
    elif humanYears <= 2:
        dogYears = FIRST_YEAR_EQUIV + SECOND_YEAR_EQUIV * (humanYears - 1)
    else:
        dogYears = FIRST_YEAR_EQUIV + SECOND_YEAR_EQUIV + THREE_PLUS_YEARS_MULTIPLIER * (humanYears - 2)


# DO NOT MODIFY CODE BELOW THIS LINE
if __name__ == "__main__":
    main() ```
Asked By: darktown

||

Answers:

Do a return dog years from getDogYears(), and do dogYears = getDogYears(humanYears) inside the main() function.

FIRST_YEAR_EQUIV = 15
SECOND_YEAR_EQUIV = 9
THREE_PLUS_YEARS_MULTIPLIER = 5

def main():
    print("This program calculate's a dog's approximate age in "dog years" based on human years.n")

    humanYears = float(input("Dog's age in human years? "))

    while humanYears < 0:
        print("nHuman age must be a positive number.")
        humanYears = float(input("Dog's age in human years? "))
    else:
        dogYears = getDogYears(humanYears)

        # end if
    print("nA dog with a human age of", format(humanYears, ",.1f"), "years is", 
    format(dogYears, ",.1f"), "in dog years.")


def getDogYears(humanYears):
    if humanYears <= 1:
        dogYears = FIRST_YEAR_EQUIV * humanYears
    elif humanYears <= 2:
        dogYears = FIRST_YEAR_EQUIV + SECOND_YEAR_EQUIV * (humanYears - 1)
    else:
        dogYears = FIRST_YEAR_EQUIV + SECOND_YEAR_EQUIV + THREE_PLUS_YEARS_MULTIPLIER * (humanYears - 2)
    return dogYears
Answered By: Don Kaluarachchi
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.