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

Time:10-11

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() ```

CodePudding user response:

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
  • Related