You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python简单循环程序报错求助:NameError: name 'age'未定义

Fixing the "NameError: name 'age' is not defined" in Your Python Program

Hey Lindsay, let's sort out that error you're hitting! The problem is super straightforward—your another_rec() function is trying to use the age variable, but it doesn't have access to it. Here's why and how to fix it:

What's Causing the Error?

The age variable is defined inside your main_module() function. Variables created inside a function are local to that function, meaning other functions can't see them unless you explicitly pass them over. Right now, another_rec() is trying to reference age like it's available everywhere, but Python doesn't know what you're talking about.

Step-by-Step Fixes

We need to make two key changes to get this working properly, plus a small tweak to make your input handling more user-friendly:

  1. Pass age as a parameter to another_rec()
    Update the function definition to accept age as an argument, so it can use it to generate recommendations:

    def another_rec(age):
    
  2. Send age when calling another_rec() in main_module()
    When you call the function from main_module(), pass the age variable you calculated:

    another_rec(age)
    
  3. Handle case-insensitive input (optional but nice!)
    Right now, if the user types "y" lowercase instead of "Y", your loop will exit. Let's make the input check case-insensitive by converting the input to uppercase:

    second_rec = input("Would you like another recommendation Y/N: ").upper()
    

Full Fixed Code

Here's the complete working code with all the fixes applied, keeping your modular structure intact:

import random

def greeting():
    print("Hi there, welcome to the world's simplest tv suggestion program!")
    print("")

def get_birth_year():
    birth_year = 0
    birth_year = input("Please enter your year of birth: ")
    is_valid = is_year_valid(birth_year)
    while not is_valid:
        birth_year = input("Please enter a four digit year of birth: ")
        is_valid = is_year_valid(birth_year)
    birth_year = int(birth_year)
    return birth_year

def is_year_valid(birth_year):
    try:
        birth_year = int(birth_year)
        # Add a check for 4-digit year to make validation stricter!
        is_valid = 1900 <= birth_year <= 2024
    except ValueError:
        is_valid = False
    return is_valid

def calculate_age(birth_year):
    age = 2018 - birth_year
    return age

def show_rec_output(age):
    print("Based on your age, a good Netflix show for you to watch would be:")
    adult = ["Master of None", "Unbreakable Kimmy Schmidt", "Black Mirror", "Godless", "Dear White People", "Grace and Frankie", "Jessica Jones"]
    all_ages = ["The Crown", "The Great British Bake Off", "Jessica Jones", "Sherlock", "A Series of Unfortunate Events", "Big Mouth"]
    if age >= 18:
        print(random.choice(adult))
    else:
        print(random.choice(all_ages))

def another_rec(age):
    second_rec = input("Would you like another recommendation Y/N: ").upper()
    while second_rec == "Y":
        show_rec_output(age)
        second_rec = input("Would you like another recommendation? Y/N: ").upper()
    print("Go make some popcorn!")

def main_module():
    greeting()
    birth_year = get_birth_year()
    age = calculate_age(birth_year)
    show_rec_output(age)
    another_rec(age)

main_module()

(I also added a small check in is_year_valid() to ensure the birth year is a reasonable 4-digit number—this makes your input validation even better, which fits your homework requirements!)

Why This Works

Now age is explicitly passed from main_module() to another_rec(), so the function knows exactly what value to use. The case-insensitive input makes the program more user-friendly, and all your modular functions still do their separate jobs perfectly, meeting your homework's requirements.

内容的提问来源于stack exchange,提问作者Lindsay C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:46:21