cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# Audi
# BMW
# Subaru
# Toyota
每条
if
语句的核心都是一个值为True
或False
的表达式,这种表达式被称为条件测试。如果值为True
才会执行紧跟的代码,否则不执行。
car = "bmw"
print(car == "bmw")
# True
print(car == "audi")
# False
car = "BMW"
print(car == "bmw")
# False
# 转化为小写再进行比较。
print(car.lower() == "bmw")
# True
car = "bmw"
print(car != "bmw")
# False
num = 1
# 等于。
print(num == 1)
# True
# 不等于。
print(num != 1)
# False
# 大于。
print(num > 0)
# True
# 大于等于。
print(num >= 0)
# True
# 小于、小于等于同理。
num = 1
# 1.and :同时满足。
print(num > 0 and num < 1)
# False
# 2.or :满足其一。
print(num > 0 or num < 1)
# True
nums = [1, 3, 5]
print(3 in nums)
# True
nums = [1, 3, 5]
print(1 not in nums)
# False
flag = True
print(flag == False)
# False
import random
# 测试三轮。
for i in range(0, 3):
# 取 1 ~ 15 随机数作为判断条件。
month = random.randint(1, 15)
if 3 <= month <= 5:
print(month, "in spring")
elif 6 <= month <= 8:
print(month, "in summer")
elif 9 <= month <= 11:
print(month, "in autumn")
elif month == 12 or month <= 2:
print(month, "in winter")
else:
print(month, "is invalid!")
# 11 in autumn
# 7 in summer
# 15 is invalid!
students = []
# 不为空则遍历元素,否则提示。
if students:
for student in students:
print(student)
else:
print("students is null.")
# students is null.
database = [1, 2, 3]
requests = [0, 1, 5]
for req in requests:
if req in database:
print(req, "in database.")
else:
print(req, "not in database.")
# 0 not in database.
# 1 in database.
# 5 not in database.
“-------怕什么真理无穷,进一寸有一寸的欢喜。”
微信公众号搜索:饺子泡牛奶。