1. 程式人生 > 其它 >Python基礎之if

Python基礎之if

技術標籤:Python_Basepython

簡介

if語句可以根據條件採取一定的措施,每條if語句的核心都是一個值為TrueFalse的表示式,稱為條件測試,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!")
- End -
一個努力中的公眾號
關注一下吧