04_control_flow.ipynb
- Lecture 4: Control Flow
- Outline
- What is the Flow of Execution?
- Control Flow Generic Form
- Control Flow I: Repetition
- `while`-loop: Simple Countdown
- `while`-loop: Deconstructing the Header
- `while`-loop: Newton’s method
- `while`-loop: Nested
- Endless loops (Type of Errors III)
- `for`-loop: Simple Countdown
- `for`-loop: Deconstructing the Header
- `for`-loop: Iterable Sequences – Range
- `for`-loop: Iterable Sequences – String
- `for`-loop: Iterable Sequences – Vector
- `for`-loop: Nested
- Control Flow II: Conditional Execution
- Deconstructing the `if`-statement Header
- Alternative Conditional Execution
- Chained Conditional Execution
- Nested Conditional Execution
- Propositional Logic Truths Tables
- Logical Operators
- Summary: Looking Back and Looking Forward
- File 文件
- Edit 编辑
- View 看法
- Run
- Kernel 核心
- Settings 设置
- Help 帮助
Introduction to Programming for Business Analytics
业务分析编程简介 ¶
业务分析编程简介
Murwan Siddig, Stefan Pilot
穆尔万·西迪格、斯特凡·派洛特
Lecture 4: Control Flow¶
第 4 讲:控制流 ¶
Outline¶ 大纲 ¶
- The flow of Execution
执行流程 - Control Flow I: Repetition
控制流程 I:重复- The
while
-loopwhile
循环 - Endless loops (Types of errors II)
无限循环(错误类型 II) - The
for
-loopfor
循环
- The
- Control Flow II: Conditional Execution
控制流二:条件执行
What is the Flow of Execution?¶
执行流程是怎样的? ¶
The flow of execution is the order in which statements are executed.
执行流程是语句的执行顺序。
Execution begins at the first statement of the program (i.e., the first line of code) and statements are run one at a time:
执行从程序的第一条语句(即第一行代码)开始,并且一次运行一个语句:- (
) from left to right.
( ) 从左到右。 - (
) from top to bottom.
( ) 从上到下。
- (
Repetition and conditional execution allow us to control the flow of execution.
重复和条件执行使我们能够控制执行流程。- Repetition: Control how often certain parts of the code are executed.
重复:控制代码某些部分的执行频率。 - Conditional execution: Control whether certain parts of the program are executed.
条件执行:控制程序的某些部分是否被执行。
- Repetition: Control how often certain parts of the code are executed.
Control Flow Generic Form¶
控制流通用形式 ¶
Control Flow statements have the following generic form:
控制流语句具有以下通用形式:
HEADER
BODY
END
Header: Declares the start, and the specifics, of the statement.
标题:声明语句的开始和细节。- Contains a keyword that indicates the type of the statement.
包含指示语句类型的关键字。 - The keyword is followed by another expression depending on the type of the statement.
根据语句的类型,关键字后跟另一个表达式。
- Contains a keyword that indicates the type of the statement.
Body: Contains the (expressions) part of the program being controlled.
主体:包含被控制程序的(表达式)部分。- For readability every expression in the body is indented.
为了便于阅读,正文中的每个表达式都缩进。 - There is no limitation on the number of expressions in the body.
正文中的表达式数量没有限制。
- For readability every expression in the body is indented.
Termination expression: Indicates where the control flow statement ends.
终止表达式:表示控制流语句的结束位置。- The termination expression is done using the keyword
end
.
终止表达式使用关键字end
完成。
- The termination expression is done using the keyword
Note: Indentation is a blank space, before the start of a sentence, produced by a single TAB (⇥).
注意:缩进是句子开头之前的空格,由单个制表符 (⇥) 产生。
Control Flow I: Repetition¶
控制流程 I:重复 ¶
Repetition is when we evaluate certain expressions (usually with some variation), repeatedly, until a specified termination criterion is reached.
重复是指我们反复评估某些表达式(通常带有一些变化),直到达到指定的终止标准。
- Repetition is done using a loop-statement.
重复是使用循环语句完成的。- A loop-statement is an instruction that repeats until the termination criterion is reached.
循环语句是重复执行直到达到终止标准的指令。 - Each round of repetition in a loop-statement is called an iteration.
循环语句中的每一轮重复称为迭代。
- A loop-statement is an instruction that repeats until the termination criterion is reached.
There are two types of loops:
有两种类型的循环:while
-loop: termination condition is based on a Boolean expression (Bool
value).
while
-loop:终止条件基于布尔表达式(Bool
值)。for
-loop: termination condition is based on a range or a sequence of values.
for
-loop:终止条件基于值的范围或序列。
In this lecture, we will focus on while-loops
在本次讲座中,我们将重点关注 while 循环Question: Why do we need to execute the same code repeatedly?
问题:为什么我们需要重复执行相同的代码?Answer: Repetition is very useful in automating repetitive tasks without making errors.
回答:重复对于自动执行重复性任务而不出错非常有用。
while
-loop: Simple Countdown¶
while
-loop:简单倒计时 ¶
Suppose you want to write a program that prints (in each new line) a countdown from 10
to 1
.
假设您要编写一个程序来打印(在每个新行中)从 10
到 1
的倒计时。
- Chances are, you thought of writing something like this:
您很可能想写这样的东西:
What if the countdown starts from 100
? What about 1000000000000
?
如果倒计时从 100
开始怎么办? 1000000000000
怎么样?
while
-loop, we can perform a countdown, from any number, in a concise manner.
while
循环,我们可以以简洁的方式从任意数字执行倒计时。
while
-loop: Deconstructing the Header¶
while
-loop:解构标头 ¶
A while
-loop statement has the following generic form.
while
循环语句具有以下通用形式。
while BOOLEAN_EXPRESSION
BODY
end
- The header consists of the keyword
while
followed by a Boolean expression (BOOLEAN_EXPRESSION
).
标头由关键字while
后跟布尔表达式 (BOOLEAN_EXPRESSION
) 组成。 - The Boolean expression defines the stopping condition.
布尔表达式定义停止条件。- Recall that a Boolean expression evaluates to a
Bool
value: eithertrue
orfalse
.
回想一下,布尔表达式的计算结果为Bool
值:true
或false
。- As long as (while)
BOOLEAN_EXPRESSION
evaluates totrue
, the loop will continue.
只要 (while)BOOLEAN_EXPRESSION
的计算结果为true
,循环就会继续。 - As soon as the
BOOLEAN_EXPRESSION
evaluates tofalse
, the loop will be stopped.
一旦BOOLEAN_EXPRESSION
计算结果为false
,循环就会停止。
- As long as (while)
- Recall that a Boolean expression evaluates to a
The while
-loop can almost be read as English: "While the condition is true evaluate the body of the code. When the condition becomes false stop."
while
循环几乎可以读作英语:“当条件为 true 时评估代码主体。当条件变为 false 时停止。”
while
-loop: Newton’s method¶
while
-loop:牛顿法 ¶
- Loops are often used in programs that compute numerical results by starting with an approximate answer and iteratively improving it.
循环通常用在通过从近似答案开始并迭代改进它来计算数值结果的程序中。 - For example, one way of computing the square root of a number
is Newton’s method where you start with (almost) any estimate and improve this estimate with the following formula:
例如,计算数字 的平方根的一种方法是牛顿法,您可以从(几乎)任何估计 开始,并使用以下公式改进该估计:
indicates the value of the estimate after iterations, and it is updated repeatedly using this formula until it converges to .
表示经过 次迭代后的估计值,并使用该公式重复更新,直到收敛到 。
Suppose you want to write a program that starts with an initial estimate
假设您要编写一个程序,从初始估计
while
-loop: Nested¶
while
-循环:嵌套 ¶
We can nest multiple while
-loops within one another.
我们可以将多个 while
循环嵌套在一起。
Endless loops (Type of Errors III)¶
无限循环(错误类型 III) ¶
Endless loop, also known as an infinite loop, is a loop that continues to run indefinitely.
无限循环,也称为无限循环,是无限期地持续运行的循环。
for
-loop: Simple Countdown¶
for
-loop:简单倒计时 ¶
An alternative way to perform repetition is to use a for
-loop statement.
执行重复的另一种方法是使用 for
循环语句。
for
-loop: Deconstructing the Header¶
for
-loop:解构标头 ¶
The for
-loop statement has the following generic form.
for
-循环语句具有以下通用形式。
for ITERATOR in ITERABLE_SEQUENCE
BODY
end
- The header starts with the keyword
for
.
标头以关键字for
开头。 - The keyword
for
is followed by an iterator variable (ITERATOR
), the keywordin
, and an iterable sequence (ITERABLE_SEQUENCE
).
关键字for
后跟迭代器变量 (ITERATOR
)、关键字in
和可迭代序列 (ITERABLE_SEQUENCE
)。 - An iterable sequence is an ordered collection of elements that we can iterate over.
可迭代序列是我们可以迭代的元素的有序集合。- We are going to discuss iterable sequences based on three data types: Range, String, and Vector.
我们将讨论基于三种数据类型的可迭代序列:Range、String 和 Vector。
- We are going to discuss iterable sequences based on three data types: Range, String, and Vector.
- In the Simple Countdown example, the iterator variable (
countdown
) takes the values1
,2
, ,10
of the iterable sequence1:10
.
在简单倒计时示例中,迭代器变量 (countdown
) 的值为1
、2
、 、10
Note: We could also use =
instead of the keyword in
.
注意:我们还可以使用 =
代替关键字 in
。
for
-loop: Iterable Sequences – Range¶
for
-loop:可迭代序列 – 范围 ¶
- In the previous example, the iterable sequence is given by a range.
在前面的示例中,可迭代序列由范围给出。 - Mathematically, a range is sequence of elements uniquely determined by a combination of the following parameters.
从数学上讲,范围是由以下参数的组合唯一确定的元素序列。start
: the value of the first element in the sequence.
start
:序列中第一个元素的值。step
: the difference (space) between two consecutive values in the sequence.
step
:序列中两个连续值之间的差异(空格)。stop
: (an upper bound on) the value of the last element in the sequence.
stop
:序列中最后一个元素的值(上限)。
- A generic range in Julia has the following form
start:step:stop
.
Julia 中的通用范围具有以下形式start:step:stop
。- When the value of
step
is not specified, it is assumed to be1
.
当未指定step
的值时,假定为1
。
- When the value of
In the following example, we use start=1
, step=3
, and stop=10
1
, 1+3
, 1+3+3
, 1+3+3+3
.
在下面的示例中,我们使用 start=1
、 step=3
和 stop=10
1
, 1+3
、 1+3+3
、 1+3+3+3
。
- Neither
start
,step
norstop
have to be an integer value.
start
、step
和stop
都不必是整数值。
- Neither
start
,step
norstop
have to be a positive value.
start
、step
和stop
都不必是正值。- Note that when
step < 0
the iterable sequence has a descending order. Furthermore,step
can NOT be0
.
请注意,当step < 0
时,可迭代序列具有降序排列。此外,step
不能是0
。
- Note that when
for
-loop: Iterable Sequences – String¶
for
-loop:可迭代序列 – 字符串 ¶
- We can also use
String
values as iterable sequences.
我们还可以使用String
值作为可迭代序列。 - In each iteration, the iterable variable takes the values of the different characters comprising the string.
在每次迭代中,可迭代变量采用组成字符串的不同字符的值。
for
-loop: Iterable Sequences – Vector¶
for
-loop:可迭代序列 – 向量 ¶
- We can also use
Vector
values as iterable sequences.
我们还可以使用Vector
值作为可迭代序列。 - In each iteration, the iterable variable takes the values of the different elements in the vector.
在每次迭代中,可迭代变量采用向量中不同元素的值。
for
-loop: Nested¶
for
-循环:嵌套 ¶
We can nest multiple for
-loops within one another.
我们可以将多个 for
循环嵌套在一起。
Control Flow II: Conditional Execution¶
控制流 II:条件执行 ¶
Suppose we want to perform a countdown from 10
to 1
but only display the value of countdown
when it is even.
假设我们要执行从 10
到 1
的倒计时,但仅在偶数时显示 countdown
的值。
- Checking if a number is even is equivalent to checking if it is divisible by
2
.
检查一个数字是否为偶数相当于检查它是否可以被2
整除。 - We can use the modulus operator
%
which is a binary operator that gives the remainder of dividing two numbers.
我们可以使用模运算符%
,它是一个二元运算符,给出两个数字相除的余数。
- If a
x
is divisible byy
x % y = 0
.
如果x
可以被y
x % y = 0
整除。 - To check if a number is even, we need to check if
x%2 == 0
.
要检查数字是否为偶数,我们需要检查是否x%2 == 0
。
We know how to check if a number is even. But how do we tell just to only print countdown
value if it is even?
我们知道如何检查一个数字是否为偶数。但是我们如何告诉只打印 countdown
值(如果它是偶数)?
- To check if the value of countdown is even before printing it, we can use conditional execution.
要在打印之前检查倒计时的值是否为偶数,我们可以使用条件执行。- Conditional execution provides the ability to check if certain conditions are met before executing the code.
条件执行提供了在执行代码之前检查是否满足某些条件的能力。 - The simplest form of conditional execution is an
if
-statement.
条件执行的最简单形式是if
语句。
- Conditional execution provides the ability to check if certain conditions are met before executing the code.
Putting everything together:
将所有内容放在一起:
Deconstructing the if
-statement Header¶
解构 if
语句头 ¶
An if
-statement has the following generic form:
if
语句具有以下通用形式:
if BOOLEAN_EXPRESSION
BODY
end
- The header consists of the keyword
if
followed by a Boolean expression (BOOLEAN_EXPRESSION
).
标头由关键字if
后跟布尔表达式 (BOOLEAN_EXPRESSION
) 组成。 - The Boolean expression is the condition that determines whether the body of the statement is executed or not.
布尔表达式是判断语句体是否执行的条件。BOOLEAN_EXPRESSION
istrue
BODY
will be executed.
BOOLEAN_EXPRESSION
是true
BODY
将被执行。BOOLEAN_EXPRESSION
isfalse
BODY
will NOT be executed.
BOOLEAN_EXPRESSION
是false
BODY
将不会被执行。
Alternative Conditional Execution¶
替代条件执行 ¶
- What if we would like to run something else if the condition not satisfied (i.e., when
BOOLEAN_EXPRESSION
evaluates tofalse
)? For example:
如果条件不满足(即,当BOOLEAN_EXPRESSION
计算为false
时),我们想运行其他东西怎么办?例如:- Display the value of
countdown
if it is divisible by3
.
如果countdown
能被3
整除,则显示该值。 - Display a message stating that the number is not divisble by
3
and the remainder of the division.
显示一条消息,指出该数字不能被3
和除法的余数整除。
- Display the value of
Alternative execution is a form of conditional execution with two possibilities (alternatives).
替代执行是一种有两种可能性(替代方案)的条件执行形式。
- Each of the two possibilities is called a branch.
这两种可能性中的每一种都称为分支。 - The condition (i.e.,
BOOLEAN_EXPRESSION
) determines which of the two branches is executed.
条件(即BOOLEAN_EXPRESSION
)确定执行两个分支中的哪一个。
Chained Conditional Execution¶
链式条件执行 ¶
For more than two possibilities, we can use chained conditional.
对于两种以上的可能性,我们可以使用链式条件。
- Chained conditional statements can be created by using the keyword
elseif
.
可以使用关键字elseif
创建链式条件语句。
- In chained conditional statements, conditions are checked in the following order:
在链式条件语句中,按以下顺序检查条件:- If the condition in the first branch is
false
, the next branch is checked, and so on.
如果第一个分支中的条件是false
,则检查下一个分支,依此类推。 - If the condition in any of the branches is
true
, the body in the corresponding branch is executed and the statement ends.
如果任何分支中的条件为true
,则执行相应分支中的主体并结束语句。 - If more than one condition is
true
, only the firsttrue
branch is executed.
如果true
有多个条件,则仅执行第一个true
分支。
- If the condition in the first branch is
Nested Conditional Execution¶
嵌套条件执行 ¶
Another way to create a conditional execution statement with more than two possibilities (branches) is to use nested conditional.
创建具有两种以上可能性(分支)的条件执行语句的另一种方法是使用嵌套条件。
- Nested conditional statements can be created by nesting one branch of conditional execution into another.
可以通过将条件执行的一个分支嵌套到另一分支来创建嵌套条件语句。
Propositional Logic Truths Tables¶
命题逻辑真值表 ¶
Each Boolean expression in the previous examples consists of single clause only (countdown%2 == 0
, countdown%3 == 0
, ...
).
前面示例中的每个布尔表达式仅包含单个子句( countdown%2 == 0
、 countdown%3 == 0
、 ...
)。
What if we want to display the value of
countdown
if it is divisible by2
and divisible by3
?
如果我们想要显示countdown
的值,如果它可以被2
整除并且可以被3
整除,该怎么办?What if we want to display the value of
countdown
if it is divisible by2
or divisible by3
?
如果我们想要显示countdown
的值,如果它可以被2
整除或可以被3
整除,该怎么办?In formal logic, we can change the meaning of a statement using the symbols:
在形式逻辑中,我们可以使用符号改变语句的含义:- ¬
NOT ← 不是 - ∧
AND ∧ 和 - ∨
OR ∨ 或
- ¬
Example: Suppose that we have the following statements.
示例:假设我们有以下语句。- P = “The earth spins on its axis”.
P =“地球绕其轴旋转”。 - Q = “The earth is round”.
Q =“地球是圆的”。
- P = “The earth spins on its axis”.
- ¬P
"The earth does not spin on its axis"
ØP “地球不绕轴旋转” - P ∧ Q
"The earth spins on its axis and The earth is round"
P ∧ Q “地球绕其轴旋转,地球是圆的” - P ∨ Q
"The earth spins on its axis or The earth is round"
P ∨ Q “地球绕其轴旋转或地球是圆的”
The truth table for ¬ (equivalently NOT)
← 的真值表(相当于 NOT)
Q | ¬P |
---|---|
True 真的 | False 错误的 |
False 错误的 | True 真的 |
The truth table for ∧ (equivalently AND)
∧ 的真值表(相当于 AND)
P | Q | P ∧ Q P∧Q |
---|---|---|
True 真的 | True 真的 | True 真的 |
True 真的 | False 错误的 | False 错误的 |
False 错误的 | True 真的 | False 错误的 |
False 错误的 | False 错误的 | False 错误的 |
The truth table for ∨ (equivalently OR)
∨ 的真值表(相当于 OR)
P | Q | P ∨ Q P∨Q |
---|---|---|
True 真的 | True 真的 | True 真的 |
True 真的 | False 错误的 | True 真的 |
False 错误的 | True 真的 | True 真的 |
False 错误的 | False 错误的 | False 错误的 |
Logical Operators¶ 逻辑运算符 ¶
In Julia, the symbol for ¬ (NOT) is !
, ∧ (AND) is &&
, and ∨ (OR) is ||
.
在 Julia 中, Ø (NOT) 的符号是 !
,∧ (AND) 是 &&
,∨ (OR) 是 ||
。
It is helpful to view false
0
and true
1
:
查看 false
0
和 true
1
很有帮助:
!p
1-p
.
p && q
p * q
.
p || q
minimum(p+q, 1)
.
The truth table for !p
!p
的真值表
p |
1-p !p |
---|---|
true |
1-1=0 false |
false |
1-0=1 true |
The truth table for p&&q
p&&q
的真值表
p |
q |
p*q p&&q |
---|---|---|
true |
true |
1*1=1 true |
true |
false |
1*0=0 false |
false |
true |
0*1=0 false |
false |
false |
0*0=0 false |
The truth table for p||q
p||q
的真值表
p |
q |
minimum(p+q,1) p||q |
---|---|---|
true |
true |
minimum(1+1,1)=1 true |
true |
false |
minimum(1+0,1)=1 true |
false |
true |
minimum(0+1,1)=1 true |
false |
false |
minimum(0+0,1)=0 false |
To display countdown
only if it is divisible by 2
and divisible by 3
countdown%2 == 0 && countdown%3 == 0
.
仅当 countdown
可被 2
整除且可被 3
countdown%2 == 0 && countdown%3 == 0
整除时才显示 countdown
。
To display countdown
if it is divisible by 2
or divisible by 3
countdown%2 == 0 || countdown%3 == 0
.
Summary: Looking Back and Looking Forward¶
Looking Back:
- The flow of execution is the order in which statements are executed.
- We can control the flow of execution using the
while
-loop,if
,else
, andelseif
statements. - The
while
-loop statement is used for evaluating certain expressions (usually with some variation), repeatedly, until a termination condition is reached. - In a
while
-loop, the termination condition is based on a boolean expression. - The termination condition of a
for
-loop is based on aniterable sequence
. - An
iterable sequence
is an ordered collection of elements that we can iterate over, such asRange
,String
, andVector
. - The
if
,else
andelseif
statements are used to ensure that certain conditions are met before executing the code. - We can also control the flow of execution using the
for
-loop.
Looking Forward:
- How can we group statements that makes our code easier to read and debug?
- How can we eliminate repetitive code in a way that we can ensure that, later, when we make a change in the code, we only make the change in one place?