Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the differences between if and elif in python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the difference between if and elif in python. The introduction in the article is very detailed and has certain reference value. Interested friends must read it!

Example 1: a = 5 if a < 6: #Condition 1 print(1)if a < 7: Condition 2 print(2)else: print(3)

Condition 1 and condition 2 are independent, the value of a is judged to be less than 6 in the first time, so the number 1 is printed, and the value of a is judged to be less than 7 in the second time, so 2 is printed. If all if statements fail, the statements after else will be executed, otherwise the else statement will not be executed.

If condition 2 were changed to elif, the result would be different.

Example 2 a = 5 if a < 6: #Condition 1 print(1)elif a < 7: Condition 2 print(2)else: print(3)

This time condition 1 and condition 2 are related, that is, if condition 1 succeeds, condition 2 will not continue to judge. Conversely, if condition 1 fails, then condition 2 continues to be judged. If both condition 1 and condition 2 fail, then the statement in else is executed.

The result of Example 2 is obviously that only 1 will be printed.

Of course, it is also possible to mix if and elif, but it looks strange and readable.

Example 3 a = 5if a < 6: print(1)elif a < 4: print(2)if a < 7: print(3)else: print(4)

The result is: 1, 3

Application scenarios:

If you only want to execute one block of code, use the if-elif-else structure.

If you want to run multiple blocks of code, use multiple ifs. (Multiple conditions met simultaneously)

What is the difference between if and elif in python? Thank you for reading all the contents of this article! Hope to share the content to help everyone, more relevant knowledge, welcome to pay attention to the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report