Illustration by Duncan Hull

Python — A Journey from being a Beginner to an Expert — part 1

Let’s learn Python in a most enjoyable fashion so that we can solve problems at ease and also share its beauty with others.

Motivation

Almost everyday at work, I code in Python and solve various problems in the field of Data Science & Algorithms. Its structure, flow of code and some very Pythonic way of doing things have attracted me a lot. I feel empowered to use Python as one of the key tools to solve wide range of problems. This progression helped me to learn this language in more depth and that can be seen the way I code now. Hence it’s a right candidate for me to share with you all, and hope you would feel likewise I do when I code in Python.

I will make this as a series of articles starting from basics and slowly move into more advanced topics. But in doing so, I will make sure that from the first article itself we would be able to solve some real world problems and this engagement would go deeper as we move along.

I strongly believe that a programming language how much ever beautiful it is, it is still a tool to solve problems. It’s like English, Bengali, Hindi, French, German and so on. So, if we don’t marry Python with the real world or some theoretical problems then the real beauty of Python will not get exemplified.

So, I will primarily use three areas of problems as we discuss Python in details. They are namely problems from Machine Learning, Algorithms & Data Structures and Application Development. You can see these areas to be verticals and Python is a horizontal which would cut through these verticals. My job would be to make it simple, palatable and interesting. Let’s begin…

Python — Table of Contents

  1. Python Basics (this article)
  2. Python Advanced Concepts
  3. Object Oriented Programming in Python
  4. Implementing Algorithms & Data Structures
  5. … (we will innovate) …

Introduction

Python is a programming language that lets you work more quickly and integrate your systems more effectively. It is popular and highly readable object-oriented language — both powerful and relatively easy to learn.

Some quotes which would get you motivated instantly -

“Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers,” said Cuong Do, Software Architect, YouTube.com.
“Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. Today dozens of Google engineers use Python, and we’re looking for more people with skills in this language.” said Peter Norvig, director of search quality at Google, Inc.

Installation

If you are using Windows or Mac, Python would be installed by default with the operating system. Check to make sure, you have Python installed. If you are using Mac go to terminal or using Windows go to the command prompt and then fire the below line-

python --version

Now I have Python 3.6.4 installed in my system. If you don’t find any then you need to install.

To install, I would recommend two options-

Follow the installation process and you would be good to go. To check, everything is installed properly, do the following in the terminal (Mac) or command prompt (Windows)

python

It will open the Python interpreter, where you can fire Python commands. I just did one to show you how to add 1 + 1 in Python prompt.

You are actually done with the installation. But before we move to the next sections where we learn how to code in Python a few words about the IDE.

Anaconda distribution of Python gives us a good Python interactive editor called Jupyter Notebook. Jupyter stands for three programming languages Julia, Python & R. I will be using this most of the time.

Also I would use another Python editor called Sublime Text. I would highly recommend you to download that. As we go advanced we would be writing lines of codes in a file with extension .py and run them from the command prompt. Also we will be using them as modules and call them from different programs. So a good editor (which doesn’t have to be interactive) is needed. You can download Sublime Text from here.

Many programmers use PyCharm as well and that’s also very good. But I would prefer to use Sublime Text as an editor to write Python codes (.py)

Python Basics

Python is an interpreted language not like Java, C, or C++. In Python the application need not be compiled and built into an executables to run. Python interpreter takes each line of code, interprets & executes it.

Now, let’s use Jupyter Notebook (IDE) to write our first “Hello Word” in Python.

Just, go to terminal or command prompt or if you have the shortcut to Jupyter notebook and fire that up. I am using terminal to start the notebook. Just type jupyter notebook

It opens up an interactive editor to write Python codes. I created a folder called Python-1 where I am going to write the codes. This is how it looks like.

You can see a simple syntax which prints “Hello World”. So, what we will do is start with Functions and in its context we will learn the basics of Python.

  • First we define a function and then we call it. The output is also shown.
  • Now let’s pass an input argument to a function and see the output.
  • So, far my function was printing out things using print statement. Now let the function return some value. Say we want to compute cube of a number.
  • Now before we proceed making our function more involved, let’s see below some behaviors of the function-

Here, in the first piece of code the function doesn’t have a return statement, it only prints the value. So, when we call the function within a print() statement the function prints it (from the definition) but because it doesn’t return anything, so it prints “None” as well which is a datatype in Python.

However, in the second piece of code, the function has a return statement. So, calling it within the print() only returns the computed value.

  • Now, let’s try to default a value for an argument in a function. Say we want to compute a power of any integer value at the same time by-default we want to compute unit power (1th power) of that integer.

Here, in the first example, we just provide one value which Python understands for “n” as “x” is defaulted to 1. In the second example, we pass both the values and value of x gets overridden by the value passed in the function i.e. 2. In the third & fourth example, we passed the named parameters & values which makes the sequence irrelevant.

  • Now, you want to pass variable number of input arguments to the function. Say you want to compute a running total of numbers.

args takes variable numbers of input arguments. However, *args could be *xyz or anything starting with a ‘*’. It’s not a keyword, but it’s a convention to use *args.

  • You can also execute Python program as a main program. Let’s see how -

