Chapter 6: Loops and Iterations | Python for Everybody 讲义笔记_En

news2024/12/23 10:58:27

文章目录

  • Python for Everybody
    • 课程简介
    • Loops and Iterations
      • Updating variables
      • The `while` statement
      • Infinite loops
      • Finishing iterations with `continue`
      • Definite loops using `for`
      • Loop patterns
      • Counting and summing loops
      • Maximum and minimum loops
      • Debugging
      • Glossary


Python for Everybody

Exploring Data Using Python 3
Dr. Charles R. Severance


课程简介

Python for Everybody 零基础程序设计(Python 入门)

  • This course aims to teach everyone the basics of programming computers using Python. 本课程旨在向所有人传授使用 Python 进行计算机编程的基础知识。
  • We cover the basics of how one constructs a program from a series of simple instructions in Python. 我们介绍了如何通过 Python 中的一系列简单指令构建程序的基础知识。
  • The course has no pre-requisites and avoids all but the simplest mathematics. Anyone with moderate computer experience should be able to master the materials in this course. 该课程没有任何先决条件,除了最简单的数学之外,避免了所有内容。任何具有中等计算机经验的人都应该能够掌握本课程中的材料。
  • This course will cover Chapters 1-5 of the textbook “Python for Everybody”. Once a student completes this course, they will be ready to take more advanced programming courses. 本课程将涵盖《Python for Everyday》教科书的第 1-5 章。学生完成本课程后,他们将准备好学习更高级的编程课程。
  • This course covers Python 3.

在这里插入图片描述

coursera

Python for Everybody 零基础程序设计(Python 入门)

Charles Russell Severance
Clinical Professor

在这里插入图片描述

个人主页
Twitter

在这里插入图片描述

University of Michigan


课程资源

coursera原版课程视频
coursera原版视频-中英文精校字幕-B站
Dr. Chuck官方翻录版视频-机器翻译字幕-B站

PY4E-课程配套练习
Dr. Chuck Online - 系列课程开源官网



Loops and Iterations

We look at how Python repeats statements using looping structures.


Updating variables

A common pattern in assignment statements is an assignment statement that updates a variable, where the new value of the variable depends on the old.

x = x + 1

This means “get the current value of x, add 1, and then update x with the new value.”

If you try to update a variable that doesn’t exist, you get an error, because Python evaluates the right side before it assigns a value to x:

>>> x = x + 1
NameError: name 'x' is not defined

Before you can update a variable, you have to initialize it, usually with a simple assignment:

>>> x = 0
>>> x = x + 1

Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.


The while statement

Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. Because iteration is so common, Python provides several language features to make it easier.

One form of iteration in Python is the while statement. Here is a simple program that counts down from five and then says “Blastoff!”.

n = 5
while n > 0:
    print(n)
    n = n - 1
print('Blastoff!')

You can almost read the while statement as if it were English. It means, “While n is greater than 0, display the value of n and then reduce the value of n by 1. When you get to 0, exit the while statement and display the word Blastoff!

More formally, here is the flow of execution for a while statement:

  1. Evaluate the condition, yielding True or False.
  2. If the condition is false, exit the while statement and continue execution at the next statement.
  3. If the condition is true, execute the body and then go back to step 1.

This type of flow is called a loop because the third step loops back around to the top. We call each time we execute the body of the loop an iteration. For the above loop, we would say, “It had five iterations”, which means that the body of the loop was executed five times.

The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates. We call the variable that changes each time the loop executes and controls when the loop finishes the iteration variable. If there is no iteration variable, the loop will repeat forever, resulting in an infinite loop.


Infinite loops

An endless source of amusement for programmers is the observation that the directions on shampoo, “Lather, rinse, repeat,” are an infinite loop because there is no iteration variable telling you how many times to execute the loop.

In the case of countdown, we can prove that the loop terminates because we know that the value of n is finite, and we can see that the value of n gets smaller each time through the loop, so eventually we have to get to 0. Other times a loop is obviously infinite because it has no iteration variable at all.

Sometimes you don’t know it’s time to end a loop until you get half way through the body. In that case you can write an infinite loop on purpose and then use the break statement to jump out of the loop.

