Python基础知识(三)

For循环

01、For循环

  • For循环是迭代对象元素的常用方法 。
  • 代码块:使用缩进,块内的行必须通过制表符缩进,或相对于周围的命令缩进4个空格。
# 迭代列表
for number in [23, 41, 12, 16, 7]: 
    print(number)
'''
23
41
12
16
7
'''    

02、枚举

  • 返回一个元组,其中包含每次迭代的计数(从默认为0开始)和迭代序列获得的值
# 迭代列表
lists = ['steve', 'rachel', 'michael', 'adam', 'monica']
for index, list in enumerate(lists):
    print(index,list)
'''
0 steve
1 rachel
2 michael
3 adam
4 monica
'''

03、Continue

  • continue语句将转到循环的下一次迭代
  • continue语句用于忽略某些值,但不会中断循环
  • continue的使用在下面的示例中

04、Break

  • break语句将完全打断循环
# 申明一个列表
cleaned_list = []
# 定义文本字符串
x = "This is a example break, look quickly!"
# 用空格替换标点符号
for char in ',!' :
    x = x.replace(char,' ')
for word in x.split(' '):
    if word == 'look':
        break
    cleaned_list.append(word)
print(cleaned_list)
# ['This', 'is', 'a', 'example', 'break', '']    

05、示例

  • 从文本中删除标点符号并将最终结果转换为列表
# 字符串的声明
text = '''On a dark desert highway, cool wind in my hair Warm smell of colitas, rising up through the air Up ahead in the distance, I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway; I heard the mission bell And I was thinking to myself, "This could be Heaven or this could be Hell" Then she lit up a candle and she showed me the way'''
# 将文本中的标点符号之类的,用空格来代替--for循环
for char in '-.,;\"':
    text = text.replace(char,' ')
print(text)
# 根据空格来划分,返回列表
for char in '-.,;\"' :
    text = text.replace(char,' ')
print(text.split(' ')[0:10])	
# ['On', 'a', 'dark', 'desert', 'highway', '', 'cool', 'wind', 'in', 'my']
# 输出不带''的列表, --'',长度为0
# 声明一个空列表,来接收去掉''的结果
cleaned_list = []
#方法一 --len(),统计字符串长度
for word in text.split(' '):
    word_length = len(word)
    if word_length > 0 :
        cleaned_list.append(word)
print(cleaned_list[0:10])
# ['On', 'a', 'dark', 'desert', 'highway,', 'cool', 'wind', 'in', 'my', 'hair']
# 方法二 --continue
for word in text.split(' ') :
    if word == '':
        continue
    cleaned_list.append(word)
print(cleaned_list[0:10])    
# ['On', 'a', 'dark', 'desert', 'highway', 'cool', 'wind', 'in', 'my', 'hair']

While循环

  • while循环与for循环的区别
For 循环While 循环
遍历一组对象条件为false时自动终止
没有break也可以结束使用break语句才能退出循环
  • 使while循环退出的两种方法:1、条件为False 2、使用break语句
  • 示例
# 条件为False
count = 0
while count <= 5:
    print(count,end = ' ')
    count = count + 1	# 0 1 2 3 4 5 
# 使用break语句
count = 0
while count <= 5:
    if count == 2:
        break
    count += 1
    print (count,end = ' ')	# 1 2 
  • 若想知道while循环的次数,可以使用range函数来实现
# 生成列表
x = list(range(0,5))
# while循环
while len(x) > 0 :
    first = x[0]
    x.remove(first)
    print(x)
"""
[1, 2, 3, 4]
[2, 3, 4]
[3, 4]
[4]
[]
"""    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值