if语句是用来进行判断的,其使用格式如下:
if 条件成立:
执行
举例:
age = 30
if age>=18:
print "我已经成年了"
if 条件:
满足条件时要做的事情
else:
不满足条件时要做的事情
举例:
age = 17
if age <= 18:
print("我是小可爱")
else:
print("永远18岁")
if xxx1:
事情1
elif xxx2:
事情2
elif xxx3:
事情3
举例:
score = 77
if score >= 90 and score <= 100:
print('本次考试,等级为A')
elif score >= 80 and score < 90:
print('本次考试,等级为B')
elif score >= 70 and score < 80:
print('本次考试,等级为C')
elif score >= 60 and score < 70:
print('本次考试,等级为D')
elif score >= 0 and score < 60:
print('本次考试,等级为E')
这个关键词我们称之为“断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛出AssertionError的异常。
在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。
assert 3 > 7
# AssertionError
举例:
i = 1
while i <= 5:
j = 1
while j <= i:
print("*", end='')
j += 1
print("")
i += 1
k = 5
while k <= 5:
a = 1
while a <= k:
print("*", end='')
a += 1
print("")
if k == 0:
break
k -= 1
# 执行结果
*
**
***
****
*****
*****
****
***
**
*
count = 0
while count < 5:
print("%d is less than 5" % count)
count = count + 1
else:
print("%d is not less than 5" % count)
# 0 is less than 5
# 1 is less than 5
# 2 is less than 5
# 3 is less than 5
# 4 is less than 5
# 5 is not less than 5
for 迭代变量 in 可迭代对象:
代码块
range() 函数
range([start,] stop[, step=1]) # 从start参数的值开始到stop参数的值结束的数字序列,该序列包含start的值但不包含stop的值。
for i in range(10):
print("---%d---" % i)
# 执行结果:
# ---0---
# ---1---
# ---2---
# ---3---
# ---4---
# ---5---
# ---6---
# ---7---
# ---8---
# ---9---
for j in range(10):
if j == 5:
break
print("***%d***" % j)
print("_____________________________")
for k in range(10):
if k == 5:
continue
print("^^^%d^^^" % k)
# 执行结果:
# ***0***
# ***1***
# ***2***
# ***3***
# ***4***
# _____________________________
# ^^^0^^^
# ^^^1^^^
# ^^^2^^^
# ^^^3^^^
# ^^^4^^^
# ^^^6^^^
# ^^^7^^^
# ^^^8^^^
# ^^^9^^^
[ expr for value in collection [if condition] ]
( expr for value in collection [if condition] )
{ key_expr: value_expr for value in collection [if condition] }
{ expr for value in collection [if condition] }