This loop is obviously an infinite loop because the logical expression on the while statement is simply the logical constant True:

n = 10
while True:
    print(n, end=' ')
    n = n - 1
print('Done!')

If you make the mistake and run this code, you will learn quickly how to stop a runaway Python process on your system or find where the power-off button is on your computer. This program will run forever or until your battery runs out because the logical expression at the top of the loop is always true by virtue of the fact that the expression is the constant value True.

While this is a dysfunctional infinite loop, we can still use this pattern to build useful loops as long as we carefully add code to the body of the loop to explicitly exit the loop using break when we have reached the exit condition.

For example, suppose you want to take input from the user until they type done. You could write:

while True:
    line = input('> ')
    if line == 'done':
        break
    print(line)
print('Done!')

# Code: http://www.py4e.com/code3/copytildone1.py

The loop condition is True, which is always true, so the loop runs repeatedly until it hits the break statement.

Each time through, it prompts the user with an angle bracket. If the user types done, the break statement exits the loop. Otherwise the program echoes whatever the user types and goes back to the top of the loop. Here’s a sample run:

> hello there
hello there
> finished
finished
> done
Done!

This way of writing while loops is common because you can check the condition anywhere in the loop (not just at the top) and you can express the stop condition affirmatively (“stop when this happens”) rather than negatively (“keep going until that happens.”).


Finishing iterations with continue

Sometimes you are in an iteration of a loop and want to finish the current iteration and immediately jump to the next iteration. In that case you can use the continue statement to skip to the next iteration without finishing the body of the loop for the current iteration.

Here is an example of a loop that copies its input until the user types “done”, but treats lines that start with the hash character as lines not to be printed (kind of like Python comments).

while True:
    line = input('> ')
    if line[0] == '#':
        continue
    if line == 'done':
        break
    print(line)
print('Done!')

# Code: http://www.py4e.com/code3/copytildone2.py

Here is a sample run of this new program with continue added.

> hello there
hello there
> # don't print this
> print this!
print this!
> done
Done!

All the lines are printed except the one that starts with the hash sign because when the continue is executed, it ends the current iteration and jumps back to the while statement to start the next iteration, thus skipping the print statement.


Definite loops using for

Sometimes we want to loop through a set of things such as a list of words, the lines in a file, or a list of numbers. When we have a list of things to loop through, we can construct a definite loop using a for statement. We call the while statement an indefinite loop because it simply loops until some condition becomes False, whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set.

The syntax of a for loop is similar to the while loop in that there is a for statement and a loop body:

friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends:
    print('Happy New Year:', friend)
print('Done!')

In Python terms, the variable friends is a list1 of three strings and the for loop goes through the list and executes the body once for each of the three strings in the list resulting in this output:

Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!

Translating this for loop to English is not as direct as the while, but if you think of friends as a set, it goes like this: “Run the statements in the body of the for loop once for each friend in the set named friends.”

Looking at the for loop, for and in are reserved Python keywords, and friend and friends are variables.

for friend in friends:
    print('Happy New Year:', friend)

In particular, friend is the iteration variable for the for loop. The variable friend changes for each iteration of the loop and controls when the for loop completes. The iteration variable steps successively through the three strings stored in the friends variable.


Loop patterns

Often we use a for or while loop to go through a list of items or the contents of a file and we are looking for something such as the largest or smallest value of the data we scan through.

These loops are generally constructed by:

  • Initializing one or more variables before the loop starts
  • Performing some computation on each item in the loop body, possibly changing the variables in the body of the loop
  • Looking at the resulting variables when the loop completes

We will use a list of numbers to demonstrate the concepts and construction of these loop patterns.


Counting and summing loops

For example, to count the number of items in a list, we would write the following for loop:

count = 0
for itervar in [3, 41, 12, 9, 74, 15]:
    count = count + 1
print('Count: ', count)

We set the variable count to zero before the loop starts, then we write a for loop to run through the list of numbers. Our iteration variable is named itervar and while we do not use itervar in the loop, it does control the loop and cause the loop body to be executed once for each of the values in the list.

In the body of the loop, we add 1 to the current value of count for each of the values in the list. While the loop is executing, the value of count is the number of values we have seen “so far”.

