© Valentina Porcu 2018
Valentina PorcuPython for Data Mining Quick Syntax Referencehttps://doi.org/10.1007/978-1-4842-4113-4_5

5. Conditional Instructions and Writing Functions

Valentina Porcu1 
(1)
Nuoro, Italy
 

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

Conditional instructions are structures used to manage conditions when we create a function. Depending on certain values or the results of an operation, we implement different actions on our data using the following 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

Let’s look at some examples of the uses of if:
>>> x = 5
>>> y = 7
>>> if x < y:
...        print("x is less than y")
>>> x is less than y
Now let’s create objects and set a condition. The previous condition is fulfilled and the required sentence is printed.
>>> z = 700
>>> h = 20
>>> if h > z:
...        print("h is bigger than z")

In this second case, the condition is not fulfilled, therefore nothing is printed.

if + else

if can also work with else to give us more flexibility. For instance,
>>> z = 700
>>> h = 20
>>> if h > z:
...        print("h is bigger than z")
...else:
...        print("h is not bigger than z")
h is not bigger than z

elif

We reach maximum flexibility for if by using elif , which establishes intermediate conditions in a function. For instance, let’s create a program that asks us what our score was. We then fit this into a scoring class, which we call result. Let us proceed as follows using Python2 (we might need to enter the encoding):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
>>> print "Enter your score: "
>>> mark = int(raw_input())
>>> if 90 <= mark <= 100:
...    output = "A"
...elif 80 <= mark <= 89:
...    output = "B"
...elif 70 <= mark <= 79:
...    output = "C"
...elif 60 <= mark <= 69:
...    output = "D"
...elif mark <= 59:
...    output = "F"
...else:
...    print "I don't understand, try again"
...print "Your result is " + output
We can save the script (I named it mark2, and you can find it in the code folder or create by yourself by opening a .txt file and renaming it with a .py extension) and proceed by running it from Jupyter as shown in Figure 5-1.
../images/469457_1_En_5_Chapter/469457_1_En_5_Fig1_HTML.jpg
Figure 5-1

Running mark2 in Jupyter

Caution

Python2 and Python3 manage user input differently.

In Python 3, we simply use input() instead of raw_input():
>>> print("Enter your score: ")
>>> score = int(input())
>>> if 90 <= score <= 100:
...    output = "A"
...elif 80 <= score <= 89:
...    output = "B"
...elif 70 <= score <= 79:
...    output = "C"
...elif 60 <= score <= 69:
...    output = "D"
...elif score <= 59:
...    output = "F"
...else:
...    print("I don't understand, try again")
...print("Your result is " + output)
Enter your score:
80

Your result is B

Loops

Loops identify structures that allow you to repeat a certain portion of code, for a number of times or under certain conditions. The most important instructions in Python that allow you to tweak actions are
  • for

  • while

  • continue and break

for

The Python instruction for allows the definition of iterations. for is an iterator, so it is able to go through a sequence and perform actions on it, or perform operations. The format of for instructions is as follows:
for item in object:
        run action on item
For instance,
# we create an object (in this case, a tuple) and print every element
>>> x = (1,2,3,4,5,6,7)
# check the type of object
type(x)
<type 'tuple'>
>>> for n in x:
...        print(n)
1
2
3
4
5
6
7
# we create an object and, for each element of the object, we print a sentence together with the element
>>> x = (1,2,3,4,5,6,7)
>>> for n in x:
...    print("this is the number", n)
("this is the number", 1)
("this is the number", 2)
("this is the number", 3)
("this is the number", 4)
("this is the number", 5)
("this is the number", 6)
("this is the number", 7)
# we can also print the elements of a string
>>> string1 = "example"
>>> for s in string1:
...        print(s)
e
x
a
m
p
l
e
>>> for s in string1:
...        print(s.capitalize())
E
X
A
M
P
L
E
>>> for s in string1:
...        print(s*5)
eeeee
xxxxx
aaaaa
mmmmm
ppppp
lllll
eeeee
What happens if, for example, we have a list that contains sublists and we want to print some of its elements? Let’s look at an example:
# we create a list containing pairs of elements
>>> list1 = [(5,7), (9,2), (2,3), (14,27)]
>>> list1
[(5, 7), (9, 2), (2, 3), (14, 27)]

We want to print only the first element of each of the pairs, as shown in Figure 5-2.

>>> for (el1, el2) in list1:
...     print el1
5
9
2
14
../images/469457_1_En_5_Chapter/469457_1_En_5_Fig2_HTML.jpg
Figure 5-2

Print the first element only

If we want to, we can also carry out operations on couples—for example,
>>> for (el1, el2) in list1:
...        print el1+el2
12
11
5
41
# In Python3, we add parentheses to the function print()
>>> for (el1, el2) in list1:
...        print(el1+el2)
12
11
5
41
As for dictionaries, we can proceed as follows:
>>> dict1 = {"k1":1, "k2":2, "k3":3}
>>> for key, value in dict1.items():
...     print("the key value " + str( key ) + " is " + str( ...value ))
the key value k3 is 3
the key value k2 is 2
the key value k1 is 1
Clearly, we can also print a single key or the only value:
# python2
>>> for key, value in dict1.items(): print key
k3
k2
k1
>>> for key, value in dict1.items(): print value
3
2
1
# python3
>>> for key, value in dict1.items(): print(key)
k3
k2
k1
>>> for key, value in dict1.items(): print(value)
3
2
1

while

The instruction while executes actions if a certain condition is met. It is used in cases when we do not know with certainty how many times an iteration has to be processed, so we run it until it satisfies a specific condition.
# Python2
>>> x = 1
>>> while x < 5:
...     print x
...     x = x+1
1
2
3
4
# Python3
>>> x = 1
>>> while x < 5:
...     print(x)
...     x = x+1
With the while instruction, it is necessary to be careful not to start an infinite loop, which would then require you to force the program to close. For instance, if we set this type of loop we will get a list of “1” until we stop the execution :
# nb: don't run
>>> x = 1
>>> while x < 2:
...        print x
Let’s look at another example of while:
# Python2
>>> y = 1
>>> while y < 10:
...     print "the y value is " ,y
...     y = y +1
the y value is  1
the y value is  2
the y value is  3
the y value is  4
the y value is  5
the y value is  6
the y value is  7
the y value is  8
the y value is  9
# in this case, we print a sentence with each of the y values, which increases at each new step

continue and break

continue and break are two instructions that allow you to end a cycle or to continue passing to the next iteration. Let’s look at an example of continue:
# we create a list
>>> list1 = ['item1', 'item2', 'item3', 'cat', 'item4', 'item5']
# we create a for loop that prints each items in the list
>>> for item in list1:
...    if item in list1:
...        if item == 'cat':
...            continue
...    print(item)
item1
item2
item3
item4
item5
# the for loop must skip the element that is unlike the others; to get this result, we use continue, thus "skipping"' the element
break works in a similar way, although unlike continue, it interrupts the for cycle:
>>> for item in list1:
...    if item in list1:
...        if item == 'cat':
...            break
...    print(item)
item1
item2
item3
range()
As we have seen for lists, range() is a function in Python2 (in Python3, it is a built-in method) and not a conditional instruction. This function allows you to create lists bounded by an upper limit and a lower limit (a range).
# Python2
# we create a list of numbers from 1 to 49 (included)
>>> list = range(1, 50)
>>> list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
# check the object type
>>> type(list)
<type 'list'>
# we create a list of numbers from 30 to 44 (included)
>>> list2 = range(30, 45)
>>> list2
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]
# if we do not specify the lower limit, but only the upper limit, the list starts at 0:
>>> list3 = range(14)
>>> list3
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
We can also add the range we want to include, for example, of three elements, as the third argument : so the first parameter will be the number from to start with (20), the second the end of the list (40) and the third will be the step (3)
>>> list4 = range(20, 40, 3)
>>> list4
[20, 23, 26, 29, 32, 35, 38]
# this way, we can, for example, create lists for odd or even numbers
>>> range(0,10,2)
[0, 2, 4, 6, 8]
>>> range(1,10,2)
[1, 3, 5, 7, 9]
We can also create two objects and require a range between the two objects. For example,
>>> x = 17
>>> y = 39
>>> range(x, y)
[17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38]
Also, we can incorporate lists created with range()within another loop. For example,
>>> for el in range(1,10): print el
1
2
3
4
5
6
7
8
9
# for example, instead of passing an object in the for loop, we pass a list created with range()

