Python基础之if

简介

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 -
一个努力中的公众号
关注一下吧

你可能感兴趣的:(Python_Base,python)