03 - Conditional A - Python for Everybody Course

freeCodeCamp Concepts
26 Feb 202013:29

Summary

TLDRThis video script introduces the concept of conditional execution in Python, focusing on the 'if' statement as a decision-making tool. It explains the syntax and usage of the 'if' statement, including comparison operators and the importance of proper indentation. The script also touches on nested 'if' statements and the 'if-else' structure, illustrating how to control the flow of a program based on conditions. The emphasis is on clear code structure and the significance of indentation in Python.

Takeaways

  • 👋 Hello and welcome to chapter three, Conditional Execution.
  • 📜 In conditional execution, we meet the if statement, which allows Python to make decisions based on conditions.
  • 🔄 Sequential code executes tasks in order, but with if statements, code can branch and make decisions.
  • ❓ The if statement checks a condition and executes the indented block of code if the condition is true.
  • 📐 Python uses indentation to define the scope of if statements and other blocks of code.
  • 🔢 Comparison operators like <, <=, ==, >=, >, and != are used to form conditions in if statements.
  • 📋 Multiple lines can be included in the indented block of an if statement.
  • ⚠️ Proper indentation is crucial in Python to avoid syntax errors.
  • 🔁 Nested blocks and multiple levels of indentation are supported in Python.
  • ↔️ Two-branch if statements use if and else to provide alternative paths of execution based on conditions.

Q & A

  • What is the main purpose of the 'if' statement in Python?

    -The 'if' statement in Python is used for conditional execution, allowing the program to make decisions based on a given condition, and to execute different blocks of code depending on whether the condition is true or false.

  • How does Python determine whether to execute the code within an 'if' statement?

    -Python checks the condition specified in the 'if' statement. If the condition evaluates to true, the code within the indented block following the 'if' statement is executed. If the condition is false, the code is skipped.

  • What is the significance of the colon (:) in an 'if' statement?

    -The colon (:) in an 'if' statement signifies the end of the 'if' statement declaration and indicates the start of the indented block of code that will be executed if the condition is true.

  • Can the value of a variable be changed by evaluating it in an 'if' statement condition?

    -No, evaluating a variable in an 'if' statement condition does not change the value of the variable. The condition is merely a check and does not have side effects on the variable's value.

  • What are the different comparison operators used in 'if' statement conditions?

    -The comparison operators used in 'if' statement conditions include less than (<), less than or equal to (<=), equal to (==), greater than or equal to (>=), greater than (>), and not equal to (!=).

  • What is the difference between the assignment operator and the equality check in Python?

    -The assignment operator in Python is a single equals sign (=), used to assign a value to a variable. The equality check, on the other hand, uses a double equals sign (==) to check if two values are equal.

  • What is the shorthand syntax for an 'if' statement when there is only one line of code to execute?

    -In Python, if there is only one line of code to execute within an 'if' statement, the line can be written on the same line as the condition, following the colon (:) and indented appropriately.

  • Why is indentation important in Python?

    -Indentation is important in Python because it is used to define the scope and structure of code blocks. Incorrect indentation can lead to syntax errors and affect the execution flow of the program.

  • How does Python handle tabs and spaces for indentation?

    -Python allows the use of spaces for indentation but can get confused if tabs and spaces are mixed. It is recommended to use spaces, typically four spaces per indent level, to avoid inconsistencies and errors.

  • What is a nested block in Python?

    -A nested block in Python is an inner block of code that is indented within an outer block. This allows for complex conditional or looping structures, where the inner block is executed only when the conditions of the outer block are met.

  • What is the difference between a one-branch 'if' statement and an 'if-else' statement?

    -A one-branch 'if' statement executes a block of code only if the condition is true. An 'if-else' statement, on the other hand, provides two branches: one that executes if the condition is true (the 'if' branch), and another that executes if the condition is false (the 'else' branch).

Outlines

00:00

🔍 Understanding the If Statement in Python

