[英]python nested conditionals homework
我正在用python学习条件语句,被困在一个很简单的练习中,但我做对了。 我希望有人能指出我做错了什么。
我需要编写一个将打印"You may see that movie!"
或"You may not see that movie!"
根据以下标准。 但是,不允许在此代码的任何地方使用and
运算符。
我的代码:
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"
注意,所有的elif
和else
都与第一个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.