Among the ingredients that make a programming language powerful are control flow statements. The Python
for loop is one such control flow statement. The
if statement is another one. In this tutorial, you’ll learn about both!
Python For Loop
The world around us is built around repetition. The sun goes up every morning and after winter comes spring. As coders, we model and simulate the real world and create our own worlds with our own laws and repetitions. Suppose you want to program a web server that repeats forever the following behavior. Wait for a user request and answer it. How can you program the web server to repeat this behavior thousands of times?
The naive approach is to put the sequence of steps into the source code itself. In other words, copy and paste the sequence of steps thousands of times. Yet, repeated code is redundant, hard to read, debug, and maintain. As programmers, we should avoid redundant code at all costs.
What is the output of this code snippet?
words = ['cat', 'mouse'] for w in words: print(len(w))
The Python for loop statement is a way out of redundant code. You write code only once and put it into different contexts. In other words, the loop variable (e.g.
w in the code) accounts for the different contexts of loop executions. For example, in the puzzle word
w is first
'cat' and second
for loop repeats execution of the code body for all elements in a sequence. Then, it iterates over all sequence elements in the order of the sequence. In the code, we print out the length of each word in the sequence.
Are you a master coder?
Test your skills now!
Python While Loop
In this case, you’ll use the while loop that is more powerful because you can execute the loop body forever.
For example, a webserver internally executes a while loop that never stops (the server executes forever). Each time a new user requests the web page, the webserver serves the page and waits for the next user.
Here’s an example of a while loop that executes forever:
# Your fancy web app while True: print("<html> ... </html>") ''' <html> ... </html> <html> ... </html> <html> ... </html> <html> ... </html> ... '''
The while loop executes the loop body as long as the Boolean condition directly after the while statement evaluates to
True. In the example, this is always the case. Therefore, the program executes forever until you terminate it forcefully.
But you can also use more complicated while conditions as shown in the next example:
# Puzzle x = "hello world" while not len(x) == 5: x = x[1:] print(x)
What’s the output of this code puzzle? Find the solution below(**).
Python If Statement
The if statement allows you to control the program execution—entering different execution branches in different program states. Here’s an example:
half_truth = 21 if 2 * half_truth == 42: print('Truth!') else: print('Lie!') # Truth!
The if condition
2 * half_truth == 42 generates a result that either evaluates to
False. In the former case, it enters the first branch
print('Truth!'). In the latter case, it enters the second branch
print('Lie!'). As the expression evaluates to
True, the first branch is entered, and the shell output is
Interestingly, you can use any Python object as an if condition. Why? Because each Python object has an implicitly associated Boolean value. For example, many Python coders pass list objects into the if condition. An empty list evaluates to
False, and a non-empty list evaluates to
True. Here’s an example:
lst =  if lst: print('Full!') else: print('Empty!') # Empty!
If you don’t need to enter the else branch, you can simply skip it:
if 2+2 == 4: print('FOUR') # FOUR
The output is only printed if the if condition evaluates to
True. Otherwise, the code has no side effects because it’s simply skipped by the execution flow.
On the other hand, you may have a situation where more than two conditions can apply. In this case, you can use the
x = input('Your Number: ') if x == '1': print('ONE') elif x == '2': print('TWO') elif x == '3': print('THREE') else: print('MANY')
The code takes your input and compares it against strings
'3'. In each case, a different output is printed. Only if no string applies, the final branch is entered, and the output is
Puzzle Output (**):
x = "hello world" while not len(x) == 5: x = x[1:] print(x) # world
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.