Python 30天:第十天 -- 循环

本文介绍了Python编程中的循环结构,包括while循环和for循环的语法及使用,如条件判断、break和continue语句的运用,以及range()函数和嵌套循环的概念。此外,还讨论了循环控制技巧,如在满足特定条件时中断或跳过循环的执行。
摘要由CSDN通过智能技术生成

<< 第九天 || 第十一天 >>

第十天

循环

生活充满了例行公事。在编程中,我们也会做很多重复性的工作。为了处理重复性任务,编程语言使用循环。Python编程语言还提供了以下两种循环类型:

  1. while循环
  2. for循环

循环 

我们使用保留字while来进行 while 循环。它用于重复执行语句块,直到满足给定条件。当条件变为假时,循环后的代码行将继续执行。

  # syntax
while condition:
    code goes here

例子: 

count = 0
while count < 5:
    print(count)
    count = count + 1
#prints from 0 to 4

在上面的 while 循环中,当 count 为 5 时条件变为 false。即循环停止的时候。如果我们有兴趣在条件不再为真时运行代码块,我们可以使用else

  # syntax
while condition:
    code goes here
else:
    code goes here

例子: 

count = 0
while count < 5:
    print(count)
    count = count + 1
else:
    print(count)

 当 count 为 5 时,上述循环条件将为 false,循环停止,开始执行 else 语句。结果将打印 5。

中断并继续 - 第一部分

  • Break:当我们想退出或停止循环时,我们使用 break。
    # syntax
    while condition:
        code goes here
        if another_condition:
            break

    例子:

    count = 0
    while count < 5:
        print(count)
        count = count + 1
        if count == 3:
            break

    上面的 while 循环只打印 0、1、2,但是当它到达 3 时它停止了。

  • Continue:使用 continue 语句我们可以跳过当前迭代,并继续下一个迭代:
  # syntax
while condition:
    code goes here
    if another_condition:
        continue

例子: 

count = 0
while count < 5:
    if count == 3:
        continue
    print(count)
    count = count + 1

上面的 while 循环只打印 0、1、2 和 4(跳过 3)。

For循环

for关键字用于构成 for 循环,与其他编程语言类似,但语法有所不同。循环用于迭代序列(即列表、元组、字典、集合或字符串)。

  • 带列表的for循环
    # syntax
    for iterator in lst:
        code goes here

    例子:

    numbers = [0, 1, 2, 3, 4, 5]
    for number in numbers: # number is temporary name to refer to the list's items, valid only inside this loop
        print(number)       # the numbers will be printed line by line, from 0 to 5
  • 带字符串的for循环
    # syntax
    for iterator in string:
        code goes here

    例子:

    language = 'Python'
    for letter in language:
        print(letter)
    
    
    for i in range(len(language)):
        print(language[i])
  • 元组的for循环
    # syntax
    for iterator in tpl:
        code goes here

    例子:

    numbers = (0, 1, 2, 3, 4, 5)
    for number in numbers:
        print(number)
  • For loop with dictionary 循环遍历字典给你字典的键。
      # syntax
    for iterator in dct:
        code goes here

    例子:

    person = {
        'first_name':'Asabeneh',
        'last_name':'Yetayeh',
        'age':250,
        'country':'Finland',
        'is_marred':True,
        'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
        'address':{
            'street':'Space street',
            'zipcode':'02210'
        }
    }
    for key in person:
        print(key)
    
    for key, value in person.items():
        print(key, value) # this way we get both keys and values printed out
  • 集合中的循环
    # syntax
    for iterator in st:
        code goes here

    例子:

    it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'}
    for company in it_companies:
        print(company)

    中断并继续 - 第二部分

 简短提醒: Break:当我们想在循环完成之前停止它时,我们使用 break 。

# syntax
for iterator in sequence:
    code goes here
    if condition:
        break

例子:

numbers = (0,1,2,3,4,5)
for number in numbers:
    print(number)
    if number == 3:
        break

在上面的示例中,循环在到达 3 时停止。

continue:当我们想跳过循环迭代中的某些步骤时,我们使用continue.
  # syntax
