In this chapter we explore the ways to create a function and a loop in Python. We may need to create a loop to iterate an action over a list, or to create a function to extract some cases from a dataset. Writing functions is very important to automating data analysis.
Conditional Instructions
if
elif
else
These structures, along with those for creating loops, are indispensable for creating features that allow us to create special instructions, such as performing recursive operations on multiple rows of a dataset, establishing conditions, and so on.
if
In this second case, the condition is not fulfilled, therefore nothing is printed.
if + else
elif
Caution
Python2 and Python3 manage user input differently.
Your result is B
Loops
for
while
continue and break
for
We want to print only the first element of each of the pairs, as shown in Figure 5-2.
while
continue and break
Caution
In Python2 and Python3, range() is used differently.
Extend Functions with Conditional Instructions
map( ) and filter( ) Functions
The lambda Function
As you can see, we can create a similar function in a single line.
Scope
- 1.
Formal parameters: the arguments present in the definition of the function
- 2.
Local variables: which are defined by evaluating expressions in the body of the function and have visibility only within the function itself
- 3.
Global variables: which do not belong to either the first or the second group, but are looked for outside the function
Summary
In this chapter we examined conditional instructions, which are structures used to manage conditions when we create functions. We also looked at extending our functions.