简单的Python程序循环错误

时间:2018-05-14 21:23:52

标签: python python-3.x loops

任何人都可以帮我看看这里出了什么问题吗?我最后收到一个错误:“NameError:name'age'未定义”。我刚刚进入Python和编程,并没有看到要修改它的内容。

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)
        is_valid = True
    except ValueError:
        is_valid = False
    return is_valid


def calculate_age(birth_year):
    age = 0
    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():
    second_rec = ""
    second_rec = (input("Would you like another recommendation Y/N: "))
    while second_rec == str("Y"):
        show_rec_output(age)
        second_rec = (input("Would you like another recommendation? Y/N: "))
    else:
        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()

main_module()

我正在尝试完成的任务需要一个输入,一个输出,两个循环,输入验证以及模块中的所有内容。

1 个答案:

答案 0 :(得分:1)

问题在于:

def another_rec():
    second_rec = ""
    second_rec = (input("Would you like another recommendation Y/N: "))
    while second_rec == str("Y"):
        show_rec_output(age)

你在这里没有age,但无论如何你都试图使用它。

要解决此问题,您希望使用与show_rec_output完全相同的操作。首先,在age函数中添加another_rec参数:

def another_rec(age):

...然后,传递main_module

中的值
show_rec_output(age)
another_rec(age)