This paragraph introduces the concept of conditional execution in Python, focusing on the 'if' statement. It explains how the 'if' statement allows Python to make decisions based on certain conditions, and how indentation plays a crucial role in defining the blocks of code that are conditionally executed. Various comparison operators are discussed, including '<', '<=', '==', '>', and '!=', along with their use in conditional statements. Examples are provided to illustrate how these operators work and how the 'if' statement can control the flow of execution based on different conditions.

05:02

🚨 Importance of Indentation in Python

This paragraph emphasizes the importance of correct indentation in Python, which is syntactically significant. It explains that after an 'if' statement, indentation must be maintained for the code block to be part of the 'if' statement. The standard practice is to use four spaces for indentation, avoiding tabs to prevent confusion. The text editor Atom is recommended for its automatic handling of indentation in Python files. The explanation continues with examples, highlighting how indentation affects the scope and execution of nested blocks, and stressing the need for consistency to avoid syntax errors.

10:02

🔄 Nested and Two-Branch If Statements

This paragraph covers more advanced conditional structures, such as nested 'if' statements and two-branch 'if-else' statements. It shows how 'if' statements can be nested within each other, creating deeper levels of indentation. Examples demonstrate how nested conditions are evaluated and how the flow of execution works within these nested structures. The 'if-else' statement is introduced, explaining how it creates a fork in the road, where one block of code runs if the condition is true, and another block runs if the condition is false. Visualization techniques are suggested to help understand the structure and scope of these conditional blocks.

Mindmap

Keywords

💡Conditional Execution

Conditional execution refers to the ability of Python code to make decisions based on certain conditions. This concept is introduced in the video as a way to have Python code take different actions depending on whether a condition is true or false. An example given is using the if statement to check if a variable x is less than 10 and then executing certain lines of code based on that condition.

💡If Statement

The if statement is a fundamental control structure in Python used for conditional execution. It allows the code to evaluate a condition and execute a block of code only if the condition is true. The video explains that the if statement is followed by a condition and a colon, and the subsequent indented block of code is executed if the condition is true. For example, if x is less than 10, a specific code block will run.

💡Indentation

Indentation in Python is crucial for defining the scope of blocks of code, particularly after control structures like if statements. The video emphasizes that proper indentation is syntactically required in Python, and it determines which statements are part of a given block. For example, an indented block under an if statement will only execute if the if condition is true. Misalignment in indentation can lead to syntax errors.

💡Comparison Operators

Comparison operators are used in conditional statements to compare values. The video lists several comparison operators such as < (less than), <= (less than or equal to), == (equal to), > (greater than), >= (greater than or equal to), and != (not equal to). These operators return boolean values (True or False) and are used to form conditions in if statements. For example, if x == 5 checks if x is equal to 5.

💡True/False Questions

True/False questions in Python are conditions that evaluate to either True or False, determining the flow of control structures like if statements. The video explains that these questions are essential for making decisions in the code. For example, the condition x < 10 evaluates to True if x is less than 10, triggering the associated indented block of code.

💡Blocks of Code

Blocks of code in Python are groups of statements that are executed together, typically defined by indentation levels. The video illustrates that blocks are created by indenting lines of code under control structures like if statements. These blocks execute only if the corresponding condition is met. For instance, in an if statement, the indented block is the code that runs if the if condition is true.

💡De-indent

De-indentation in Python signifies the end of a block of code. The video describes that after an indented block under a control structure like an if statement, returning to the previous indentation level indicates the end of that block. This is crucial for maintaining the structure and flow of the program. For example, after the indented block of an if statement, a de-indented line signifies the continuation of the main code.

💡Else Statement

The else statement is used in conjunction with an if statement to execute a block of code when the if condition is false. The video explains that the else statement follows the if block and is introduced by the keyword else followed by a colon and an indented block. For example, if x is not greater than 2, the else block will execute, providing an alternative code path.

💡Nested Blocks

Nested blocks in Python refer to blocks of code that are indented within other blocks, creating a hierarchy of control structures. The video shows examples of nested if statements, where one if block contains another if block inside it. This allows for more complex decision-making processes within the code. For instance, checking if x is greater than 1 and then within that block checking if x is less than 100.

💡Syntax Errors

Syntax errors occur when the code does not conform to the rules of the Python language, often due to incorrect indentation or use of reserved keywords. The video highlights that improper indentation in control structures like if statements can lead to syntax errors, which prevent the code from running correctly. Ensuring proper indentation and structure is essential to avoid these errors.

Highlights

Introduction to conditional execution and the 'if' statement in Python.

The 'if' statement allows Python to make decisions based on a condition.

Explanation of the syntax and structure of the 'if' statement, including the use of a colon and an indented block.

Conditional execution only runs the indented block if the condition is true; otherwise, it is skipped.

Demonstration of how the value of a variable remains unchanged by the conditional check.

Use of comparison operators for creating 'true-false' questions in conditional statements.

Clarification of the difference between the assignment operator '=' and the equality check '=='.

Introduction of shorthand syntax for single-line conditional execution.

Explanation of how to handle multi-line conditional blocks and the importance of consistent indentation.

The significance of indentation in Python as a syntactical requirement for code blocks.

Guidance on setting up a text editor to use spaces instead of tabs to avoid Python indentation errors.

Illustration of nested 'if' statements and how they are visually represented with increasing indentation levels.

The concept of a two-branch 'if-else' statement as a decision point in the code.

Syntax explanation for the 'if-else' structure and the exclusive execution of either the 'if' or 'else' block.

Visual representation of code blocks using mental or drawn boxes to understand the scope of 'if' and 'else'.

Upcoming discussion on more complex conditional structures in subsequent chapters.

Transcripts

play00:00

- Hello and welcome to chapter three, Conditional Execution.

play00:03

In conditional execution, we meet the if statement.

play00:06

The if statement is where Python can go one way,

play00:09

or another way, and it's the beginning, and sort of

play00:12

our way of making Python make decisions for us.

play00:16

Sequential code, we just, you know, do some things.

play00:19

Sometimes, that's useful, but now we can

play00:20

have our code check something and then

play00:24

make a decision based on that thing.

play00:27

So, the conditional steps in Python

play00:29

are pretty straightforward.

play00:31

The key word that we're going to use is the if statement.

play00:34

And so if is a reserved word, and the if statement has,

play00:38

as part of it, a question that it asks.

play00:40

This is asking if X is less than 10.

play00:43

The colon is the end of the if statement,

play00:45

and then we begin an indented block of text.

play00:48

The way this works, in this particular thing is,

play00:50

this line is the conditional line.

play00:52

If the question is true, the line executes,

play00:55

and if the question is false, the line will skip.

play00:58

And you can think of it the way this is, right?

play01:00

X is five, ask a question, is it 10, or not?

play01:03

These questions do not harm the value of X.

play01:06

If it is, then we run this code, and then

play01:08

we sort of re-join here, and we adjust this next if.

play01:12

And if that's true, we do this code, and then we do there.

play01:14

But, in this case, it's gonna be false,

play01:16

because X is not less than 20,

play01:17

so it just continues down here.

play01:19

If we look at how this works, it runs,

play01:24

it runs this line, then it sees

play01:26

this question, it skips that line.

play01:28

So this line does not run, and so smaller prints out,

play01:31

and finis prints out, okay?

play01:34

And so that's the basic idea of an if statement,

play01:37

and the indentation, when we are done with an if statement,

play01:40

we de-indent back, and there's this little block.

play01:43

This is one if statement, and this is another if statement,

play01:48

and these are the two conditional lines,

play01:49

that either run, or they don't run,

play01:51

depending on the question, and the answer to that question.

play01:55

So, we have a number of different comparison operators

play01:58

that we can use to ask these "true-false" questions,

play02:01

that say, "Is this true?"

play02:03

So, again, we're kind of limited to the keys

play02:06

that were on computer keyboards in the 1940s, and 1950s.

