Python: Introduction III

The last part of the Python Introduction and I will cover topics on functions, methods and the packages in Python. For sure, there is a difference between function and method. I revisit my original post which I wrote about the differences between functions and methods. You can read up those before continue here.

User-defined Functions

The simplest way I can explain what is function which I wrote in my original post:

A function is a block of code to carry out a task and it calls by its name. All functions may have zero or many arguments. The arguments are passed explicitly (directly). On the exit of the function, it may or may not return value or values.

There are some examples in this post to explain about functions, how to define a function with and without arguments, uses default value for an argument, uses flexible arguments *args and **kwargs and uses of return statement in the function.

Methods

It is like a function, except it is attached to an object (dependent). A method is implicitly (indirectly) passed to the object for which it is invoked. It may or may not return a value or values. The method is accessible to data that is contained within the class.

For methods examples, I wrote it in this post.

Packages

Think the packages as a directory of Python scripts. Example each .py script is a module. This module specifies functions, methods and types in solving a particular problem. I found a link which explained in detail about packages in Python. Refer here for more reading.

In this part III, I know there are many external links are given, mainly is to reduce re-write of those entries which I wrote them sometimes ago. This blog serves as a place to find the relevant resources for reading and examples which I think it is enough to cover the basic understanding of the functions, methods and packages in Python.

Python: Introduction II

I continue from the Python: Introduction which I wrote it yesterday and it gave the very basic idea of how Python is in term of declaring variables, the data types and how we can store the data in a collection. So. variable, data type and collections. If you missed out or cannot recall them, here is the link to yesterday’s post. There are links to various data types and the collections. I did not want to repeat here.

For the part 2, I have decided to concentrate on writing the introduction to control flows. I think it will be great to have these control flows being taught first before we head to more Data Science orientated topic such as using the package called Numpy and creating our own functions and methods. So, I swapped a little bit in term of syllabus or topic in my writing.

if, elif, else

It is a conditional statement which we can use to match certain conditions. There are few methods to write this statement and it is not always that we need to use elif and else. Let us look at this syntax below:

if condition :
  expression

This syntax has 1 single condition to match only, that is why “if” is being used. Example:

z = 4
if z % 2 == 0 :
  print("z is even")

All control flows has a standard syntax and indentation applied to each of them to mark the beginning to the expression or what should it does when the condition is matched. Therefore, you can see the print() statement is slightly indented. In most IDEs, it is automatically indented when we use the colon (:) sign after the condition, in this case, z % 2 == 0.

The moment we have 1 more condition in our code, if else statement is used. See the syntax below:

if condition :
  expression
else :
  expression

In the else statement, often we do not need to specify the condition within the line because it is understood that when the if statement or condition did not match then it goes to the else statement and execute the code. It looks as though else statement is a default statement. I know in some other programming language, it does have default statement at the end of else statement which say, anything not matches then run default statement.

We can omit this else statement when we do not require to process anything if the first condition does not match. However, sometimes, we might miss out important scenarios of the if statement is skipped. What I meant here is besides being legit that the condition does not match, there is also possibilities of exceptions happened while checking through the conditions. It is recommended to use the else statement as an exception handling, either print out a line in the console or log file. This helps in the debugging procedure.

z = 5
if z % 2 == 0 :
  print("z is even")
else
  print("z is odd")

The above is an example of using if-else statement when there are two conditions, either-or situation. The variable z is 5, hence it goes to the else statement and print out “z is odd”.

Next, if-elif-else statement is used when there are few conditions in the scenario which one may get matched during the condition checking. When the first condition does not match, it goes to the next elif condition to check until it has no matches, it will end at else statement. You can have many elif statements in your codes. Below is the syntax:

if condition :
  expression
elif condition :
  expression
else :
  expression

Example of using the syntax:

z = 3
if z % 2 == 0 :
  print("z is divisible by 2")
elif z % 3 == 0 :
  print("z is divisible by 3")
else :
  print("z is neither divisible by 2 nor by 3")

The output is z is divisible by 3. After each expression, the statement terminates and returns the result. It will not proceed to check whether next condition is matched. With these 3 examples, I hope it gives some ideas about if statement, if-else statement and if-elif-else statement.

while

while statement works by repeating an action until condition is met. It is important to assess the code before running the while statement because if any chances the condition is not met, the statement will keep running and this we call it infinite loop. You have to force to end the application manually. The syntax for while statement:

while condition :
  expression

Example of using the while syntax:

x = 0
while x < 5:
     print(f'The number is {x}')
     x += 1  

