Programming Basics: Statements & Functions: Crash Course Computer Science #12

CrashCourse
17 May 201711:56

Summary

TLDR在这段视频脚本中,Carrie Anne带领我们深入了解了编程语言的基本构建模块。她首先解释了编程语言中的语句和语法,并通过一个赋值语句的例子来说明。接着,她通过一个老式街机游戏的例子,介绍了如何使用变量初始化和控制流语句(如if语句和while循环)来构建游戏逻辑。Carrie Anne还展示了如何将重复的代码块封装成函数,以简化复杂性并提高代码的可重用性。此外,她强调了函数在现代编程中的重要性,说明了如何通过函数的抽象和模块化来构建大型软件。最后,她提到了编程语言中预写的函数集合——库,这些库由专家编写、优化并经过严格测试,为程序员提供了强大的工具。整个脚本以对算法的讨论作为结尾,为下一集内容埋下伏笔。

Takeaways

  • 📝 编程语言的产生是为了抽象化底层硬件细节,让程序员更专注于解决计算问题。
  • 🔑 编程语言中的语句类似于自然语言中的句子,遵循一定的语法规则。
  • 📚 赋值语句是编程中的一种基础语句,用于将值赋给变量。
  • 🔍 变量命名应具有可读性,以便于他人理解代码。
  • 🔁 程序是一系列指令的列表,按顺序执行,类似于食谱的步骤。
  • 🎮 通过构建一个视频游戏的示例,介绍了编程的基础概念。
  • 🚦 控制流语句,如If语句,允许程序根据条件选择不同的执行路径。
  • ⭕️ While循环是一种条件控制循环,会重复执行代码块直到条件为假。
  • 🔄 For循环是一种计数控制循环,会重复执行特定次数的代码块。
  • 🔢 函数可以封装复杂的代码段,通过传入参数来调用,简化代码复用。
  • 📈 通过函数调用函数的方式,可以构建更复杂的程序逻辑。
  • 📚 现代编程语言提供了大量的预写函数,称为库,这些库由专家编写,经过优化和严格测试。
  • 🔍 算法是编程中的重要概念,它定义了解决问题的步骤和方法。

Q & A

  • 编程语言中的语句是什么?

    -编程语言中的语句是单个完整的思想,类似于自然语言中的句子,它遵循一定的语法规则,可以改变程序的行为。

  • 什么是赋值语句?

    -赋值语句是一种编程语言语句,用于将一个值赋给一个变量,例如 'A equals 5' 表示变量 A 被赋值为数字 5。

  • 为什么我们需要使用变量?

    -变量允许程序员存储和操作数据,它们可以被赋予任意有意义的名称,只要在程序中是唯一的,这有助于其他人理解和维护代码。

  • 程序是如何执行指令的?

    -程序按照指令列表从上到下执行,直到完成所有指令,类似于烹饪食谱中的步骤。

  • 控制流语句是什么,它们如何工作?

    -控制流语句用于控制程序的执行流程,不仅仅是简单的从上到下执行。例如,If 语句根据条件的真假来决定执行不同的代码路径。

  • 如何使用If语句来控制程序流程?

    -If 语句通过“如果条件为真,则执行某些代码”的方式来工作。如果条件为假,则可以配合使用 Else 语句来执行替代的代码块。

  • While循环和For循环有什么区别?

    -While循环是基于条件的循环,只要条件为真就会重复执行代码块。For循环是基于计数的循环,它会重复执行指定次数的代码块。

  • 函数在编程中有什么作用?

    -函数允许将代码段封装并命名,可以通过调用函数名来重复使用,这样可以隐藏实现细节,提高代码的可读性和可维护性。

  • 为什么说函数是现代编程的核心?

    -函数使得代码模块化,可以独立开发和测试,适合大型程序和团队协作。它还允许重用代码,避免了重复编写相同的功能。

  • 库(Libraries)在编程中扮演什么角色?

    -库是一组预写的函数,由专家编写、优化并经过测试,提供给所有程序员使用。库可以处理各种常见任务,如网络通信、图形和声音处理等。

  • 算法在编程中的重要性是什么?

    -算法是解决特定问题的明确步骤集合,它们是编程的基础,决定了程序的效率和逻辑结构。良好的算法可以提高程序的性能和可读性。

  • 为什么说抽象是编程中的强大工具?

    -抽象允许程序员隐藏实现细节,只展示操作结果,这样可以简化复杂问题,使得编程更加高效和易于管理。

