Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learn Python by Building Data Science Applications

You're reading from  Learn Python by Building Data Science Applications

Product type Book
Published in Aug 2019
Publisher Packt
ISBN-13 9781789535365
Pages 482 pages
Edition 1st Edition
Languages
Authors (2):
Philipp Kats Philipp Kats
Profile icon Philipp Kats
David Katz David Katz
Profile icon David Katz
View More author details

Table of Contents (26) Chapters

Preface Section 1: Getting Started with Python
Preparing the Workspace First Steps in Coding - Variables and Data Types Functions Data Structures Loops and Other Compound Statements First Script – Geocoding with Web APIs Scraping Data from the Web with Beautiful Soup 4 Simulation with Classes and Inheritance Shell, Git, Conda, and More – at Your Command Section 2: Hands-On with Data
Python for Data Applications Data Cleaning and Manipulation Data Exploration and Visualization Training a Machine Learning Model Improving Your Model – Pipelines and Experiments Section 3: Moving to Production
Packaging and Testing with Poetry and PyTest Data Pipelines with Luigi Let's Build a Dashboard Serving Models with a RESTful API Serverless API Using Chalice Best Practices and Python Performance Assessments Other Books You May Enjoy

Loops and Other Compound Statements

In the previous chapter, we learned how to create and operate on data structures. Now, let's discuss how to operate on them effectively.

We will first cover loops—a special type of compound statement (code that compounds other code, just like functions)—that allows the same code to be run over and over—any number of times, or even indefinitely. After loops, we will discuss if-else statements—logical forks that allow us to split code execution based on test results. Finally, we will cover two less popular, but still very useful, clauses—try, which helps to save the day if something goes wrong (an error is raised) within the code, and with , which helps to close the context safely (for example, close the file correctly).

Hence, this chapter will cover the following topics:

  • Understanding if, else, and elif...

Technical requirements

Understanding if, else, and elif statements

Conditional execution is one of the cornerstones of programming. It allows us to execute one code, but not the other, depending on the condition. This condition is described in Python as an if statement. It is pretty self-explanatory: code within the scope will be executed if the condition is met:

if rain is True:
agenda = 'Stay Home'

Here, if the rain variable is true, the agenda is to stay at home.

This statement can make functions more flexible. In the following example, if b is equal to 0, we can't use it as a denominator, so we can check the value, and return None instead. As return terminates all the code of the function, the division does not happen:

def percentage(a, b):
if b == 0:
return None

return round(a / b, 2)

On many occasions, there could be more than one outcome of the logical fork. If...

Running code many times with loops

Loops are compound statements that repeat the code within them many times, a specific number of times, until a certain test is met, or even indefinitely. By doing so, loops enable us to incrementally update the values or traverse over a collection of values, computing something for each of them. For example, the factorization function we wrote at the end of the last chapter to illustrate recursing can be written with loops, multiplying the value by the next value in the row each time.

Python loops have two main forms—for and while. Let's now look at them in detail.

The for loop

The for loop is the classical form of the loop—it literally goes over an iterable (collection...

Handling exceptions with try/except and try/finally

try/except is here to save the day if some code fails. We've seen errors before. In Jupyter, they appear as text highlighted in red when we do something wrong. In many cases, however, it is hard to predict whether an error will occur—for example, if we're working with an external database or service, there is no guarantee that everything will work as it should all the time. Before we learn how to mitigate those potential exceptions, let's briefly review what the exception is and why we should create our own ones.

Exceptions

But what are the exceptions? You can think of them as warning messages letting us know about computation issues and halting the...

Understanding the with statements

Last but not least, the with statement is usually used with any kind of connections or managed resources such as file handles. Consider the following example:

with open('./text_file.txt', 'r') as file:
data = file.read()

print(data)

Here, we use a with clause together with the open() function. The open function returns a file-like object that has __enter__ and __exit__ methods, representing the opening and closing of the file. Both can be used directly, but the file needs to be closed properly once it is opened. The close() function along together with the with clause does exactly that – it opens an object, and makes sure it is closed (using those two methods) at the end. Essentially, it is the equivalent of the following try/finally statement:

try:
file = open('./text_file.txt', 'r').__enter__...

Summary

In this chapter, we covered a wide spectrum of compound statements. In particular, we covered the if clause, which allows us to build logical forks – parts of code that are executed if a condition is met. We also discussed two types of loops, which allow us to run the same code multiple times, in repetition. Lastly, we covered try/except/finally and with clauses, which gives us options in terms of catching errors on the fly, without halting execution of the script, and guaranteeing that given connections, such as open files, are handled properly.

This chapter concludes our tour of the basics of the language. By no means have we covered it all! However, from now on, we will depart from the sandbox example and start writing code that is actually useful.

In the next chapter, we'll start communicating with external APIs and process data. See you there!

...

Questions

  1. Can the if clause work with multiple (more than two) logical branches?
  2. What is the difference between for and while loops?
  3. How can I loop through multiple (two or more) arrays of the same length? Or of different lengths?
  4. Why do we need exceptions? How can I catch one?
  5. What is the difference between finally and except?
  6. When should the with clause be used?
  7. How can I use with on a custom object?

lock icon The rest of the chapter is locked
You have been reading a chapter from
Learn Python by Building Data Science Applications
Published in: Aug 2019 Publisher: Packt ISBN-13: 9781789535365
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}