Python - if 條件控制


注意

本篇圖片素材都來自慕課網,因為素材過於優秀,直接拿過來了,加水印只是為了防止整篇文章被搬

 

前言

程序並非是一成不變的向下執行,有的時候也要根據條件的不同選擇不一樣的代碼,這個時候便用到了分支結構

 

最簡單的分支結構

對條件進行判斷:

  • 如果條件為真,執行“條件為真的分支”
  • 如果條件為假,執行“條件為假的分支”

 

if ... else ... 語句

Python 提供了 if 條件控制語句用於選擇執行流程

if 條件:
    條件為真的分支
else:
    條件為假的分支

 

可以選擇不帶 else 分支

if 條件:
    條件為真的分支

 

代碼栗子一

# 栗子一
if 2 > 1:
    print('2 > 1 is true')
else:
    print('2 > 1 is false')


# 輸出結果
2 > 1 is true

 

代碼栗子二

# 栗子二
lis = [1, 2, 3, 4]
if len(lis) > 5:
    print('列表長度大於 5')
else:
    print('列表長度小於 5')


# 輸出結果
列表長度小於 5

 

代碼栗子三

if 1 == 1:
    print('1 == 1 is true')


# 輸出結果
1 == 1 is true

 

多分支選擇結構

對多個條件進行判斷:

  • 如果條件 1 為真,則執行代碼塊 1
  • 如果條件 2 為真,則執行代碼塊 2
  • 如果條件 3 為真,則執行代碼塊 3
  • 如果以上條件都不滿足,則執行代碼塊 4

 

if ... elif .. elif .. else .. 語句

if 條件 1:
    代碼塊 1
elif 條件 2:
    代碼塊 2
elif 條件 3:
    代碼塊 3
else:
    代碼塊 4

 

不帶 else 分支

if 條件 1:
    代碼塊 1
elif 條件 2:
    代碼塊 2
elif 條件 3:
    代碼塊 3

 

代碼栗子

# 栗子一
from random import randint

res = randint(0, 4)
if res == 0:
    print('num is 0', res)
elif res == 1:
    print('num is 1', res)
elif res == 2:
    print('num is 2', res)
elif res == 3:
    print('num is 3', res)
else:
    print('num is 4', res)


# 輸出結果
num is 2 2

randint 是返回隨機整數

 

分支嵌套結構

程序首先判斷條件 1 是否為真

如果條件 1 為真,則判斷條件 2 是否為真

  • 條件 1 為真並且條件 2 為真,執行代碼塊 1
  • 條件 1 為真並且條件 2 為假,執行代碼塊 2

如果條件 1 為假,則判斷條件 3 是否為真

  • 條件 1 為假並且條件 3 為真,執行代碼塊 3
  • 條件 1 為假並且條件 3 為假,執行代碼塊 4

 

代碼栗子

# 分支嵌套結構
from random import randint

res1 = randint(0, 1)
res2 = randint(0, 1)
if res1 == 0:
    if res2 != 0:
        print("0,1")
    else:
        print("0,0")
else:
    if res2 > 0:
        print("1,1")
    else:
        print("1,0")


# 輸出結果
1,0

 

擴展:random 模塊詳解

https://www.cnblogs.com/poloyy/p/14845553.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM