[Python]学习笔记5——For循环

For循环

是迭代对象元素的常用方法
具有可迭代方法的任何对象都可以在for循环中使用。
python的一个独特功能是代码块不被{} 或begin,end包围。
相反,python使用缩进,块内的行必须通过制表符缩进,或相对于周围的命令缩进4个空格。

for number in [23, 41, 12, 16, 7]:
    print(number)
print('Hi')

结果:
在这里插入图片描述
1、枚举
枚举函数返回一个元组,其中包含每次迭代的计数(从默认为0的开始)和迭代序列获得的值

friends = ['steve', 'rachel', 'michael', 'adam', 'monica']
for index, friend in enumerate(friends):
    print(index,friend)

结果:
在这里插入图片描述
练习一个题:

#将这段话的标点符号去掉,并且把它分开到列表中
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 a in ['-',',',';','\"']:
    text=text.replace(a,' ')#用空格代替

print(text)

text=text.split(' ')[0:100]#用空格给分开
print(text)

结果:
在这里插入图片描述
2、len(’’)

#将这段话的标点符号去掉,并且把它分开到列表中
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 a in ['-',',',';','\"']:
    text=text.replace(a,' ')#用空格代替

list=[]
for a in text.split(' '):
    if len(a)>0:#如果提取出来的长度大于0就放进列表中
        list.append(a)

print(list[0:20])

结果:
在这里插入图片描述
3、Continue
continue语句将转到循环的下一次迭代
continue语句用于忽略某些值,但不会中断循环

for a in ['-',',',';','\"']:
    text=text.replace(a,' ')#用空格代替

list=[]
for a in text.split(' '):
    if len(a)==0:#如果提取出来的=0就下一次循环
        continue
    list.append(a)

print(list[0:20])

结果:
在这里插入图片描述
4、Break
break语句将完全打断循环

#将这段话的标点符号去掉,并且把它分开到列表中
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 a in ['-',',',';','\"']:
    text=text.replace(a,' ')#用空格代替

list=[]
for a in text.split(' '):
    if len(a)==0:
        break
    list.append(a)

print(list[0:20])

结果:
在这里插入图片描述

练习:

编写一个Python程序,它迭代整数从1到50(使用for循环)。对于偶数的整数,将其附加到列表even_numbers。对于奇数的整数,将其附加到奇数奇数列表中。

提示:range(1,51)代表1-50取整数

even_number=[]#偶数列表
odd_number=[]#奇数列表

for a in range(1,51):
    if a%2==0:
        even_number.append(a)
    else:
        odd_number.append(a)

print(even_number)
print(odd_number)

结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Shadownow/article/details/105820708