play02:11

Less than, less than or equal to.

play02:13

So, we didn't have fancy math characters,

play02:15

so we just concatenated less than equal

play02:18

to be less than, or equal to.

play02:20

This double equals is asking, "Is this equal to?"

play02:24

So that's a little tricky, the equals

play02:26

sign is that assignment operator.

play02:28

If I was building a language today from scratch,

play02:30

I would probably make assignment be arrow,

play02:32

and the equals question to have an equals.

play02:36

Or, I might say, somewhere I would say,

play02:39

question equals, but I'm not building

play02:42

this language, so that's not up to me.

play02:45

So this is the question, double equals

play02:47

is asking the question, is equal to.

play02:51

Greater than or equal, greater than, and not equal.

play02:54

So this is the exclamation point,

play02:56

is sort of like not equal, so that's how we do not equal.

play03:00

So, we take a look at some of these, and some examples.

play03:04

All of these are going to be true,

play03:05

because of the way X is set.

play03:09

If X is equal to five, that's the question version.

play03:12

That's true or false, it'll execute that.

play03:15

If X is greater than four, it's gonna execute that.

play03:18

If X is greater than or equals five,

play03:19

it's gonna execute that.

play03:21

Here's kind of a short hand, where, if there's only

play03:23

one line in this block, you can kind of pull it up,

play03:25

right on the same line, after the equals.

play03:27

If X is less than six, which it is, true, execute that.

play03:31

Then, if X is less than or equals five, do that.

play03:34

And if X is not equal six, do that.

play03:36

Now, like I said, all of these questions

play03:38

have been carefully constructed so that they are true.

play03:41

Just to show you the syntax of those comparison operators.

play03:45

And you don't just have to have a single

play03:47

line of text in the indented block.

play03:49

And this will be something you're gonna get used to.

play03:52

So, if we indent more than one line,

play03:56

then the conditional code is actually these three lines.

play04:00

So, the idea is, you have an if statement,

play04:02

you come in, you do an indent.

play04:03

And as long as you stay indented, you stay in that if block.

play04:06

If it's false, it just skips all of those.

play04:11

So, the way this is going to execute.

play04:13

X is five, print, before five.

play04:17

Is X equal five, that's the question mark, and that's true.

play04:20

So, it's gonna run all these, and then come back,

play04:23

and then continue on, and then de-indent.

play04:25

So, all of this stuff is running.

play04:28

It says if X equals six, well, that was false.

play04:31

So that skips all of them, so none

play04:33

of these lines of code run, so these actually don't run.

play04:39

And, it says, afterwards six.

play04:41

That's a mistake, those don't run right there.

play04:44

Okay, because X does not equal six.

play04:49

So, indentation is an essential part of Python.

play04:55

We use indentation in lots of programming languages,

play04:57

often to demarcate blocks, to show

play05:01

where blocks start and stop.

play05:03

But in Python, it's syntactically correct,

play05:06

if you make an error, if your indentation is wrong,

play05:09

after an if, you must indent, and you maintain the indent

play05:12

as long as you want to, to be in that same if block.

play05:16

And then, when you're done with the if block,

play05:17

you can reduce the indent.

play05:18

In this rule of indenting, comment lines,

play05:21

and blank lines are completely ignored.

play05:26

So, we're gonna tend to put four spaces.

play05:32

Four spaces ends up being the normal thing that we do.

play05:36

You'll see, all the code that I write

play05:38

has four spaces for each indent.

play05:39

If I go in twice, I use eight spaces.

play05:42

We have this instinct of wanting to hit

play05:44

the tab key to move in four spaces.

play05:46

Now, the problem is that it might look the same

play05:49

on your screen, a tab, and four spaces,

play05:52

might line up the same place, depending on how tabs are set.

play05:56

But Python can get confused by that,

play05:58

so we tend to avoid using actual tabs in files.

play06:03

So most programming text editors, like if you're

play06:04

using Notepad, or TextWrangler, there is a place

