条件控制
if语句
格式:
if 表达式:
语句1
else:
语句2
逻辑:当程序执行到if 语句时,首先计算表达式的值,如果表达式的值为真,那么执行语句1,否则执行语句2
a=1
if a==1:
print(1)
else:
print(2)
if-elseif-else语句
if 表达式1:
语句1
elseif 表达式2
语句2
elseif 表达式3
语句3
else #可以有,也可以没有
语句e
if age<0:
print("娘胎里")
elseif age>0 and age<3:
print("婴儿")
while 表达式
while 表达式:
语句1
else
语句2
逻辑:在条件语句(表达式)为False,执行else中的语句2,否则继续执行表达式,知道表达式为False,然后退出
循环
for循环
for 变量名 in 集合:
语句
逻辑:按照顺序取出集合中的每个元素赋值给变量,再去执行语句。那么如此循环往复,直到取完集合中的元素截止
for i in range(10):
print(i)
range([start,]end[,step])函数,列表生成器,start可选,默认0,step默认1
同时便利下标、元素
for index, m in enumerate(range(10)):
print(index,m)
循环中的while
while 语句
while 表达式:
语句
逻辑:当程序执行到while语句的时候没首先计算表示的值,如果表达式的值为加,结束循环,否则执行语句,再去计算表达式 ……知道表达式的值为假,才停止
问题:计算1+2+……+100=?
i=1
sum=0
while i<=100:
i=i+1
sum=sum+i
print(sum)
break语句,结束循环语句,在执行语句之后,写break,就会跳出循环
while 表达式:
语句
break
continue语句,跳过当前循环中的剩余语句,然后继续下一次循环
e.g,
for i in range(10):
print(i)
if i==3:
continue
print("*")
问题:
打印99乘法表?
随机生成一个6位数的验证码?