条件语句
If 语句:是一种条件语句,根据条件为 true 还是 false 运行或执行相关代码
if phone_balance < 5: phone_balance += 10 bank_balance -= 10
If、Elif、Else:
if season == 'spring': print('plant the garden!') elif season == 'summer': print('water the garden!') elif season == 'fall': print('harvest the garden!') elif season == 'winter': print('stay indoors!') else: print('unrecognized season')
说明:
if
:if 语句必须始终以 if 条件开始,其中包含第一个要检查的条件。如果该条件为 True,Python 将运行这个 if 块中的缩进代码,然后跳到 if 语句之后的剩余代码。elif
:elif 条件用来检查其他条件(前提是 if 语句中之前的条件结果为 False)。可以从示例中看出,可以使用多个 elif 块处理不同的情形。else
:最后是 else 条件,它必须位于 if 语句的末尾。该条件语句不需要条件。如果 if 语句中所有前面的语句结果都为 False 时,将运行 else 块中的代码。
缩进:在 Python 中,我们使用缩进来封装代码块,缩进通常是四个空格一组。请严格遵守该惯例,因为更改缩进会完全更改代码的含义。
条件语句[相关练习]
请编写一个 if 语句,使竞争者能够根据自己的得分知道获得了哪个奖品,得分存储在整型变量 points 中。
得分 奖励 Prize in English 1 - 50 木质兔子玩偶 wooden rabbit 51 - 150 没有奖品 no prize 151 - 180 极薄薄荷 wafer-thin mint 181 - 200 企鹅 penguin 所有的上下限都包含在内,points 只能是正整数,最大值为 200。
在你的 if 语句中,将 result 变量赋给一个根据 points 的值存储相应消息的字符串。如果赢得了奖品,消息内容应该是 “Congratulations! You won a [prize name]!”,“prize name”应替换成相应的奖品。如果没有赢得奖品,消息内容应该是 “Oh dear, no prize this time.”
points = 174 # use this input to make your submission # write your if statement here if points >= 1 and points <= 50: result = "Congratulations! You won a wooden rabbit!" elif points >= 51 and points <= 150: result = "Oh dear, no prize this time." elif points >= 151 and points <= 180: result = "Congratulations! You won a wafer-thin mint!" elif points >= 181 and points <= 200: result = "Congratulations! You won a penguin!" print(result)