Caution

In Python2 and Python3, range() is used differently.

To get a list of numbers in Python3 , we write
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(2,10))
[2, 3, 4, 5, 6, 7, 8, 9]
# if we use the same name as Python2, we get this result in Python3
>>> range(10)
>>> range(0, 10)

Extend Functions with Conditional Instructions

The conditional and loop instructions we just studied allow us to extend our capabilities in writing functions. Let’s look at an example:
# we create an example function
>>> def ex1(x):
...        y = 0
...        while(y < x):
...            print('Add one!')
...            y = y + 1
...        return('Stop now!')
>>> ex1(0)
'Stop now!'
ex1(5)
Add one!
Add one!
Add one!
Add one!
Add one!
'Stop now!'

map( ) and filter( ) Functions

The map() function takes two objects, a function, and a sequence of data, and applies the function to the data sequence. Here is an example:
# map()
# Python2
# we create a function that squares a number
>>> def square(x):
...      return x*x
# check if the function does what it is supposed to do
>>> square(9)
81
# now let us create a list of numbers
>>> num = [2, 5, 7, 10, 15]
# we apply the map() function to our list to square all list numbers with only one operation
>>> map(square, num)
[4, 25, 49, 100, 225]
# Python3
# we use the list() function to get the desired result, as we did with range()
>>> list(map(square, num))
The filter() function applies a function to an object and returns the results that meet a particular criterion. Let’s create a second list of numbers:
>>> num2 = range(1,15)
>>> num2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
# we create a function that allows us to distinguish even numbers
>>> def even(x):
...        if x % 2 == 0:
...                return True
...        else:
...                return False
# we apply the filter() function to the function even() and a list of numbers, like num2
>>> filter(even, num2)
[2, 4, 6, 8, 10, 12, 14]

The lambda Function

The lambda function is a Python construct with a particular syntax that simplify a function construction allowing us to reduce one function in one line, thus making the code more simple but less powerful than creating a function with the construct def. For instance, to create a function that squares a number, we did this:
# we create a function that squares a number
>>> def square(x):
...      return x*x
# we check if the function does what it is supposed to do
>>> square(9)
81
Now we use the lambda function to create the same function:
>>> sq2 = lambda x : x*x
>>> sq2(127)
16129

As you can see, we can create a similar function in a single line.

Let’s return to a list of numbers:
>>> num =[2, 5, 7, 10, 15]
# now we use the second function we created to apply the function to the entire list
>>> map(sq2, num)
[4, 25, 49, 100, 225]
# it is not necessary to create a function; we can integrate the lambda function directly within the process. In this case, if we want to use the same lambda function over there, we will rewrite it instead than recalling it by its name
>>> map(lambda x: x*x, num)
[4, 25, 49, 100, 225]

Scope

When writing a function, we can define an object within the function itself or relate to an object created externally by the function. In the first case, we speak of a global variable; in the second case, a local variable. With respect to a function, we therefore have three elements:
  1. 1.

    Formal parameters: the arguments present in the definition of the function

     
  2. 2.

    Local variables: which are defined by evaluating expressions in the body of the function and have visibility only within the function itself

     
  3. 3.

    Global variables: which do not belong to either the first or the second group, but are looked for outside the function

     
So far we have worked with global variables, defining them first and then applying various operations through some functions. In the following case, however, let’s define a global test variable external to the function and a local test function within the function. The function calls the local variable.
>>> test = "hello"
>>>     def fun1():
 ...       test = "hi"
 ...       print(test)
>>> fun1()
hi
In this next case, however, let’s refer to a variable external to the function itself. In so doing, the calculation is performed correctly:
num1 = 5
def fun2():
        global num1
        num2 = num1 + 1
        print(num2)
fun2(num1)
6

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.249.210