Once the loop completes, the value of count is the total number of items. The total number “falls in our lap” at the end of the loop. We construct the loop so that we have what we want when the loop finishes.

Another similar loop that computes the total of a set of numbers is as follows:

total = 0
for itervar in [3, 41, 12, 9, 74, 15]:
    total = total + itervar
print('Total: ', total)

In this loop we do use the iteration variable. Instead of simply adding one to the count as in the previous loop, we add the actual number (3, 41, 12, etc.) to the running total during each loop iteration. If you think about the variable total, it contains the “running total of the values so far”. So before the loop starts total is zero because we have not yet seen any values, during the loop total is the running total, and at the end of the loop total is the overall total of all the values in the list.

As the loop executes, total accumulates the sum of the elements; a variable used this way is sometimes called an accumulator.

Neither the counting loop nor the summing loop are particularly useful in practice because there are built-in functions len() and sum() that compute the number of items in a list and the total of the items in the list respectively.


Maximum and minimum loops

To find the largest value in a list or sequence, we construct the following loop:

largest = None
print('Before:', largest)
for itervar in [3, 41, 12, 9, 74, 15]:
    if largest is None or itervar > largest :
        largest = itervar
    print('Loop:', itervar, largest)
print('Largest:', largest)

When the program executes, the output is as follows:

Before: None
Loop: 3 3
Loop: 41 41
Loop: 12 41
Loop: 9 41
Loop: 74 74
Loop: 15 74
Largest: 74

The variable largest is best thought of as the “largest value we have seen so far”. Before the loop, we set largest to the constant None. None is a special constant value which we can store in a variable to mark the variable as “empty”.

Before the loop starts, the largest value we have seen so far is None since we have not yet seen any values. While the loop is executing, if largest is None then we take the first value we see as the largest so far. You can see in the first iteration when the value of itervar is 3, since largest is None, we immediately set largest to be 3.

After the first iteration, largest is no longer None, so the second part of the compound logical expression that checks itervar > largest triggers only when we see a value that is larger than the “largest so far”. When we see a new “even larger” value we take that new value for largest. You can see in the program output that largest progresses from 3 to 41 to 74.

At the end of the loop, we have scanned all of the values and the variable largest now does contain the largest value in the list.

To compute the smallest number, the code is very similar with one small change:

smallest = None
print('Before:', smallest)
for itervar in [3, 41, 12, 9, 74, 15]:
    if smallest is None or itervar < smallest:
        smallest = itervar
    print('Loop:', itervar, smallest)
print('Smallest:', smallest)

Again, smallest is the “smallest so far” before, during, and after the loop executes. When the loop has completed, smallest contains the minimum value in the list.

Again as in counting and summing, the built-in functions max() and min() make writing these exact loops unnecessary.

The following is a simple version of the Python built-in min() function:

def min(values):
    smallest = None
    for value in values:
        if smallest is None or value < smallest:
            smallest = value
    return smallest

In the function version of the smallest code, we removed all of the print statements so as to be equivalent to the min function which is already built in to Python.


Debugging

As you start writing bigger programs, you might find yourself spending more time debugging. More code means more chances to make an error and more places for bugs to hide.

One way to cut your debugging time is “debugging by bisection.” For example, if there are 100 lines in your program and you check them one at a time, it would take 100 steps.

Instead, try to break the problem in half. Look at the middle of the program, or near it, for an intermediate value you can check. Add a print statement (or something else that has a verifiable effect) and run the program.

If the mid-point check is incorrect, the problem must be in the first half of the program. If it is correct, the problem is in the second half.

Every time you perform a check like this, you halve the number of lines you have to search. After six steps (which is much less than 100), you would be down to one or two lines of code, at least in theory.

In practice it is not always clear what the “middle of the program” is and not always possible to check it. It doesn’t make sense to count lines and find the exact midpoint. Instead, think about places in the program where there might be errors and places where it is easy to put a check. Then choose a spot where you think the chances are about the same that the bug is before or after the check.


Glossary

