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

news2024/11/29 18:36:50

文章目录

  • 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


课程简介

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/741376.html

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

相关文章

Linux命令简单学习

文件 输出并覆盖到哪个文件夹 1>文件 正常输出并覆盖 2>文件 输出错误流到某个文件夹 nohup 不强杀不退出 软连接,注意这里需要绝对路径 %% 一个文字的 %%a 当前locale 的星期名缩写(例如&#xff1a; 日&#xff0c;代表星期日)%A 当前locale 的星期名全称 (如&…

wsl 1和wsl 2在形式上的区别

完整的比较请参考&#xff1a; 比较 WSL 版本 | Microsoft Learn 如果是已经安装完成&#xff0c;但安装的是wsl &#xff0c;之后想由 wsl 1升级到wsl 2&#xff0c;请参考&#xff1a;WSL1升级至WSL2_wsl1升级wsl2_goldVitaminC的博客-CSDN博客 在形式上&#xff0c;wsl 1是…

Android AccessibilityService 实现《李跳跳》功能

AccessibilityService&#xff08;无障碍服务&#xff09;是 Android 操作系统中的一个功能&#xff0c;旨在帮助用户具有视觉、听觉或运动上的障碍更轻松地使用设备。它是 Android 提供的一种特殊服务&#xff0c;可以接收设备上发生的各种事件&#xff0c;并提供自定义的反馈…

UWB的技术特点

近年来&#xff0c;超宽带(UWB)无线通信成为短距离、高速无线网络最热门的物理层技术之一。 UWB的产生与发展 超宽带(UWB)有着悠久的发展历史&#xff0c;但在1989年之前&#xff0c;超宽带这一术语并不常用&#xff0c;在信号的带宽和频谱结构方面也没有明确的规定。1989年&a…

2023年了,v-if和v-for的优先级千万别怼错了,可尴尬的...

前言 v-if和v-for到底是谁的优先级更高呢&#xff1f;在vue3版本出来之前你直接说v-for更高&#xff0c;我无法反驳你&#xff0c;但是老哥现在是2023年了&#xff0c;咱可不兴这样回答了&#xff0c;可尴尬的... 剖析 我们都知道&#xff0c;这个v-if是条件渲染&#xff0c;…

flutter开发实战-Running Gradle task ‘assembleDebug‘ 的解决方法

flutter开发实战-Running Gradle task ‘assembleDebug‘ 的解决方法 使用Android studio经常出现Running Gradle task ‘assembleDebug‘问题&#xff0c;记录一下解决方法。 一、在Android目录下更改build.gradle 将repositories中的google(), mavenCentral() repositori…

一、简单的Spring Authorization Server示例代码

需要有一定的OAuth2的基础 需要有一定的Spring Security基础 Spring Authorization Server 官方简介&#xff1a;Spring Authorization Server is a framework that provides implementations of the OAuth 2.1 and OpenID Connect 1.0 个人理解为OAuth 2.1 and OpenID Conne…

用技术指标伦敦金行情走势图

经常有投资者说&#xff0c;伦敦金行情走势图老是涨跌涨跌&#xff0c;抓不准它涨跌的规律&#xff0c;老是被它弄得头昏脑胀。其实看伦敦金行情走势图的方法有很多&#xff0c;最直接的就是使用技术指标。技术指标本来就是投资者为了避免伦敦金行情走势图上价格干扰性波动&…

玩转AI二维码:分享我的漂亮二维码生成秘诀

这几天我又生成了很多漂亮的二维码图片&#xff0c;有了一些感受和想法&#xff0c;特总结此文&#xff0c;分享给大家 先看效果&#xff0c;喜欢的可以继续读下去&#xff08;遵守平台规则&#xff0c;图片已阉割&#xff0c;需要更多图片参数的同学可直接看文章最后&#xf…

Leap AI + Python 开发绘图应用

使用python语言&#xff0c;并借助Leap AI网站的api key&#xff0c;可以轻松实现AI绘图功能。使用时&#xff0c;用户只要输入prompt提示词&#xff0c;几秒钟之内服务器就能生成图片并返回图片的链接地址。开发人员可以利用这个功能开发个性化的绘图软件&#xff0c;或者整合…

后端Linux软件安装大全[JDK、Tomcat、MySQL、Irzsz...持续更新中]

文章目录 前言1.软件安装方式2.安装jdk3.安装Tomcat4.安装MySQL5.安装lrzsz 总结 前言 为了巩固所学的知识&#xff0c;作者尝试着开始发布一些学习笔记类的博客&#xff0c;方便日后回顾。当然&#xff0c;如果能帮到一些萌新进行新技术的学习那也是极好的。作者菜菜一枚&…

Webkit浏览器内核探究——Webkit简介

文章目录 1、什么是Webkit2、Webkit做了什么3、Webkit组成4、应用程序如何利用Webkit的 1、什么是Webkit Wekbit是一个开源的Web浏览器引擎&#xff0c;也就是浏览器的内核。 Apple的Safari, Google的Chrome, Nokia S60平台的默认浏览器&#xff0c;Apple手机的默认浏览器&…

如何监测电路中恶性负载

随着社会的发展和科技的进步&#xff0c;人们对于用电的安全性和稳定性要求越来越高。电路中的恶性负载往往会导致电路故障&#xff0c;甚至引发火灾等严重事故。因此&#xff0c;如何监测电路中的恶性负载成为了一个重要的课题。本文将从恶性负载的定义、监测方法、防范措施等…

【新版系统架构】第十八章-安全架构设计理论与实践

信息安全体系架构设计 信息系统安全设计重点考虑&#xff1a;系统安全保障体系&#xff0c;信息安全体系架构 系统安全保障体系&#xff1a; 安全区域策略的确定&#xff0c;根据安全区域的划分&#xff0c;主管部门应制定针对性的安全策略统一配置和管理防病毒系统&#xff…

【实验一】java基础

1、每个非素数都可以唯一地被分解为若干素数地乘积&#xff0c;请编程对其进行验证。 个人答案&#xff1a; package 实验1;import java.util.Scanner;public class sushu {public static Scanner input new Scanner(System.in);public static void main(String[] args) {Sy…

【工具使用】VS Code 某些文件夹为灰色全局搜索搜不到该文件夹的内容

一&#xff0c;简介 本文主要介绍在VS Code使用过程中&#xff0c;出现文件夹为灰色&#xff0c;且搜索内容时灰色文件夹中的字符串检索不到问题的原因和解决方法&#xff0c;从而提高工作效率。供参考。 二&#xff0c;问题现象 VS Code中部分文件夹显示为灰色&#xff0c;…

找工作第三弹——JS面试题由浅入深

目录 前言理论篇1.js的单线程2.js的数据类型3.js的内存泄漏4.js的宏任务与微任务&#xff08;事件循环机制&#xff09;5.js的作用域与作用域链6.js的闭包7.ES6新增8.原型和原型链8.深浅拷贝9.js的防抖和节流10.js中的this指向11.改变this指向的call、apply、bind12.事件流13.D…

Git 命令提交和分支控制

强大的分支和合并&#xff1a;Git 提供了强大的分支功能&#xff0c;使得开发者可以轻松创建、合并和管理分支。这种灵活性使得团队可以同时进行多个任务和实验性开发&#xff0c;而不会相互干扰 Git 在处理大型代码仓库和版本历史时表现出色。它使用了一种称为“快照”的机制…

数据处理轻松搞定:如何利用PaddleNLP高效处理大规模文本数据

目录 前言一、paddleNLP介绍、特性1-1、介绍1-2、特性介绍 二、paddleNLP安装三、PaddleNLP一键使用3-1、中文分词3-2、词性标注3-3、命名实体识别3-4、依存句法分析&#xff08;DDParser&#xff09;3-5、解语知识标注3-6、文本纠错&#xff08;ERNIE-CSC&#xff09;3-7、文本…

工业园区扬尘噪音监测,该怎么操作?这篇告诉你!

随着工业园区的不断发展和扩大&#xff0c;扬尘和噪声问题成为引起关注的重要环境挑战。工业活动产生的扬尘和噪声不仅对周边居民的生活质量和健康构成威胁&#xff0c;也对环境可持续性产生负面影响。 因此&#xff0c;进行有效的扬尘和噪声监测成为管理者和决策者必须关注和解…