Python中For循环与While 循环的使用
For循环是迭代对象元素的常用方法,具有可迭代方法的任何对象都可以在for循环中使用。python的一个独特功能是代码块不被{} 或begin,end包围。相反,python使用缩进,块内的行必须通过制表符缩进,或相对于周围的命令缩进4个空格。
For循环在枚举中使用:
返回一个元组,其中包含每次迭代的计数(从默认为0开始)和迭代序列获得的值:
# For在枚举中使用:
# 返回一个元组,其中包含每次迭代的计数(从默认为0开始)和迭代序列获得的值:
friends = ['steve', 'rachel', 'michael', 'adam', 'monica']
for index, friend in enumerate(friends):
print(index,friend)
Continue和Break在For循环中的使用:
利用For循环:从下面文本中删除标点符号并将其转换为列表:
- 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
思路:
- 第一步:从文本中删除标点符(String中replace方法)
- 第二步:将其转换为列表(Split函数:将String转换成list)
# 利用For循环:从文本中删除标点符号并将其转换为列表:(Continue在For循环中的使用:)
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'''
print(text)
#第一步:从文本中删除标点符,
for char in '-.,;\n"\'':
text = text.replace(char,' ')
print(text)
#第二步:将其转换为列表
# Split converts string to list。Split函数:将String转换成list
print('要将其转换为列表:',text.split(' ')[0:20])
#法一:利用空格长度=0,去除列表中空格。
# Each item in list is split on spaces
# Dont want to have non words in my list for example ''
# which in this case are things of zero length
len('')
# Making new list with no empty words in it
cleaned_list = []
for word in text.split(' '):
word_length = len(word)
if word_length > 0:
cleaned_list.append(word)#不是空格,append追加
print('利用For循环中if语句:',cleaned_list[0:20])
#法二:利用Continue:
# continue语句将转到循环的下一次迭代
# continue语句用于忽略某些值,但不会中断循环
cleaned_list = []
for word in text.split(' '):
if word == '':
continue#如果是空格,不处理,继续for循环
cleaned_list.append(word)
print('利用For循环中continue',cleaned_list[0:20])
# for中Break的使用:
# break语句将完全打断循环
cleaned_list = []
for word in text.split(' '):
if word == 'desert':
print('I found the word I was looking for')
break
cleaned_list.append(word)
print(cleaned_list)
举例:
编写一个Python程序,使用for循环迭代整数从1到50。对于偶数的整数,将其附加到列表even_numbers;对于奇数的整数,将其附加到奇数奇数列表中。
# Making empty lists to append even and odd numbers to.
even_numbers = []
odd_numbers = []
for number in range(1,51):
if number%2==0:
even_numbers.append(number)
else:
odd_numbers.append(number)
print(even_numbers,"\n",odd_numbers)
For 循环与While 循环区别:
For 循环 | While 循环 |
---|---|
遍历一组对象 | 条件为false时自动终止 |
没有break也可以结束 | 使用break语句才能退出循环 |
break语句在While 循环中使用:
使用break可以完全退出循环
count = 0
while count <= 5:
if count == 2:
break
count += 1
print (count)
x = 1
while x % 5 != 0:
x += 1
print(x)