for iterator in sequence:
    code goes here
    if condition:
        continue

例子: 

numbers = (0,1,2,3,4,5)
for number in numbers:
    print(number)
    if number == 3:
        continue
    print('Next number should be ', number + 1) if number != 5 else print("loop's end") # for short hand conditions need both if and else statements
print('outside the loop')

 在上面的示例中,如果数字等于 3,则跳过条件之后(但在循环内部)的步骤,如果还有任何迭代,则继续执行循环。

range()函数

range()函数用于数字列表。range (start, end, step)采用三个参数:starting、ending 和 increment。默认情况下它从 0 开始,增量为 1。范围序列至少需要 1 个参数(结束)。使用范围创建序列

lst = list(range(11)) 
print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
st = set(range(1, 11))    # 2 arguments indicate start and end of the sequence, step set to default 1
print(st) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

lst = list(range(0,11,2))
print(lst) # [0, 2, 4, 6, 8, 10]
st = set(range(0,11,2))
print(st) #  {0, 2, 4, 6, 8, 10}
# syntax
for iterator in range(start, end, step):

例子:

for number in range(11):
    print(number)   # prints 0 to 10, not including 11

嵌套循环 

我们可以在循环中编写循环。

# syntax
for x in y:
    for t in x:
        print(t)

例子: 

person = {
    'first_name': 'Asabeneh',
    'last_name': 'Yetayeh',
    'age': 250,
    'country': 'Finland',
    'is_marred': True,
    'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
    'address': {
        'street': 'Space street',
        'zipcode': '02210'
    }
}
for key in person:
    if key == 'skills':
        for skill in person['skills']:
            print(skill)

 For Else

如果我们想在循环结束时执行一些消息,我们使用 else。

# syntax
for iterator in range(start, end, step):
    do something
else:
    print('The loop ended')

例子:

for number in range(11):
    print(number)   # prints 0 to 10, not including 11
else:
    print('The loop stops at', number)

Pass

在python中when语句是必需的(分号后),但我们不喜欢在那里执行任何代码,我们可以写pass这个词来避免错误。我们也可以将它用作占位符,用于未来的陈述。

例子:

for number in range(6):
    pass

🌕你建立了一个重要的里程碑,你是不可阻挡的。继续前进!您刚刚完成了第 10 天的挑战,您已经迈出了通往卓越之路的 10 步。现在为你的大脑和肌肉做一些练习。

练习: 第十天

练习:1级

  1. 使用 for 循环迭代 0 到 10,使用 while 循环执行相同的操作。

  2. 使用 for 循环将 10 迭代到 0,使用 while 循环执行相同的操作。

  3. 编写一个循环,对 print() 进行七次调用,因此我们在输出中得到以下三角形:

      #
      ##
      ###
      ####
      #####
      ######
      #######
  4. 使用嵌套循环创建以下内容:

    # # # # # # # #
    # # # # # # # #
    # # # # # # # #
    # # # # # # # #
    # # # # # # # #
    # # # # # # # #
    # # # # # # # #
    # # # # # # # #
  5. 打印以下图案:

    0 x 0 = 0
    1 x 1 = 1
    2 x 2 = 4
    3 x 3 = 9
    4 x 4 = 16
    5 x 5 = 25
    6 x 6 = 36
    7 x 7 = 49
    8 x 8 = 64
    9 x 9 = 81
    10 x 10 = 100
  6. 使用 for 循环遍历列表 ['Python', 'Numpy','Pandas','Django', 'Flask'] 并打印出项目。

  7. 使用 for 循环从 0 迭代到 100 并仅打印偶数

  8. 使用 for 循环从 0 到 100 迭代并只打印奇数

练习:2级 

  1. 使用 for 循环从 0 迭代到 100 并打印所有数字的总和。
    The sum of all numbers is 5050.
  2. 使用 for 循环从 0 迭代到 100 并打印所有偶数之和和所有奇数之和。
    The sum of all evens is 2550. And the sum of all odds is 2500.

🎉恭喜!🎉

<< 第九天 || 第十一天 >>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

舍不得,放不下

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值