Outlines

00:00

🖥️ 编程语言的基本构建块

本段介绍了编程语言的出现背景和基本构建块。最初,编程语言被开发出来是为了抽象掉低级细节,使程序员能够更专注于解决计算问题,而不是硬件细节。本段通过一系列语句和示例解释了如何用编程语言表达复杂的命令,比如变量赋值和基本运算。还提到了程序就像食谱一样,按顺序执行指令。最后,引入了控制流语句,特别是 If 语句,用以控制程序的流程,让程序能够根据不同的条件执行不同的代码块。

05:01

🎮 利用循环和函数构建视频游戏

这一段通过设计一个简单的视频游戏来讲解编程的基本概念,如循环和函数。游戏中,Grace Hopper需要捕获越来越多的虫子以防止它们破坏计算机。通过初始化变量和使用控制流语句,如If语句和循环,演示了如何控制程序的逻辑流。介绍了 While 循环和 For 循环的概念和用法,以及如何使用这些循环来重复执行代码片段。最后,引入了函数的概念,演示了如何将代码封装成函数以简化复杂问题的解决方案,并提高代码的重用性和可维护性。

10:02

🔧 函数的抽象力量和编程实践

这一段强调了函数在现代编程中的作用和重要性。通过函数,可以将复杂的代码抽象成简单的函数调用,这使得即便是非常复杂的软件也能够被有效地管理和维护。程序通常被模块化为多个小函数,每个函数负责不同的功能。这种方式不仅使单个程序员能够独立编写整个应用程序,还使得团队成员能够高效协作。此外,现代编程语言包含大量预写的函数库,这些库提供了网络、图形和声音等功能,大大简化了程序员的工作。最后,预告下一集将讨论算法的主题。

Mindmap

Keywords

💡编程语言

编程语言是一种用于编写计算机程序的高级语言,它允许程序员专注于解决计算问题,而不是处理硬件细节。在视频中,编程语言的发展是为了抽象化底层细节,使得编写复杂程序变得更加容易。

💡语句

语句是编程语言中表达完整思想的单个指令,类似于自然语言中的句子。视频中提到,通过使用不同的单词可以改变语句的含义,但必须遵守语法规则。

💡语法

语法是一套规则,它规定了语言中语句的结构和组成。无论是自然语言还是编程语言,都有其特定的语法。视频中通过“我想喝茶”和“I want tea”来说明语法的概念。

💡赋值语句

赋值语句是编程中的一种语句,用于将一个值赋给一个变量。例如,视频中的“A equals 5”就是一个赋值语句,表示变量A被赋予了数值5。

💡变量

变量是编程中用来存储数据的容器,它们可以被赋予不同的值。视频中指出,变量可以被命名为任何有意义的名称,只要它们是唯一的,便于理解代码。

💡程序

程序是一系列指令的列表,类似于食谱中的步骤。视频中通过一个视频游戏的例子来说明程序的执行过程,即从第一个语句开始,按顺序执行,直到结束。

💡控制流语句

控制流语句用于控制程序的执行流程,不仅仅是从上到下简单执行。视频中提到了If语句作为最常见的控制流语句,它根据条件的真假来决定执行哪条路径。

💡条件语句

条件语句是一种基于条件真假来执行不同代码路径的语句。视频中通过“If I am tired, then get tea”来说明条件语句的工作原理。

💡循环

循环是一种编程结构,用于重复执行一段代码直到满足特定条件。视频中介绍了while循环和for循环两种形式,并通过游戏得分的计算来说明循环的应用。

