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

2025-10-27 10:30:09

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语句详解

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