专业编程基础技术教程

网站首页 > 基础教程 正文

七爪源码:条件语句—if、if elif 和 if elif else

ccvgpt 2024-11-20 13:03:03 基础教程 6 ℃

大家好,今天我们将讨论Python中的if、if elif和if elif else条件语句,并尝试了解不同的用例和编写相同条件语句的不同方式。

if, if elif, and if elif else is 到底是什么鬼?

七爪源码:条件语句—if、if elif 和 if elif else

在 Python 中,要根据满足某些条件来执行语句,我们使用 if 语句。

让我们看几个例子:-

示例 1:-

going_to_office = True #variable that stores the boolean value
if going_to_office == True: print("Work from office")

这里不用检查 going_to_office 的值是否为 True,我们可以直接写成

if going_to_office: print("Work from office")

因此,如果条件被评估为 True 则 print 语句将被执行,否则不执行。

示例 2:-

让我们说我们有

going_to_office = True
if going_to_office: 
     print("Work from office")
else:
     print("Enjoy work from home")

因此,如果不满足第 1 行的条件,则控制移至 else 并执行 else 条件下的语句。

示例 3:-

假设我们有 if elif else 条件

going_to_office = False
be_at_home = True
if going_to_office: #condition1
 print(“Work from office”)
elif be_at_home: #condition2
 print(“Enjoy work from home”)
else:
 print(“Work from Starbucks”)

所以如果条件1和条件2不满足,则执行else条件下的语句。


结论

if、if elif 和 if elif else 等基本条件语句很容易理解,所以请告诉我您对本文的看法。

在此先感谢您阅读本文……

关注七爪网,获取更多APP/小程序/网站源码资源!

最近发表
标签列表