python嵌套条件作业

时间:2018-07-01 20:48:55

标签: python python-3.x if-statement

我正在用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!")    

2 个答案:

答案 0 :(得分:1)

首先确定电影的等级是

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对齐,并且没有缩进,因为它们都属于该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中非常重要。每个缩进级别定义一个代码块,因此确定哪些块在哪些块下(即嵌套块)。 Here是一个简短的教程,对此进行了说明。

答案 1 :(得分:0)

为简化今天的回答,您可以使用词典:

npx