Сначала определите, каков рейтинг фильма:
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"
Обратите внимание, что все elif
s и else
выровнены с первым 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. Каждый уровень отступа определяет блок кода и, следовательно, определяет, какие блоки находятся под какими блоками (то есть вложенными блоками). Здесь - это краткое руководство, объясняющее это.