Python基础语言入门之循环语句

Python基础语言入门之循环语句

Python有两种循环语句:
1.for循环:
for循环必须有一个可迭代的对象,才能循环;
for循环可以遍历任何序列的项目
2.while循环
while循环先给定一个判断条件,判断条件为true时执行循环体,判断条件为false时循环结束
3.控制循环语句
break语句:
在语句执行过程中终止循环,并跳出整个循环
continue语句:
在语句执行过程中终止该次循环,并开始下一次循环
pass语句:
pass是空语句,是为了保持程序结构的完整性。


1.1.for循环结构
for循环的语法格式如下:
for iterating_var in sequence:
statements(s)

for i in range(5):
    print('hello')
>>>
hello
hello
hello
hello
hello

1.2.for-else,逻辑和if-else一样
for 中的语句正常执行,else 中的语句会在循环正常执行完的情况下执行

for n in range(10,20):
    for i in range(2,n):
        if n%i == 0:
            j = n/i
            print('%d等于%d*%d'%(n,i,j))
    else:
        print(n)
>>>
10等于2*5
10等于5*2
10
11
12等于2*6
12等于3*4
12等于4*3
12等于6*2
12
13
14等于2*7
14等于7*2
14
15等于3*5
15等于5*3
15
16等于2*8
16等于4*4
16等于8*2
16
17
18等于2*9
18等于3*6
18等于6*3
18等于9*2
18
19

2.1.while循环结构
while 判断条件:
执行语句……

count = 0
while count < 6:
    print('the count is:{}'.format(count))
    count += 1
print('end')
>>>
the count is:0
the count is:1
the count is:2
the count is:3
the count is:4
the count is:5
end

2.2.while-else,逻辑和if-else一样

count = 0
while count < 2:
    print('count小于5')
    count += 1
else:
    print('count大于等于5')
>>>
count小于5
count小于5
count大于等于5

3.1.break语句
终止所有,跳出循环

s = 0
n = 0
for i in range(10):
    for j in range(5):
        s = s + (i*j)
        n += 1
        print('第%i次运算'%n)
        if s > 20:
            break
print(s)
>>>
第1次运算
第2次运算
第3次运算
第4次运算
第5次运算
第6次运算
第7次运算
第8次运算
第9次运算
第10次运算
第11次运算
第12次运算
第13次运算
第14次运算
第15次运算
第16次运算
第17次运算
第18次运算
第19次运算
第20次运算
第21次运算
22

3.2.continue语句
终止本次,开始下次循环

n = 0
while n<20:
    if n == 5:
        n = 15
        continue
    print('n等于%i' % n)
    n += 1
>>>
n等于0
n等于1
n等于2
n等于3
n等于4
n等于15
n等于16
n等于17
n等于18
n等于19

3.3.pass语句
不中断也不跳过

for letter in 'python':
    if letter == 'h':
        print('当前字母是h,但是执行了pass')
        continue
    print('当前字母:',letter)
print('Goodbye')
>>>
当前字母: p
当前字母: y
当前字母: t
当前字母是h,但是执行了pass
当前字母: o
当前字母: n
Goodbye

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值