当前位置:   article > 正文

python快速入门【三】-----For 循环、While 循环_python中迭代整数1到50

python中迭代整数1到50

python入门合集:

python快速入门【一】-----基础语法

python快速入门【二】----常见的数据结构

python快速入门【三】-----For 循环、While 循环

python快速入门【四】-----各类函数创建

python快速入门【五】---- 面向对象编程

python快速入门【六】----真题测试


 

For 循环

For循环是迭代对象元素的常用方法(在第一个示例中,列表)

具有可迭代方法的任何对象都可以在for循环中使用。

python的一个独特功能是代码块不被{} 或begin,end包围。相反,python使用缩进,块内的行必须通过制表符缩进,或相对于周围的命令缩进4个空格。

虽然这一开始可能看起来不直观,但它鼓励编写更易读的代码,随着时间的推移,你会学会喜欢它

In [1]

  1. #取第一个列表成员(可迭代),暂称它数字(打印它)
  2. #取列表的第二个成员(可迭代),暂时将其称为数字,等等......
  3. for number in [23, 41, 12, 16, 7]:
  4. print(number)
  5. print('Hi')
  1. 23
  2. 41
  3. 12
  4. 16
  5. 7
  6. Hi

枚举

返回一个元组,其中包含每次迭代的计数(从默认为0开始)和迭代序列获得的值:

In [2]

  1. friends = ['steve', 'rachel', 'michael', 'adam', 'monica']
  2. for index, friend in enumerate(friends):
  3. print(index,friend)
  1. 0 steve
  2. 1 rachel
  3. 2 michael
  4. 3 adam
  5. 4 monica

Task

从文本中删除标点符号并将最终产品转换为列表:

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

(加州旅馆)

In [3]

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'''

In [4]

print(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循环中使用。即使是字符串,尽管没有可迭代的方法 - 但我们不会在这里继续。具有可迭代方法基本上意味着数据可以以列表形式呈现,其中有序地存在多个值。

In [5]

  1. for char in '-.,;\n"\'':
  2. text = text.replace(char,' ')
  3. print(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

In [6]

  1. # Split converts string to list.
  2. # Each item in list is split on spaces
  3. text.split(' ')[0:20]
  1. ['On',
  2. 'a',
  3. 'dark',
  4. 'desert',
  5. 'highway',
  6. '',
  7. 'cool',
  8. 'wind',
  9. 'in',
  10. 'my',
  11. 'hair',
  12. 'Warm',
  13. 'smell',
  14. 'of',
  15. 'colitas',
  16. '',
  17. 'rising',
  18. 'up',
  19. 'through',
  20. 'the']

In [7]

  1. # Dont want to have non words in my list for example ''
  2. # which in this case are things of zero length
  3. len('')
0

In [8]

  1. # Making new list with no empty words in it
  2. cleaned_list = []

In [9]

  1. for word in text.split(' '):
  2. word_length = len(word)
  3. if word_length > 0:
  4. cleaned_list.append(word)

In [10]

cleaned_list[0:20]
  1. ['On',
  2. 'a',
  3. 'dark',
  4. 'desert',
  5. 'highway',
  6. 'cool',
  7. 'wind',
  8. 'in',
  9. 'my',
  10. 'hair',
  11. 'Warm',
  12. 'smell',
  13. 'of',
  14. 'colitas',
  15. 'rising',
  16. 'up',
  17. 'through',
  18. 'the',
  19. 'air',
  20. 'Up']

Continue

continue语句将转到循环的下一次迭代

continue语句用于忽略某些值,但不会中断循环

In [11]

  1. cleaned_list = []
  2. for word in text.split(' '):
  3. if word == '':
  4. continue
  5. cleaned_list.append(word)
  6. cleaned_list[1:20]
  1. ['a',
  2. 'dark',
  3. 'desert',
  4. 'highway',
  5. 'cool',
  6. 'wind',
  7. 'in',
  8. 'my',
  9. 'hair',
  10. 'Warm',
  11. 'smell',
  12. 'of',
  13. 'colitas',
  14. 'rising',
  15. 'up',
  16. 'through',
  17. 'the',
  18. 'air',
  19. 'Up']

Break

break语句将完全打断循环

In [12]

cleaned_list = []

In [13]

  1. for word in text.split(' '):
  2. if word == 'desert':
  3. print('I found the word I was looking for')
  4. break
  5. cleaned_list.append(word)
  6. cleaned_list
I found the word I was looking for
['On', 'a', 'dark']

Task (顺道介绍一下Range函数)

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

In [14]

  1. # Making empty lists to append even and odd numbers to.
  2. even_numbers = []
  3. odd_numbers = []
  4. for number in range(1,51):
  5. if number % 2 == 0:
  6. even_numbers.append(number)
  7. else:
  8. odd_numbers.append(number)

In [15]

print("Even Numbers: ", even_numbers)
Even Numbers:  [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]

In [16]

print("Odd Numbers: ", odd_numbers)
Odd Numbers:  [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]

Python 2 vs Python 3 (Range函数的不同点)

python 2 xrange and python 3 range are same (resembles a generator) python 2 range生成一个list

注意: 较长的列表会很慢

更多参考: http://pythoncentral.io/pythons-range-function-explained/

 

 

While 循环

For 循环While 循环
遍历一组对象条件为false时自动终止
没有break也可以结束使用break语句才能退出循环

如果我们希望循环在某个时刻结束,我们最终必须使条件为False

In [1]

  1. # Everytime through the loop, it checks condition everytime until count is 6
  2. # can also use a break to break out of while loop.
  3. count = 0
  4. while count <= 5:
  5. print(count)
  6. count = count + 1
  1. 0
  2. 1
  3. 2
  4. 3
  5. 4
  6. 5

break语句

使用break可以完全退出循环

In [2]

  1. count = 0
  2. while count <= 5:
  3. if count == 2:
  4. break
  5. count += 1
  6. print (count)
  1. 1
  2. 2

while True条件使得除非遇到break语句,否则不可能退出循环

如果您陷入无限循环,请使用计算机上的ctrl + c来强制终止

In [3]

  1. num = 0
  2. while True:
  3. if num == 2:
  4. print('Found 2')
  5. break
  6. num += 1
  7. print (num)
  1. 1
  2. 2
  3. Found 2

提醒:使用模运算符(%),它将数字左边的余数除以右边的数字

In [4]

  1. # 1 divided by 5 is 0 remainder 1
  2. 1 % 5
1

In [5]

  1. # 5 divided by 5 is 0 remainder 0
  2. 5 % 5
0
比较操作符功能
<小于
<=小于或等于

| 大于 = | 大于或等于 == | 等于 != | 不等于

In [6]

  1. x = 1
  2. while x % 5 != 0:
  3. x += 1
  4. print(x)
  1. 2
  2. 3
  3. 4
  4. 5

当我们知道要循环多少次时,Range很有用

下面例子是: 从0开始,但不包括5

In [7]

  1. candidates = list(range(0, 5))
  2. candidates
[0, 1, 2, 3, 4]

In [8]

  1. while len(candidates) > 0:
  2. first = candidates[0]
  3. candidates.remove(first)
  4. print(candidates)
  1. [1, 2, 3, 4]
  2. [2, 3, 4]
  3. [3, 4]
  4. [4]
  5. []
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/436466
推荐阅读
相关标签
  

闽ICP备14008679号