The most crucial part here is the variable x which works as a counter to ensure the condition is met. Without this line of code (x += 1 ) the condition is always true and the loop becomes infinite.

This is the output from executing the while statement. When x = 5, it stops and exits from the while statement and does not print out anything.

for

Remember in the previous blog, I mentioned about using Python list (collections)? For statement is a good control flow to iterate (repeat) through the Python list to get each element.

for var in seq :
  expression

Without using for statement, we might want to repeat few times of the print statements to print out the elements inside the Python list below:

fam = [1.73, 1.68, 1.71, 1.89]

print(fam[0])
print(fam[1])
print(fam[2])
print(fam[3])

Although this is a correct syntax, it is not a good practice. Below demonstrates how to use a for statement to iterate through the Python list and print the values out.

for height in fam :
  print(height)

Both of the codes returns the same output.

1.73
1.68
1.71
1.89

For statement works well for any types of collections or even with a string. Below example uses my_string as the “list” and a variable character as the “item_name” to represent the elements inside the list. One by one, it prints out each character in the my_string.

In for statement, we can use the enumerate(), a Python built-in function. enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.

Why is enumerate return a tuple?

When enumerate() returns in a form of enumerate object, it comes in a form of index, value. It is because enumerate() accepts start parameter which is the index value of the counter, by default it is 0. A simple illustration is as below:

