與布爾值(特別是返回布爾值的表達式)有關的有趣之處在於,我們可以根據它們的不同來做出決定並走不同的道路True
或者False
價值。
在Python我們使用if
陳述:
condition = True
if condition == True:
# do something
條件測試解決時True
,就像上述情況一樣,其代碼塊將被執行。
什麼是街區?塊是在右邊縮進一個級別(通常為4個空格)的部分:
condition = True
if condition == True:
print(“The condition”)
print(“was true”)
該塊可以由單行或多行組成,並在您移回到上一個縮進級別時結束:
condition = True
if condition == True:
print(“The condition”)
print(“was true”)
print(“Outside of the if”)
與結合if
你可以有一個else
塊,如果條件測試if
結果到False
:
condition = True
if condition == True:
print(“The condition”)
print(“was True”)
else:
print(“The condition”)
print(“was False”)
和你可以有不同的聯繫if
與檢查elif
,如果先前的檢查是False
:
condition = True
name = "Roger"
if condition == True:
print(“The condition”)
print(“was True”)
elif name == “Roger”:
print(“Hello Roger”)
else:
print(“The condition”)
print(“was False”)
在這種情況下,如果condition
是False
和name
變量值為“ Roger”。
在一個if
聲明你只能擁有一個if
和else
檢查,但有多個系列elif
檢查:
condition = True
name = "Roger"
if condition == True:
print(“The condition”)
print(“was True”)
elif name == “Roger”:
print(“Hello Roger”)
elif name == “Syd”:
print(“Hello Syd”)
elif name == “Flavio”:
print(“Hello Flavio”)
else:
print(“The condition”)
print(“was False”)
if
和else
也可以以內聯格式使用,這使我們可以根據條件返回一個值或另一個值。
例子:
a = 2
result = 2 if a == 0 else 3
print(result) # 3
更多python教程:
- Python簡介
- 在macOS上安裝Python 3
- 運行Python程序
- Python 2和Python 3
- 使用Python的基礎
- Python數據類型
- Python運算子
- Python字符串
- Python布爾值
- Python數字
- Python,接受輸入
- Python控制語句
- Python列表
- Python元組
- Python集
- Python字典
- Python函數
- Python對象
- Python循環
- Python模塊
- Python類
- Python標準庫
- 調試Python
- Python變量範圍
- Python,從命令行接受參數
- Python遞歸
- Python嵌套函數
- Python Lambda函數
- Python閉包
- Python虛擬環境
- 使用Python將GoPro用作遠程網絡攝像頭
- Python,如何從字符串創建列表
- Python裝飾器
- Python Docstrings
- Python自省
- Python註釋
- Python,如何列出目錄中的文件和文件夾
- Python,如何檢查數字是否為奇數或偶數
- Python,如何獲取文件的詳細信息
- Python,如何檢查文件或目錄是否存在
- Python異常
- Python,如何創建目錄
- Python,如何創建一個空文件
- Python,`with`語句
- Python,創建網絡請求
- Python,使用`pip`安裝第三方軟件包
- Python,讀取文件內容