💡函数

函数是编程中的一种抽象,它允许将代码包装成可重用的单元。视频中通过将求幂的代码封装成函数来说明函数的概念,并展示了如何通过函数名调用函数。

💡

库是一组预写的函数,由专家编写、优化并经过严格测试。视频中提到,现代编程语言带有大量的库,这些库几乎涵盖了所有领域,如网络、图形和声音等。

💡算法

算法是解决特定问题的明确步骤集合。虽然视频中没有详细解释算法,但它提到了算法是未来讨论的话题,暗示了算法在编程中的重要性。

Highlights

编程语言的发展是为了抽象化底层硬件细节,让程序员能够更专注于解决计算问题。

编程语言中的语句类似于自然语言中的完整思想,例如“我想要茶”或“正在下雨”。

语法是一套规则,它决定了语言中语句的结构和组成。

赋值语句是编程语言中的一种,用于将一个值赋给一个变量。

变量可以任意命名,但最好的做法是使用有意义的名称以便于他人理解代码。

程序是一系列指令的列表,类似于食谱,从第一条指令开始按顺序执行。

通过使用控制流语句,可以控制程序的执行流程,而不仅仅是从上到下。

If语句是最常见的控制流语句,其基本形式是“如果X为真,则做Y”。

If语句可以与ELSE语句结合使用,ELSE语句作为当表达式为假时的备选方案。

while循环是一种条件控制循环,它会在条件为真时重复执行代码块。

for循环是一种计数控制循环,它会重复执行特定次数的代码块。

函数或方法是一种封装复杂代码的方式,可以通过调用函数名在程序中重复使用。

函数通过参数接收输入,并使用return语句将结果返回给调用它的程序部分。

函数可以嵌套调用,即一个函数中可以调用另一个函数。

现代编程中,将程序模块化为函数不仅允许单个程序员编写整个应用程序,还允许团队高效地协作开发更大的程序。

现代编程语言提供了大量预写的函数,称为库,这些库由专家编写、优化并经过严格测试。

算法是编程中的一个重要概念,将在未来的课程中讨论。

Transcripts

play00:03

Hi, I’m Carrie Anne, and welcome to CrashCourse Computer Science!

play00:05

Last episode we discussed how writing programs in native machine code, and having to contend

play00:09

with so many low level details, was a huge impediment to writing complex programs.

play00:14

To abstract away many of these low-level details, Programming Languages were developed that

play00:18

let programmers concentrate on solving a problem with computation, and less on nitty gritty

play00:22

hardware details.

play00:23

So today, we’re going to continue that discussion, and introduce some fundamental building blocks

play00:28

that almost all programming languages provide.

play00:30

INTRO

play00:40

Just like spoken languages, programming languages have statements.

play00:43

These are individual complete thoughts, like “I want tea” or “it is raining”.

play00:47

By using different words, we can change the meaning; for example, “I want tea” to

play00:51

“I want unicorns”.

play00:52

But we can’t change “I want tea” to “I want raining” - that doesn’t make

play00:54

grammatical sense.

play00:55

The set of rules that govern the structure and composition of statements in a language

play00:59

is called syntax.

play01:00

The English language has syntax, and so do all programming languages.

play01:03

“A equals 5” is a programming language statement.

play01:06

In this case, the statement says a variable named A has the number 5 stored in it.

play01:10

This is called an assignment statement because we're assigning a value to a variable.

play01:13

To express more complex things, we need a series of statements, like “A is 5, B is

play01:18

ten, C equals A plus B”

play01:20

This program tells the computer to set variable ‘A’ equal to 5, variable ‘B’ to 10,

play01:25

and finally to add ‘A’ and ‘B’ together, and put that result, which is 15, into -- you

play01:29

guessed it -- variable C.

play01:31

Note that we can call variables whatever we want.

play01:33

Instead of A, B and C, it could be apples, pears, and fruits.

play01:36

The computer doesn’t care, as long as variables are uniquely named.

play01:39