play06:08

to set the tabs, to say, "Don't put tabs in this document,

play06:11

"but every time I hit tab, move over four spaces."

play06:14

You hit a tab, but it's like, space, space, space, space.

play06:17

The nice thing about Atom, and this is

play06:19

the text editor we tend to recommend in this class.

play06:21

A, because it works on Windows, Linux, and Mac,

play06:25

but also because it automatically sets this up.

play06:27

As soon as you save your file with .py extension,

play06:30

you can sort of hit the tab key with impunity,

play06:32

and everything works perfectly.

play06:35

But, the key thing here is that Python insists

play06:38

that you get this right, and if you don't get this right,

play06:41

you're going to get indentation errors.

play06:43

They're just another syntax error.

play06:47

So, if you're using something like TextWrangler,

play06:49

or Notepad, run around in the preferences,

play06:54

and you'll find something about expanding tabs,

play06:56

or maybe how many spaces each tab stop is supposed to be.

play07:01

So, you'd check these, and what this really is doing

play07:03

is telling your text editor, "Never put an actual tab

play07:05

"in a document, but somehow simulate

play07:07

"tab stops, using spaces."

play07:10

So, here is a bit of code, it's got nested block.

play07:15

But it gives you the sense that you have to be

play07:17

very explicit when you're reading Python code,

play07:20

of whether the indent is the same between two lines,

play07:24

the same, increased, or decreased.

play07:28

Every time you increase it, you mean something,

play07:30

every time you decrease it, you mean something,

play07:31

and literally, if it stays the same,

play07:33

you mean something, as well.

play07:35

So, if we take a look at this, here,

play07:37

we have a line, and the next line has the same indent.

play07:40

This is an if, with a colon at the end, so we have

play07:42

to increase the indent, and now we're maintaining it.

play07:46

So, these two lines are part of that if,

play07:48

but now we have to de-indent it.

play07:50

So, whether you choose to de-indent this word,

play07:53

or this word, or whatever, where you do

play07:55

this de-indent affects the scope of how far

play07:59

this if statement lasts, right?

play08:01

It lasts up to, but not including,

play08:03

the line that's de-indented to the same level as the if.

play08:07

This is a de-indent, now, we have a blank line,

play08:10

which doesn't matter, and we maintain it.

play08:12

And we have a for, which we'll learn about,

play08:14

in the next chapter, which is a looping structure.

play08:16

Do a for, for runs this five times,

play08:18

it has a colon, and it also expects an indented block.

play08:22

Now, we have what's called a nested block,

play08:24

where we have an if, and a colon, we go in some more.

play08:27

So this is like two indents, right?

play08:29

So, these are one indent, and these are two indents.

play08:32

This is a block, within a block, and then we de-indent.

play08:36

So that means this print is not part

play08:38

of the if statement, but is still part of the for statement.

play08:41

Then we de-indent again, and then that means

play08:44

this print is on the same level as that for statement.

play08:48

So, if you start thinking about this,

play08:51

you wanna be able to start thinking

play08:52

that these blocks are the start of the block,

play08:55

with the colon line, up to, but not including,

play08:59

this line that's been de-indented.

play09:01

So, the for goes this far, right?

play09:04

The for goes up to, but not

play09:05

including the line that's de-indented.

play09:07

The if goes up to, but not

play09:08

including the line that's de-indented.

play09:11

So, as you do this, you'll sort of mentally

play09:14

start drawing these blocks, and pretty soon,

play09:16

you will start constructing them as blocks.

play09:19

It takes a while, but it doesn't take forever.

play09:22

But in Python, unlike other languages, oops ...

play09:32

In Python, unlike other languages,

play09:36

this is very important, and it matters,

play09:39

and you can have syntax errors if you get it wrong.

play09:41

'Cause you're really communicating

play09:43

the shape and the structure of your code,

play09:45

using these indents, and de-indents.

play09:48

We already saw a nested indent,

play09:50

this is a nested if, so you can put an if

play09:52

