本章主要讲while循环和for循环
循环:在满足特定条件的情况下,重复执行某段代码
while循环
例:
1.打印1-10
num = 1
while num < 11:
print(num)
num += 1
'''在该段代码中,先给变量num赋予初值1,然后进行判断 发现1<11,所以执行print,
将1打印出来,再将num+1---->num=2,在进行判断 2<11,所以继续打印2,然后num再加1,直至num=10,
发现10<11打印10,num+1--->num=11,11不小于11,所以退出循环
'''
打印结果:
2.猜数字游戏
#先给定一个目标数字
answer = 10
#input输出的数据类型是字符串,因此要转换一下数据leixing
num = int(input("请输入你要的猜的数字:"))
#一直循环,直至猜对
while True:
if answer == num:
print("恭喜你,猜对了")
break #终止循环,
else:
print("抱歉,猜测错误,重新输入")
num = int(input("请输入你要的猜的数字:")) #重新猜数字
3.计算1–99数字和
#先给定一个目标数字
num = 1
result = 0
while num <100:
result += num
num += 1
print(result) #注意此处的print前没有空格
打印结果
#先给定一个目标数字
num = 1
result = 0
while num <100:
result += num
num += 1
print(result) #注意此处的print前有空格,与上边代码可做一个比较
打印结果:
1
3
6
…
4851
4950
4.九九乘法表(while版本)
row = 1
column = 1
#第一个while控制行
while row <= 9:
#第二个while控制列row
while column <= row:
result = column * row
# 此处打印的是同一行中的列
# 因此不需要换行,所以修改end=' ',让其在一行中显示
print("%d*%d=%d"%(column,row,result),end=' ')
column += 1
row += 1
column = 1
#此处,是为了使用换行符
#打印完一行以后,就要换行
print('')
'''若想看看效果,可以试着将print('')和end=' '去掉'''
上述代码中end的作用:(print自带换行)
print('1*1=1')
print('1*2=2')
打印结果:
1*1=1
1*2=2
print('1*1=1',end=' ')
print('1*2=2')
打印结果:
1*1=1 1*2=2
break语句
跳出整个循环
num = 1
while num <= 10:
if num == 5:
break
print(num)
num += 1
打印结果:
1
2
3
4
continue语句
跳出当前这次循环
num = 1
while num <= 10:
if num == 5:
num += 1 #因为此处如果不加1,后边num一直等于5
continue
print(num)
num += 1
打印结果:
1
2
3
4
6
7
8
9
10
小案例:打印1–100以内所有偶数:
num = 1
while num <= 100:
if num % 2 == 1: # % 取余运算符
num += 1
continue
print(num)
num += 1
for循环:
for循环可以遍历任何序列的对象(列表、字典、元组、字符串等,后续会讲到)
1.示例:
learn = "hello world"
for i in learn:
print(i)
打印结果:
h
e
l
l
o
w
o
r
l
d
2.计算1到99的和
num = range(1,100) #range函数代表从开头数字到末尾数字-1
result = 0
for i in num:
result += i
print(result)
打印结果:
4950
3.统计“python will play an important role in the future”中p出现的次数
index = "python will play an important role in the future"
num = 0 #统计p出现的次数
for i in index:
if i == 'p':
num += 1
else:
continue
print(num)
打印结果:
3
4.用for循环打印九九乘法表
for row in range(1,10):
for column in range(1,row+1):
result = column * row
print("%d*%d=%d"%(column,row,result),end=' ')
column = 1
print('')