if
语句可以根据条件采取一定的措施,每条if
语句的核心都是一个值为True
或False
的表达式,称为条件测试,Python
根据条件测试的值为True
还是False
来决定是否执行if
语句中的代码,即为True
时执行if
语句后面的代码,为Flase
则忽略。
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)
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.")
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!")