循环语句
‘’’
在我们编程过程中,需要遍历各种数据,例如遍历字符串,列表,集合,字典,元组等等类型,
这时候常常需要用到循环语句进行处理。
python 循环语句主要有for,while 两种表达方式
‘’’
for循环
‘’’
for variable in iter_object
test_module
variable:为 自定义一个临时变量
iter_object:为一个可迭代的对象
test_module:为程序的处理模块
‘’’
print('console'.center(50,'-'))
#遍历列表
x = [1,2,3,4]
for x_index in x:
print(x_index)
print('*'*20)
#遍历字符串
x = 'hello,world'
for y_index in x:
print(y_index)
print('*'*20)
#遍历字典
x = {'name':'xu','age':18}
for x,y in x.items():
print(x,y)
print('*'*20)
#1+2+3+...+100的方法
#使用range 生成一个1到100的序列
sum = 0
for rax in range(1,101):
sum+=rax
print(sum)
---------------------console----------------------
1
2
3
4
********************
h
e
l
l
o
,
w
o
r
l
d
********************
name xu
age 18
********************
5050
while 循环
‘’’
while循环是python循环的另一种方式
格式为:
while condition:
test_module
condition: 为条件控制
test_module: 循环的运行模块
‘’’
#无限循环
print('console'.center(50,'-'))
while True: #档条件为真的时候,则会一致执行下方空格缩进的语句
print('无限循环')
---------------------console----------------------
无限循环
无限循环
无限循环
...
#1+2+3+...+100的方法
print('console'.center(50,'-'))
x = 1
sum = 0
while x<=100: #当满足条件则会执行while里面的代码,条件不满足则会跳出循环,往下执行
sum+=x
x+=1
print(sum)
---------------------console----------------------
5050
break语句
‘’’
break 语句常常运用在循环语句过程中与条件控制语句相结合进行使用
执行break 语句则会跳出整个循环语句
‘’’
print('console'.center(50,'-'))
for ins in range(1,10):
if ins==5: #当满足条件则会执行break语句,该break后面的代码则不会执行,跳出整个循环代码
print('我准备跳出循环咯')
break
print(ins)
print('我跳出了循环咯')
---------------------console----------------------
1
2
3
4
我准备跳出循环咯
我跳出了循环咯
-------------
continue语句
‘’’
continue语句 语句常常运用在循环语句过程中与条件控制语句相结合进行使用
continue语句 语句则会跳出当前循环,但是不会跳出整个循环
‘’’
print('console'.center(50,'-'))
for ins in range(1,10):
if ins==5: #当满足条件则会执行continue语句,该continue后面的代码则不会执行,继续下一次新的循环
print('我准备跳出当前循环咯')
continue
print(ins)
print('我跳出了循环咯') #循环完成以后进行执行
---------------------console----------------------
1
2
3
4
我准备跳出当前循环咯
6
7
8
9
我跳出了循环咯