Bummer! This is just a preview. You need to be signed in with a Treehouse account to view the entire video.
Blocks In Python1:13 with Kenneth Love
A more in-depth look at how Python blocks are formatted.
This block formatting is what people are talking about when they mention Python's significant whitespace. The rules for it are fairly simple and should be memorized.
- Blocks start with a line that ends with a colon (':').
- Block content is indented compared to the line that starts the block.
- You de-dent, or remove the indentation, to end the block.
- You must use the same amount of indentation throughout your file. So if one block uses 4 spaces, all of the other blocks must use 4 spaces, too.
If you want more information on Python formatting, read PEP8.
In the second video of this stage, we talked about if and else blocks.
And I thought the word blocks might confuse a
few people, so I want to talk about it more.
In Python, we don't have curly braces to show sections
of code that are related, like many other languages do.
In fact, let's look at a couple of examples.
As you can see, there are curly braces
before and after each chunk, or block of code.
In Python, we don't use curly braces, we use indentation.
[SOUND] So let's see some similar code in Python.
The code that's in the block, in our case,
the code that'll be run when the if condition is
true, or when it's not in the else, is indented
one tab further than the if or the else themselves.
It doesn't have to be tabs, it can be spaces.
It just has to be consistent through the entire script.
You'l get errors about indentation if your code isn't formatted correctly
or things will behave weirdly, so you'll know when something is wrong.
It's also a habit you build over time.
You'll probably even find yourself using
Python's indentation rules in other languages.
Using white space to show code structure might seem like a silly
rule when you first start, but
it definitely increases the readability of Python.
More readable code is easier to debug and revisit months later
You need to sign up for Treehouse in order to download course files.Sign up