But it’s probably best practice to name them things that make sense in case someone

play01:42

else is trying to understand your code.

play01:44

A program, which is a list of instructions, is a bit like a recipe: boil water, add noodles,

play01:49

wait 10 minutes, drain and enjoy.

play01:50

In the same way, the program starts at the first statement and runs down one at a time

play01:55

until it hits the end.

play01:56

So far, we’ve added two numbers together.

play01:58

Boring.

play01:59

Let’s make a video game instead!

play02:00

Of course, it’s way too early to think about coding an entire game, so instead, we’ll

play02:04

use our example to write little snippets of code that cover some programming fundamentals.

play02:08

Imagine we’re building an old-school arcade game where Grace Hopper has to capture bugs

play02:12

before they get into the Harvard Mark 1 and crash the computer!

play02:15

On every level, the number of bugs increases.

play02:18

Grace has to catch them before they wear out any relays in the machine.

play02:21

Fortunately, she has a few extra relays for repairs.

play02:24

To get started, we’ll need to keep track of a bunch of values that are important for

play02:27

gameplay, like what level the player is on, the score, the number of bugs remaining, as

play02:32

well as the number of spare relays in Grace’s inventory.

play02:34

So, we must “initialize” our variables, that is, set their initial value: “level

play02:39

equals 1, score equals 0, bugs equals 5, spare relays equals 4, and player name equals “Andre”.

play02:45

To create an interactive game, we need to control the flow of the program beyond just

play02:48

running from top to bottom.

play02:50

To do this, we use Control Flow Statements.

play02:52

There are several types, but If Statements are the most common.

play02:55

You can think of them as “If X is true, then do Y”.

play02:59

An English language example is: “If I am tired, then get tea”

play03:02

So if “I am tired” is a true statement, then I will go get tea

play03:06

If “I am tired” is false, then I will not go get tea.

play03:09

An IF statement is like a fork in the road.

play03:11

Which path you take is conditional on whether the expression is true or false -- so these

play03:15

expressions are called Conditional Statements.

play03:18

In most programming languages, an if statement looks something like …. “If, expression,

play03:21

then, some code, then end the if statement”.

play03:24

For example, if “level” is 1, then we set the score to zero, because the player

play03:28

is just starting.

play03:29

We also set the number of bugs to 1, to keep it easy for now.

play03:32

Notice the lines of code that are conditional on the if-statement are nested between the

play03:35

IF and END IF.

play03:37

Of course, we can change the conditional expression to whatever we want to test, like “is score

play03:40

greater than 10” 5 or “is bugs less than 1”.

play03:43

And If-Statements can be combined with an ELSE statement, which acts as a catch-all if the

play03:46

expression is false.

play03:47

If the level is not 1, the code inside the ELSE block will be executed instead, and the

play03:51

number of bugs that Grace has to battle is set to 3 times the level number.

play03:55

So on level 2, it would be six bugs, and on level 3 there’s 9, and so on.

play03:59

Score isn’t modified in the ELSE block, so Grace gets to keep any points earned.

play04:03

Here are some examples of if-then-else statements from some popular programming languages -- you

play04:07

can see the syntax varies a little, but the underlying structure is roughly the same.

play04:11

If-statements are executed once, a conditional path is chosen, and the program moves on.

play04:15

To repeat some statements many times, we need to create a conditional loop.

play04:19

One way is a while statement, also called a while loop.

play04:22

As you might have guessed, this loops a piece of code “while” a condition is true.

play04:25

Regardless of the programming language, they look something like this:

play04:28

In our game, let’s say at certain points, a friendly colleague restocks Grace with relays!

play04:32

Hooray!

play04:33

To animate him replenishing our stock back up to a maximum of 4, we can use a while loop.

play04:37

Let’s walk through this code.

play04:39

First we’ll assume that Grace only has 1 tube left when her colleague enters.

play04:43

When we enter the while loop, the first thing the computer does is test its conditional…is

play04:47

relays less than 4?

play04:49