enumerate(iterable, start=0)
list = ["eat","sleep","repeat"] 
print(enumerate(list)

When we check the output from the console, it shows as below:

[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]

It starts with an index 0, of course, it can be changed with indicating the index value, such as enumerate(list,1), then the index begins with 1 instead of 0. This enumerate() function may look useful when we want to list the elements from the collections with the index and value.

fam = [1.73, 1.68, 1.71, 1.89]
for index, height in enumerate(fam) :
  print("index " + str(index) + ": " + str(height))

Reusing the above example and now, we have added enumerate(fam) in the for statement instead of using “for height in fam”. Then, in the print() statement, we convert the index value and height value to string and concatenate them. This maybe useful when we want to print out our shopping cart’s items list. Its output shows:

index 0: 1.73
index 1: 1.68
index 2: 1.71
index 3: 1.89

Mastering the use of the control flows can help in the later stage when we go into the data structure section. I have written separate blogs about if-else statements, while and for loops, you can refer to the links below:

Python: Introduction I

It has been a while I stopped learning Python from DataCamp due to my part time classes and assignment, and work commitment. It is not easy to keep track each of them everyday. On top of it, I still have my volunteer work with TechLadies and regularly have to meet up to brainstorm and updates each other.

Today’s topic is very much on Python, definitely. I want to concentrate on my writing in Python for next 2 weeks before I head off for an holiday. I am sure, I will be lazy after my break. It would be great if I can write up something to summarize or reorganize what I have been writing for the past few months on my Python’s learning using DataCamp and Udemy.

Remember my very first day I started learning Python using Udemy, it taught about the installation and I went on to install IntelliJ. Till to date, I hardly using it, most of my time, I am using the online version of Jupyter Notebook. I find it pretty easy to be used. I understood that there are many other IDEs in the market and there is no specific software to be used to code Python. For now, I will just keep it simple for my learning.

How to begin?

After the installation of the python 3, I open the terminal (in Linux) or command prompt (Windows) to go into the Python’s shell by typing the following command:

python

From the terminal or command prompt screen, I can see a return message from Python with the version number. There are Python 2 and Python 3. So, be clear on which version is being used on the machine because the syntax are slightly different from each others.

Checking version

On the very first time, we always want to know if everything we installed for Python works or not. Checking the version, if it is updated, latest and correct version to be used is first time we might want to do with:

python --version

Simple open up your terminal or command line to type the above command on it. On the screen, it may return you the version info such as below:

Python 3.7.0

print(‘Hello World’)

Next, we always start with simple print statement using the built-in function named print() to print out some lines, most often we will print in our first line is “Hello World”. Really, most people who first started learning programming language will have this line printed. I use this function everywhere in my coding and it is very useful. It is just same as the PRINT statement from the SQL server, if you are coming from database background. Using single quote or double quote is not a matter.

print('Hello World!')
print("Hello World!")

Variables and Types

Then, we touch on the variables and types, the important component in most programming languages. Variables and types are interrelated. I discussed about the characteristic of a variable in my first post. Let me have it here too!

  • Specific and case-sensitive name, best practice to use lowercase.
  • Define things that are subject to change.
  • Can be used to store texts, numbers or dates.
  • Cannot start with number.
  • Cannot use space  and symbols in the name, use _ instead.

Then, there are plenty of different data types as well, yes, that is the types I meant here. Remember, different types have different behaviours. I wrote many posts about each of them before. I will link them up whenever we re-visit the topic.

  • Boolean operations: and, or, not (True, False)
  • Numeric types: int, float, complex (number, decimal)
  • Text sequence type: str (string)
  • Sequence type: list, tuple, range
  • Mapping type: dict 
  • Sets type: set
  • None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. It is a null value or no value at all which is different than empty string, 0 or False.

The simplest way to demonstrate how we can create a variable and assign a value to it.

height = 1.67
weight = 180

name = 'Joanne'
gender = 'Female'

isStudent = True

The above shows the height and weight variables in float and int data type, then we have name and gender in string and a variable called isStudent with a Boolean value. In Python, it does not require to declare a variable with any prefix in front of or behind the variable which we can see in Javascript or SQL Server, if you are familiar with those languages. Then, you may ask how does compiler (computer) knows it is of what type of data types.

What is the difference between (=) and (==)?

The single equal sign (=) assigns the value on the right to a variable on the left whereas the double equal sign (==) tests if the two things have the same value. The two things can be a comparison of two variables or a variable with a math operator.

type()

type(height)
type(weight)
type(name)
type(isStudent)

type() is a built-in function which allows us to check the data types of the variables we created with assigned values. type() helps to answer the above question.

That completed the fundamental and basic to code in Python. Now, you know how to do the following:

  • use the print() statement to print texts.
  • use of variables and data types.
  • use the type() statement to print out the data type of a variable.

Probably, now you want to know what is integer, string, Boolean and etc. I have some links here to help out the basic explanation together with examples:

To talk about numbers and strings, it can be another topics by its own as there are many interesting about them such as the use of (+) sign. It is concatenate sign which means it combines two or more variables of same type together. The way number and string use (+) sign also difference than each other. Also, we have to remember that in Python, string and integer cannot use of (+) sign together. It throws exception (error). Exception is a programming jargon means error. There is a topic of exception handling in Python too. In this case, there is string formatting and integer formatting.

Let us move into fundamental part two, Python List.

Python Collections

It is an interesting topic and important part in Python. Almost everyone of us will use Python List in our daily coding life 🙂 It is a collection of values and allows to have different types within the elements, one of the most simplest and easiest collections. When it comes to the word “collection”, Python has four type of collections.

You can read more about the basic of these collection here. Each of them has different characteristics, syntax, structure and usage. Along the way, we use different collections to explain the Python codes and concepts. Below is an example of how list looks like:

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

Declaring a list is same as declare a variable, it just requires to follow the list’s syntax to create one. As mentioned earlier, it can be any data types in a list. So, you can declare a list as below too:

family = ['Anna', 1.73, 'Eddie', 1.68, 'Mother', 1.71, 'Father', 1.89]

We can use the lists above to work with control flows, going through the iteration and/or condition checking, then calculate a value and return a result. I think I will cover it in the next post.

Up to now, this portion is still a basic Python and does not involve any analytics or data science work if you are looking for one.

Day 23: Python Basic Statistics

One of the interesting exercises for Python so far, I want to share my source code for the question I extracted from the online learning website. The datasets for heights and positions are pre-randomized from the website.

  • Convert heights and positions, which are regular lists, to numpy arrays. Call them np_heights and np_positions.
  • Extract all the heights of the goalkeepers. You can use a little trick here: use np_positions == 'GK' as an index for np_heights. Assign the result to gk_heights.
  • Extract all the heights of all the other players. This time use np_positions != 'GK' as an index for np_heights. Assign the result to other_heights.
  • Print out the median height of the goalkeepers using np.median(). Replace None with the correct code.
  • Do the same for the other players. Print out their median height. Replace None with the correct code.
# Import numpy
import numpy as np

# Convert positions and heights to numpy arrays: np_positions, np_heights
np_heights = np.array(heights)
np_positions = np.array(positions)

# Heights of the goalkeepers: gk_heights
gk_heights = np_heights[np_positions == 'GK']

# Heights of the other players: other_heights
other_heights = np_heights[np_positions != 'GK']

# Print out the median height of goalkeepers. Replace 'None'
print("Median height of goalkeepers: " + str(np.median(gk_heights)))

# Print out the median height of other players. Replace 'None'
print("Median height of other players: " + str(np.median(other_heights)))

The output of the above source code execution is,

Median height of goalkeepers: 188.0
Median height of other players: 181.0