Get startedGet started for free

Control flow and loops

1. Control flow and loops

Now that we've covered the basic data types in Python, let's look at how we can write if-statements and loops.

2. Whitespace matters

Before we start, I want to say that whitespace and indentation matter in python. In R, you use curly brackets to denote code blocks, but in Python, you denote code blocks with indentations.

3. Control flow

Control flow statements are used to alter the behavior of your code. To write a conditional if statement in Python, use the if keyword followed by an expression that returns a boolean value, followed by a colon. The code that should get executed based on the boolean expression is always indented. It is common practice to use four spaces to indent this code. The indentation after the colon is mandatory. Everything within this indented block will be executed if the expression evaluates to True. That is the code indented in Python is analogous to the code between the curly brackets in R.

4. if-elif-else

We can add additional conditions in the form of elif and/or else statements. These work just like the else-if and else statements in R. As you can see here on the right, when writing elif and else statements in Python, you break out of the indentation block, and align them with the if statement. Just like in R, you can have multiple elif statements, and they are checked in the order in which they are written. The code block for the first expression that returns true is executed, and the remaining are skipped.

5. Loops

for loops are a great way to execute code for a specific number of times. In Python, you begin the for loop with the for keyword, followed by a temporary variable you can create on the fly. You then specify the "in" keyword followed by the object to loop over and end the line with a colon. Then, just like the if statement you saw in the last slide, you indent the block of code to be executed.

6. Let's practice!

Now it's your turn to write if statements and for loops in Python.