Well, relays is currently 1, so yes.

play04:52

Now we enter the loop!

play04:53

Then, we hit the line of code: “relays equals relays plus 1”.

play04:56

This is a bit confusing because the variable is using itself in an assignment statement,

play05:00

so let's unpack it.

play05:01

You always start by figuring out the right side of the equals sign first, so what does

play05:05

“relays plus 1” come out to be?

play05:07

Well, relays is currently the value 1, so 1 plus 1 equals 2.

play05:11

Then, this result gets saved back into the variable relays, writing over the old value,

play05:16

so now relays stores the value 2.

play05:17

We’ve hit the end of the while loop, which jumps the program back up.

play05:21

Just as before, we test the conditional to see if we’re going to enter the loop.

play05:24

Is relays less than 4?

play05:26

Well, yes, relays now equals 2, so we enter the loop again!

play05:29

2 plus 1 equals 3.

play05:30

So 3 is saved into relays.

play05:32

Loop again.

play05:33

Is 3 less than 4?

play05:34

Yes it is!

play05:35

Into the loop again.

play05:36

3 plus 1 equals 4.

play05:38

So we save 4 into relays.

play05:39

Loop again.

play05:40

Is 4 less than 4?....

play05:41

No!

play05:42

So the condition is now false, and thus we exit the loop and move on to any remaining

play05:46

code.

play05:47

That’s how a while loop works!

play05:48

There’s also the common For Loop.

play05:50

Instead of being a condition-controlled loop that can repeat forever until the condition

play05:53

is false, a FOR loop is count-controlled; it repeats a specific number of times.

play05:58

They look something like this:

play05:59

Now, let’s put in some real values.

play06:01

This example loops 10 times, because we’ve specified that variable ‘i’ starts at

play06:05

the value 1 and goes up to 10.

play06:07

The unique thing about a FOR loop is that each time it hits NEXT, it adds one to ‘i’.

play06:11

When ‘i’ equals 10, the computer knows it’s been looped 10 times, and the loop

play06:15

exits.

play06:16

We can set the number to whatever we want -- 10, 42, or a billion -- it’s up to us.

play06:20

Let’s say we want to give the player a bonus at the end of each level for the number of

play06:24

vacuum relays they have left over.

play06:25

As the game gets harder, it takes more skill to have unused relays, so we want the bonus

play06:30

to go up exponentially based on the level.

play06:32

We need to write a piece of code that calculates exponents - that is, multiplying a number

play06:36

by itself a specific number of times.

play06:38

A loop is perfect for this!

play06:40

First lets initialize a new variable called “bonus” and set it to 1.

play06:43

Then, we create a FOR loop starting at 1, and looping up to the level number.

play06:48

Inside that loop, we multiply bonus times the number of relays, and save that new value

play06:52

back into bonus.

play06:53

For example, let’s say relays equals 2, and level equals 3.

play06:57

So the FOR loop will loop three times, which means bonus is going to get multiplied by

play07:01

relays... by relays... by relays.

play07:03

Or in this case, times 2, times 2, times 2, which is a bonus of 8!

play07:07

That’s 2 to the 3rd power!

play07:08

This exponent code is useful, and we might want to use it in other parts of our code.

play07:12

It’d be annoying to copy and paste this everywhere, and have to update the variable

play07:15

names each time.

play07:16

Also, if we found a bug, we’d have to hunt around and update every place we used it.

play07:21

It also makes code more confusing to look at.

play07:23

Less is more!

play07:24

What we want is a way to package up our exponent code so we can use it, get the result, and

play07:28

not have to see all the internal complexity.

play07:30

We’re once again moving up a new level of abstraction!

play07:40

To compartmentalize and hide complexity, programming languages can package pieces of code into

play07:44

named functions, also called methods or subroutines in different programming languages.

play07:49

These functions can then be used by any other part of that program just by calling its name.

play07:53

Let’s turn our exponent code into a function!

play07:55

First, we should name it.

play07:57