within an if, and you can go as far deep as you want to go,

play09:55

like Russian dolls, and so, here we have X equals 42.

play09:59

If it's one, we indent one, and then

play10:01

with this next thing we do, these are on the same level

play10:04

of indent, but now we see an if,

play10:06

and it has to indent further.

play10:07

So this is like two in, eight spaces.

play10:11

Then we de-indent back, actually, we'd de-indent back two.

play10:14

So, if you watch this, and you take a look

play10:16

at how this works, it runs to here.

play10:22

Comes in here, the answer is, "Yes, X is greater than one."

play10:24

Prints this, is X less than 100,

play10:26

well, it's 42, so the answer is yes.

play10:28

So, it runs this, and then it kind of continues

play10:30

back to there, and you can also think

play10:32

of drawing boxes around this.

play10:33

This is one if box, and then, within that if box,

play10:37

there is another if box, and again, it's the indent.

play10:41

The indent block, up to, but not including

play10:43

where the de-indent happens.

play10:45

And this here is like two backwards de-indents.

play10:49

So, it ends two blocks, so two blocks

play10:51

are ended by where we place this.

play10:53

We could move this in, or we could move this out.

play10:55

We could have it all the way into here,

play10:57

we could have it to here, or here,

play10:59

and where we put that line depends on how

play11:01

the ends of these blocks are going to work out.

play11:05

One form, that's a one-branch if that we just saw,

play11:10

but then, you could also have what's called a two-branch if.

play11:12

The basic idea of a two-branch if is that

play11:15

you're gonna come in, you're gonna ask a question,

play11:17

and you're gonna go one direction, if it's yes,

play11:19

and another direction, if it's no.

play11:21

We call this an if, then, else,

play11:22

it's kind of like a fork in the road.

play11:24

The way to think about it is, depending

play11:26

on the output of this question, we're gonna pick

play11:28

one or two of these, but if we pick one,

play11:30

the other one's never gonna happen.

play11:31

So, it's like an either, or, we're either

play11:33

gonna go one way, or we're gonna go the other way.

play11:36

But there is no path where we somehow

play11:37

go boot through both of them, that doesn't happen.

play11:41

The syntax that we use for this

play11:44

is what we call the if, then, else.

play11:47

So, the first part is a normal if,

play11:49

with an indent, and then we de-indent,

play11:52

and then this is another reserved word,

play11:53

else, with a colon, and then we re-indent.

play11:56

This is really, ends up being part of a whole block here,

play11:59

and the else is, this is the part that runs if it's false,

play12:04

and this is the part that runs if it's true.

play12:06

The first branch of the if, the first indented block,

play12:09

is what runs if it's true,

play12:11

and then the second indented block

play12:12

is the one that runs if it's false.

play12:15

So, here we go, if X is greater than two,

play12:17

in this case, it's yes, we're gonna print bigger.

play12:20

And then we're gonna be all done.

play12:21

So, we do one, and so, this one did run,

play12:23

and this one did not run.

play12:25

So, basically, with an if, then, else,

play12:27

one of the two branches is gonna run,

play12:29

but there's no case in which both branches run.

play12:32

Again, you sort of draw these blocks

play12:35

around these things, mentally, and in this one,

play12:38

you sort of take, from the if.

play12:39

The else is really part of the block,

play12:41

up to, but not including, that print,

play12:43

which is back, de-indented back

play12:46

to the same level as the if statement.

play12:51

Python is actually one of the more elegant languages,

play12:54

even though, after a while, this indenting,

play12:57

when you get too far in, it gets a little bit complex.

play13:01

This is a good way to visualize this, with these indents.

play13:04

Coming up next, we're gonna talk about

play13:06

some more complex conditional structures.

Rate This

5.0 / 5 (0 votes)

相关标签
Conditional LogicPython CodingIf StatementCode IndentationProgramming BasicsDecision MakingSyntax RulesNested BlocksCode StructureProgramming Tutorial
您是否需要英文摘要?