accumulator
A variable used in a loop to add up or accumulate a result.
counter
A variable used in a loop to count the number of times something happened. We initialize a counter to zero and then increment the counter each time we want to “count” something.
decrement
An update that decreases the value of a variable.
initialize
An assignment that gives an initial value to a variable that will be updated.
increment
An update that increases the value of a variable (often by one).
infinite loop
A loop in which the terminating condition is never satisfied or for which there is no terminating condition.
iteration
Repeated execution of a set of statements using either a function that calls itself or a loop.


  1. We will examine lists in more detail in a later chapter. ↩︎

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/745490.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Chapter 7: Strings | Python for Everybody 讲义笔记_En

文章目录 Python for Everybody课程简介StringsA string is a sequenceGetting the length of a string using lenTraversal through a string with a loopString slicesStrings are immutableLooping and countingThe in operatorString comparisonString methodsParsing stri…

x86平台实时Windows机器视觉EtherCAT运动控制器VPLC711

一、市场背景 简单易用&#xff0c;功能强大&#xff0c;正运动技术持续专注智能制造核心控制器的产品与平台的突破&#xff01; 随着智能制造的兴起&#xff0c;制造型企业正面临着日益激烈的市场竞争和对生产效率与产品品质提升的迫切需求&#xff0c;以满足市场的要求。同…

详解自定义类型:结构体,枚举,联合

目录 结构体 结构体基础知识 结构的自引用 结构体内存对齐 结构体大小计算 存在内存对齐的原因 设计结构体时的技巧 修改默认对齐数 结构体实现位段&#xff08;位段的填充&可移植性&#xff09; 什么是位段 位段的内存分配 位段的跨平台问题 位段的应用 枚…

做数据库内核开发的人员很少吗?

是的&#xff0c;相对于其他领域的软件开发&#xff0c;数据库内核开发人员的数量确实相对较少。这是因为数据库内核开发是一项高度专业化和复杂的任务&#xff0c;需要深入理解数据库系统的原理、算法和底层技术。 我这里刚好有嵌入式、单片机、plc的资料需要可以私我或在评论…

和鲸数据科学专家平台正式成立,凝聚专家资源推进产业数字化升级

2015年&#xff0c;大数据与人工智能从技术到公众认知均迎来重大突破&#xff0c;全国首批“数据科学与大数据技术”专业获批 同年&#xff0c;和鲸科技的前身科赛网 Kesci 正式成立&#xff0c;从数据竞赛社区出发为“数据人”提供实践与成长的平台。 2023年&#xff0c;数据…

sql语句汇总

最近项目中接触到了mySql,把经常用到的MySql语句记录下来&#xff0c;方便以后随时查阅。 1.密码加密 表结构如下 INSERT INTO tbl_userinfo ( vc_accname,vc_username,vc_pwd,vc_phone,i_role_id,dt_creatTime) VALUES (%s,%s,AES_ENCRYPT((%s), Wang),%s,%d,NOW())该表主…

Shiro教程(二):Springboot整合Shiro全网最全教程

Shiro教程&#xff08;二&#xff09;&#xff1a;Springboot整合Shiro全网最全教程 1、SpringBoot整合Shiro环境搭建 新建Module 新建springboot项目 选择一个依赖就行&#xff0c;因为这里idea版本的问题&#xff0c;SpringBoot的版本最低就是2.7.13。可以等项目创建成功之后…

无需下载任何软件!BurpSuite如何抓取iphone数据包

一、手机电脑处于同一个网段下 此处我的手机和电脑都处在X.X.1.X网段下 二、BurpSuite设置 添加代理 手机端配置代理 配置完点击存储 三、手机导入证书文件 手机端在Safari浏览器输入【电脑端ip:8080】 允许 在设置里打开 “已下载描述文件” 选择安装&#xff08;因为我已…

第五课:Figma 玻璃拟态页设计

效果展示 通过背景模糊实现玻璃拟态效果 选择合适的背景&#xff0c;绘制形状&#xff0c;给形状添加 Effects&#xff0c;点击下方的下拉选择框&#xff0c;选择 background blur&#xff1b;添加后会发现&#xff0c;画面无任何改变&#xff0c;调整 Fill 后面的百分比&…

【JavaEE进阶】使用注解存储对象