When this Python code is loaded, the Python interpreter is assigned __name__ property to __main__. It is used and we will see later that when you have one main.py and have other .py files which you are loading as a module in main.py. Then all you need to run main.py from the console, which in turn will run other .py files. I’ll show that as an example in the later part.

  • Inside a function, the scope of a variable is local. But when we use the keyword “global” the scope of that variable (even inside the function definition) becomes global. The following two examples shows the difference.
  • Conditional Structures — We always work with some conditions. Let’s see how conditional structures are defined for Python.
  • Loops help us repeat certain tasks programmatically. Let’s see one of the examples using “while” loop. While the condition is true, the loop will execute and perform the assigned tasks.
  • There is another way to loop through, using a “for” loop.
  • Using “continue” and “break” statements in loops-

Here whenever, “i” is an even number come out of the “if” scope and continue the loop (which means the following print() does not get executed)

Whenever the code encounters “break” statement, it comes out of the loop straightaway.

  • A lot of times when dealing with iterators, we also get a need to keep a count of iterations. Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object.

Now that we have seen how functions in Python work and in doing so we have also seen the data types. Let’s learn them separately.

Built-in Atomic Data Types

Python supports Object-oriented programming so, what it follows is that Python considers data to be the focal point of the problem-solving process. In Python we define a class which is a description of what the data look like (the state) and what the data can do (the behavior). Classes are analogous to abstract data types, and an object is an instance of a class. We will learn Object Oriented Programming in details in our next article but here let’s take this concept into the applications.

Python has two main built-in numeric classes that implement the integer and floating point data types. These Python classes are called -

  • int
  • float
Example of built-in numeric classes in Python

Python has boolean data type, implemented as the Python bool class which represents the Truth value. The possible state values for a boolean object are True and False with standard boolean operators, and , or and not.

Example of built-in boolean classes in Python

Built-in Collection Data Types in Python

Python has number of built-in collection classes.

Lists, strings, and tuples are ordered collections and sets and dictionaries are unordered collections.

  1. Lists : List is an ordered collection of zero or more references to Python data objects. Lists are written as comma-delimited values enclosed in square brackets. The empty list is simply [ ].Lists are heterogeneous, meaning that the data objects need not all be from the same class and the collection can be assigned to a variable.

Lists support a number of methods that will be used to build data structures. They are below-

Number of methods supported by the list
The output of the above code

Often we define a Python function called “range” in conjunction with lists. Range produces a range object that represents a sequence of values. It is described below -

Note : Lists are mutable objects, meaning the same list can be modified (appended, removed, etc.) which we have just seen.

2. Strings : Strings are sequential collections of zero or more letters, numbers and other symbols. We call these as characters. They are denoted within a quotation mark.

A major difference between lists and strings is that lists can be modified i.e. they are mutable but strings can’t be modified i.e. strings are immutable. Let’s see what it means-

You can see that string doesn’t support an item assignment and hence it is immutable.

3. Tuples : Tuples are very similar to lists in that they are heterogeneous sequences of data. The difference is that a tuple is immutable, like a string. A tuple cannot be changed. Tuples are written as comma-delimited values enclosed in parentheses.

4. Sets : A set is an unordered collection of zero or more immutable Python data objects. Sets do not allow duplicates and are written as comma-delimited values in curly braces. Sets are heterogeneous in nature.

5. Dictionary : Dictionaries are an unordered collection of items. It is a collection of associated pair of items, each consisting of a key and a value. Dictionaries are written as a comma-delimited key:value pairs enclosed in curly braces.

I think it is a very powerful data structure and I use them heavily. I will explain it in more details when we do Algorithms & Data-structures why it is a powerful data-structure. Just for now it could be worth mentioning that to search through a dictionary the time complexity is of the order of 1 (i.e. constant which is awesome :) ). Let’s get into this later for sure, for now let’s learn how to use it.

It is important to note that the dictionary is maintained in no particular order with respect to the keys. The placement of the key depends on the concept of “hashing” which we will cover as part of the algorithm study. So, dictionary is also known as hash maps.

Dictionaries have both methods and operators. Let see how they work-

Let’s one see the operators-

Let’s see the methods now -

There are different ways dictionary is unpacked or used in a for loop. We will use the technique we just learnt about dictionary -

What Next ?

In this article we have covered the basic concepts of Python, which is good enough for you to get started or for someone who knows it already to refresh some of the ideas.

In the next series of articles we will use these concepts to build more advanced concepts, get into the object-oriented way of programming and implement lots of algorithms & data-structures.

I hope I have done justice to your time. Stay tuned for more …

But before we bid a good bye, let’s solve a problem using what we have learnt so far.

Check your concepts by solving a problem -

Question : Say there is a bunch of books which you want to catalog by their names, so that they can be easily searched. How would you do that ?

Let’s take this question and give it a mathematical form. Say, the books are stored in a string array.

book = ['The Lord of the Rings', 'The Hobbit', 'Harry Potter and the Chamber of Secrets', 'Black Beauty', 'Kane and Abel', 'To Kill a Mocking Bird', 'Gitanjali', 'Spring and Autumn Annals', 'Rumi Poems']
Book Catalog

The output will look like -

I think now it’s time to say good bye :) see you soon. Take care.

Sources

  1. Learning Python by Joe Marini
  2. Algorithms & Data Structures using Python