python中if-else语句及if-elif-else语句详解

 时间:2026-02-15 16:34:49

1、简单的if语句只有一个测试条件和一个操作。代码示例如下:

age = 18

if age >= 18:

    print("You are an adult now.")

python中if-else语句及if-elif-else语句详解

1、if-else语句适用于只有两种情况的条件测试,当条件测试通过时执行一个操作,不通过时执行另外一个操作。代码示例如下:

age = 16

if age >= 18:

    print("You are an adult now.")

else:

    print("You will be an adult in " + str(18-age) + " years.")

python中if-else语句及if-elif-else语句详解

1、if--elif-else语句适用于有3种情况的条件测试,依次判断每个条件测试是否通过,直到遇到通过了的条件测试。这个语句执行有先后顺序,而且当一个条件被满足时,接下来的条件测试会跳过,不再进行判断。代码示例如下:

age = 8

if age < 5:

    price = 0

elif age < 18:

    price = 10

else:

    price = 20

print("The ticket price for you is "+ str(price) + ".")

python中if-else语句及if-elif-else语句详解

1、if-elif-elif-else的语句类似if-elif-else的语句,不过是增加了判断条件。代码示例如下:

age = 68

if age < 5:

    price = 0

elif age < 18:

    price = 10

elif age > 65:

    price = 0

else:

    price = 20

print("The ticket price for you is "+ str(price) + ".")

python中if-else语句及if-elif-else语句详解

2、if-elif-elif-elif的语句类似if-elif-else的语句,不过是将最后一个else改成了elif,功能相同,只是阅读起来可能更容易理解。代码示例如下:

age = 68

if age < 5:

    price = 0

elif age < 18:

    price = 10

elif age < 65:

    price = 20

elif age >= 65:

    price = 0

print("The ticket price for you is "+ str(price) + ".")

python中if-else语句及if-elif-else语句详解

1、只有一个if的语句中,各个测试条件中只有一个条件满足要求。而在多个if的语句中,每个if语句的关系是并列的,不会受到其它if语句的影响。代码示例如下:

fruits = ["apple","peach","banana","orange"]

if "apple" in fruits:

    print("She would like to eat some apples.")

if "banana" in fruits:

    print("She would like to eat some bananas.")

if "strawberry" not in fruits:

    print("She doesn't want any strawberry.")

print("That's all she want.")

python中if-else语句及if-elif-else语句详解

  • python输入两个整数,输出两个整数的和
  • jieba库安装步骤
  • 二重积分极坐标r的范围怎么确定?
  • 间断点的分类及判断方法
  • 字符串的长度怎么看
  • 热门搜索
    长春旅游网 宜昌旅游景点大全 北京市旅游局官网 白云山旅游 浙江有哪些旅游景点 旅游广告语 大鹿岛旅游 热门旅游城市 牛背山旅游攻略 连云港 旅游