《Python编程:从入门到实践》学习笔记(知识点梳理+练习题答案代码)——第4章 操作列表

书籍说明

书名:《Python编程:从入门到实践》(第一版)/Python Crash Course: A Hands-On, Project-Based Introduction to Programming

作者:Eric Matthes(著)/袁国忠(译)

出版社:人民邮电出版社

开发环境说明

Python Version: 3.11.2

Python IDE: PyCharm Community Edition 2022.3.3


目录

第4章 操作列表

4.1 遍历整个列表

4.1.1 深入地研究循环

4.1.2 在for循环中执行更多的操作

4.1.3 在for循环结束后执行一些操作

4.2 避免缩进错误

4.2.1 忘记缩进

4.2.2 忘记缩进额外的代码行

4.2.3 不必要的缩进

4.2.4 循环后不必要的缩进

4.2.5 遗漏了冒号

动手试一试

4.3 创建数字列表

4.3.1 使用函数range( )

4.3.2 使用range( )创建数字列表

4.3.3 对数字列表执行简单的统计计算

4.3.4 列表解析

动手试一试

4.4 使用列表的一部分

4.4.1 切片

4.4.2 遍历切片

4.4.3 复制列表

动手试一试

4.5 元组

4.5.1 定义元祖


第4章 操作列表

4.1 遍历整个列表

  • 需要对列表中的每个元素都执行相同的操作时,可使用Python中的for循环
  • 下面使用for循环来打印魔术师名单中的所有名字:
  • magicians = ['alice', 'david', 'carolina']
    for magician in magicians:
        print(magician)

    输出结果:

        alice
        david
        carolina

4.1.1 深入地研究循环

  • for循环,对列表中的每一个元素都执行循环指定的步骤,直到遍历全部元素,跳出循环,接着执行循环结束后的代码。
  • 对于用于存储列表中每个值的临时变量,可指定任何名称。

4.1.2 在for循环中执行更多的操作

  • 在for循环中,想包含多少行代码都可以,每个缩进的代码行都是循环的一部分,且将针对列表中的每个值都执行一次。
  • magicians = ['alice', 'david', 'carolina']
    for magician in magicians:
        print(magician.title() + ", that was a great trick!")
        print("I can't wait to see your next trick, " + magician.title() + ".\n")

    输出结果:

        Alice, that was a great trick!
        I can't wait to see your next trick, Alice.

        David, that was a great trick!
        I can't wait to see your next trick, David.

        Carolina, that was a great trick!
        I can't wait to see your next trick, Carolina.

4.1.3 在for循环结束后执行一些操作

  • 在for循环结束后面,没有缩进的代码行都只执行一次,而不会重复执行。
  • magicians = ['alice', 'david', 'carolina']
    for magician in magicians:
        print(magician.title() + ", that was a great trick!")
        print("I can't wait to see your next trick, " + magician.title() + ".\n")
    print("Thank you, everyone. That was a great magic show!")

    输出结果:

        Alice, that was a great trick!
        I can't wait to see your next trick, Alice.

        David, that was a great trick!
        I can't wait to see your next trick, David.

        Carolina, that was a great trick!
        I can't wait to see your next trick, Carolina.

        Thank you, everyone. That was a great magic show!

4.2 避免缩进错误

4.2.1 忘记缩进

4.2.2 忘记缩进额外的代码行

4.2.3 不必要的缩进

4.2.4 循环后不必要的缩进

4.2.5 遗漏了冒号

动手试一试

4-1 比萨:想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用for循环将每种比萨的名称都打印出来。

修改这个for循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称。对于每种比萨,都显示一行输出,如“I like pepperoni pizza”。

在程序末尾添加一行代码,它不在for循环中,指出你有多喜欢比萨。输出应包含针对每种比萨的消息,还有一个总结性句子&

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值