Python基礎之if
阿新 • • 發佈:2021-01-08
技術標籤:Python_Basepython
簡介
if
語句可以根據條件採取一定的措施,每條if
語句的核心都是一個值為True
或False
的表示式,稱為條件測試,Python
根據條件測試的值為True
還是False
來決定是否執行if
語句中的程式碼,即為True
時執行if
語句後面的程式碼,為Flase
則忽略。
if
languages = ['java', 'c', 'python'] for language in languages: if language == 'java': print(language.upper()) else: print(language.title())
條件測試
# 檢查是否相等 ## python中檢查是否相等區分大小寫 language = 'java' if language == 'java': print("language == 'java'") # 檢查是否相等 language = 'java' print(language == 'java') # 檢查是否不相等 language = 'java' if language != 'python': print('It is false') # 檢查數字 age = 18 print(age == 18) # 檢查多個條件(and) age_0 = 22 age_1 = 18 print(age_0 >= 22 and age_1 >= 18) print(age_0 >= 23 and age_1 >= 18) # 檢查多個條件(or) age_0 = 22 age_1 = 18 print(age_0 >= 22 or age_1 >= 19) print(age_0 >= 23 or age_1 >= 19) # 檢查特定值是否包含在列表中 languages = ['java', 'c', 'python'] print('java' in languages) print('python' in languages)
if-elif-if結構
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
省略else程式碼塊
age = 18 if age < 4: print("Your admission cost is $0.") elif age < 18: print("Your admission cost is $5.") elif age >= 18: print("Your admission cost is $10.")
判斷列表是否為空
languages = []
if languages:
print("languages is not empty!")
else:
print("languages is empty!")