We can call it anything we want, like HappyUnicorn, but since our code calculates exponents, let’s

play08:02

call it exponent.

play08:03

Also, instead of using specific variable names, like “relays” and “levels”, we specify

play08:07

generic variable names, like Base and Exp, whose initial values are going to be “passed”

play08:12

into our function from some other part of the program.

play08:15

The rest of our code is the same as before, now tucked into our function and with new

play08:19

variable names.

play08:20

Finally, we need to send the result of our exponent code back to the part of the program

play08:24

that requested it.

play08:25

For this, we use a RETURN statement, and specify that the value in ‘result’ be returned.

play08:29

So our full function code looks like this:

play08:32

Now we can use this function anywhere in our program, simply by calling its name and passing

play08:36

in two numbers.

play08:37

For example, if we want to calculate 2 to the 44th power, we can just call “exponent

play08:41

2 comma 44.”

play08:43

and like 18 trillion comes back.

play08:45

Behind the scenes, 2 and 44 get saved into variables Base and Exp inside the function,

play08:50

it does all its loops as necessary, and then the function returns with the result.

play08:54

Let’s use our newly minted function to calculate a score bonus.

play08:58

First, we initialize bonus to 0.

play09:00

Then we check if the player has any remaining relays with an if-statement.

play09:04

If they do, we call our exponent function, passing in relays and level, which calculates

play09:08

relays to the power of level, and returns the result, which we save into bonus.

play09:12

This bonus calculating code might be useful later, so let’s wrap it up as a function too!

play09:17

Yes, a function that calls a function!

play09:19

And then, wait for it…. we can use this function in an even more complex function.

play09:24

Let’s write one that gets called everytime the player finishes a level.

play09:27

We’ll call it “levelFinished” - it needs to know the number of relays left, what level

play09:32

it was, and the current score; those values have to get passed in.

play09:35

Inside our function, we’ll calculate the bonus, using our calcBonus function, and add

play09:40

that to the running score.

play09:42

Also, if the current score is higher than the game’s high score, we save the new high

play09:46

score and the players name.

play09:48

Finally, we return the current score.

play09:50

Now we’re getting pretty fancy.

play09:51

Functions are calling functions are calling functions!

play09:54

When we call a single line of code, like this the complexity is hidden.

play09:57

We don’t see all the internal loops and variables, we just see the result come back

play10:01

as if by magic…. a total score of 53.

play10:04

But it’s not magic, it’s the power of abstraction!

play10:07

If you understand this example, then you understand the power of functions, and the entire essence

play10:11

of modern programming.

play10:13

It’s not feasible to write, for example, a web browser as one gigantically long list

play10:17

of statements.

play10:18

It would be millions of lines long and impossible to comprehend!

play10:21

So instead, software consists of thousands of smaller functions, each responsible for

play10:25

different features.

play10:27

In modern programming, it’s uncommon to see functions longer than around 100 lines

play10:30

of code, because by then, there’s probably something that should be pulled out and made

play10:34

into its own function.

play10:35

Modularizing programs into functions not only allows a single programmer to write an entire

play10:39

app, but also allows teams of people to work efficiently on even bigger programs.

play10:44

Different programmers can work on different functions, and if everyone makes sure their

play10:47

code works correctly, then when everything is put together, the whole program should

play10:51

work too!

play10:51

And in the real world, programmers aren’t wasting time writing things like exponents.

play10:56

Modern programming languages come with huge bundles of pre-written functions, called Libraries.

play11:01

These are written by expert coders, made efficient and rigorously tested, and then given to everyone.

play11:06

There are libraries for almost everything, including networking, graphics, and sound

play11:10

-- topics we’ll discuss in future episodes.

play11:12

But before we get to those, we need to talk about Algorithms.

play11:16

Intrigued?

play11:17

You should be.

play11:18

I’ll see you next week.

Rate This

5.0 / 5 (0 votes)

相关标签
编程基础控制流函数抽象变量初始化条件语句循环结构游戏开发算法理解编程逻辑软件工程CrashCourse