使用注解存储对象 之前我们存储Bean时&#xff0c;需要在spring-config 中添加一行 bean注册内容才行&#xff0c;如下图所示&#xff1a; 问题引入&#xff1a;如果想在Spring 中能够更简单的进行对象的存储和读取&#xff0c;该怎么办呢&#xff1f; 问题解答&#xff1a;实…

【c++】std::move 所有权转移的使用

1. std::move用法详细梳理 ref_frames_ std::move(ref_frames);cur_frames_ cur_frames;使用std::move函数的好处是可以将资源的所有权从一个对象转移到另一个对象&#xff0c;而不需要进行深拷贝操作。对于智能指针类型的变量&#xff0c;使用std::move也是可以的&#xff0…

K8s(kubernetes)集群搭建及dashboard安装、基础应用部署

基础介绍 概念 本质是一组服务器集群&#xff0c;在集群每个节点上运行特定的程序&#xff0c;来对节点中的容器进行管理。实现资源管理的自动化。 功能 自我修复弹性伸缩服务发现负载均衡版本回退存储编排 组件 控制节点(master)-控制平面 APIserver&#xff1a;资源操作…

VMware ESXi 7.0 Update 3n - 领先的裸机 Hypervisor

VMware ESXi 7.0 Update 3n - 领先的裸机 Hypervisor VMware ESXi 7.0 Update 3n Standard & All Custom Image for ESXi 7.0 U3m Install CD 更新日期&#xff1a;Fri Jul 07 2023 10:50:00 GMT0800&#xff0c;阅读量: 4518 请访问原文链接&#xff1a;https://sysin.…

全网最细,Web自动化测试-数据驱动实战,直接通关...

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 在Web自动化测试中…

智能照明控制系统在民用照明节能中的应用

摘 要 &#xff1a;通过智能照明控制系统在某宾馆电气工程中的应用实例&#xff0c;从照明控制的系统结构、设计及系统软件等方面&#xff0c;介绍了智能照明控制系统的功能及实现方式。探讨了智能照明控制系统在民用建筑中的适用范围和发展前景&#xff0c;并由此进一步推断智…

运维小知识(二)——Linux大容量磁盘分区及挂载

centos系统安装&#xff1a;链接 目录 1.&#x1f353;&#x1f353;命令格式化磁盘 2.&#x1f353;&#x1f353;大容量硬盘分区 3.&#x1f353;&#x1f353;自动挂载 整理不易&#xff0c;欢迎一键三连&#xff01;&#xff01;&#xff01; 新系统装完之后&#xff0…

基于appium的常用元素定位方法

目录 一、元素定位工具 1.uiautomatorviewer.bat 2.appium检查器 二、常用元素定位方法 1.id定位 2.class_name定位 3.accessibility_id定位 4.android_uiautomator定位 5.xpath定位 三、组合定位 四、父子定位 五、兄弟定位 一、元素定位工具 app应用的元素使用的是控…

前端实战(四):Nginx代理

Nginx的用处 Nginx的作用主要体现在作为 Web 服务器、负载均衡服务器、邮件代理服务器等方面&#xff0c;其特点是占有内存少&#xff0c;并发能力强&#xff0c;给使用者带来了很多的便利。Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件&#xff08;IMAP/POP3&…

【UE4 C++】06-绑定运动输入(实现前后移动、鼠标转向)

目录 一、WS前后移动 二、鼠标转向 一、WS前后移动 为了让玩家控制的“PlayerCharacter”能够实现前后移动 在“SCharacter.cpp"中添加如下代码 在“SCharacter.h"中添加如下代码 添加轴映射 设置自动控制玩家 此时按下WS键就可以前进后退了。 二、鼠标转向 …

2023年9月DAMA-CDGA/CDGP认证考试报名开始啦!

据DAMA中国官方网站消息&#xff0c;2023年度第三期DAMA中国CDGA和CDGP认证考试定于2023年9月23日举行。 报名通道现已开启&#xff0c;相关事宜通知如下&#xff1a; 考试科目: 数据治理工程师(CertifiedDataGovernanceAssociate,CDGA) 数据治理专家(CertifiedDataGovernanc…