繁体   English   中英

python嵌套条件作业

[英]python nested conditionals homework

我正在用python学习条件语句,被困在一个很简单的练习中,但我做对了。 我希望有人能指出我做错了什么。

我需要编写一个将打印"You may see that movie!" "You may not see that movie!" 根据以下标准。 但是,不允许在此代码的任何地方使用and运算符。

  • 任何孩子都可以看G级电影。
  • 要观看PG级电影,您的孩子必须年满8岁。
  • 要观看PG-13分级的电影,您的孩子必须年满13岁。
  • 要观看R级电影,您的孩子必须年满17岁。
  • 您的孩子可能永远不会看过NC-17电影。

我的代码:

if rating == "G":
    print("You may see that movie!")

elif rating == "PG":
    if age >= 8:
        print("You may see that movie!") 

    elif rating == "PG-13":
        if age >= 13:
            print("You may see that movie!") 

        elif rating == "R":
            if age >= 17:
                print("You may see that movie!")        
        else:
            print("You may not see that movie!")    

首先确定电影的等级是:

if rating == "G":
    # the movie has a rating of "G"
    # check age conditions for a movie with rating of "G"

elif rating == "PG":
    # the movie has a rating of "PG"
    # check age conditions for a movie with rating of "PG"

elif rating == "PG-13":
    # the movie has a rating of "PG-13"
    # check age conditions for a movie with rating of "PG-13"

elif rating == "R":
    # the movie has a rating of "R"
    # check age conditions for a movie with rating of "R"

else:
    # the movie has a rating of "NC-17"
    # check age conditions for a movie with rating of "NC-17"

注意,所有的elifelse都与第一个if和not缩进对齐,因为它们都属于if (即它们在同一代码块中)。 这意味着从上到下检查条件,直到其中一个条件成立(并且不再检查下面的其他条件)。 然后执行低于该条件的所有缩进代码(即代码块)。 如果没有条件成立,则执行else块中的代码。

现在,我们只需要填充每个那些if/elif/else与块if/else块来检查年龄限制:

if rating == "G":
    # there is no condition to see a "G" rated movie
    print("You may see that movie!") 

elif rating == "PG":
    # you must be 8 years or older to see a "PG" rated movie
    if age >= 8:
        print("You may see that movie!")
    else:
        print("You may not see that movie!")

elif rating == "PG-13":
    # you must be 13 years or older to see a "PG-13" rated movie
    if age >= 13:
        print("You may see that movie!")
    else:
        print("You may not see that movie!")

elif rating == "R":
    # you must be 17 years or older to see a "R" rated movie
    if age >= 17:
        print("You may see that movie!")
    else:
        print("You may not see that movie!")

else:
    # it is a "NC-17" rated movie; you are not allowed to see this movie at all
    print("You may not see that movie!")

不要忘记缩进在Python中非常重要。 每个缩进级别定义一个代码块,并因此确定哪些块位于哪些块下(即嵌套块)。 是一个简短的教程,对此进行了说明。

为了简化今天的答案,您可以使用字典:

min_ages = {
    'G': 0,
    'PG': 8,
    'PG-13': 13,
    'R': 17,    
}

min_age = min_ages.get(rating)
if min_age is None:
    # it is a "NC-17" rated movie; you are not allowed to see this movie at all
    print("You may not see that movie!")
else:
    if age >= min_age:
        print("You may see that movie!")
    else:
        print("You may not see that movie!")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM