Read an Excerpt
CHAPTER 1
Introduction
1.1 What is Python?
There are plenty of ways which we could begin this section with. We decided that a straightforward approach to understand what Python is, is to start with a clear and formal definition. So let's borrow it from the official website python.org.
"Python is an interpreted, object-oriented, high-level programming language with dynamic semantics."
Now, this is a very clear definition for anybody who is already familiar with all the concepts used in the definition itself. This book though, targets a different audience with potentially no expertise at all on programming languages, so we will go over the concepts mentioned in the definition.
Let's start with a very general point of view. Python is a programming language which is very flexible and adapts to different context. Whether you need a rapid development of applications up to large scientific projects which require intense computations, this language has your back. One of Python's main characteristics is that it is easy to learn since its syntax generally facilitates the readability of the code. Also, users love the fact that in many situations the syntax required to develop a given set of instructions resembles the plain English which makes Python formidable in terms of immediate understanding of its features.
One of the other peculiarity which we must take into account when are choosing a programming language is its flexibility and the capacity of being extended to increment its features. This job is carried out by the so called modules. We reserve a specific section of this book to modules since they play a very important role in code development.
On last important characteristic is that Python is a multi-platform environment. Whether we are using Windows, MacOS or any of the Linux distributions, the Python interpreter can always be installed and used.
It really seems that this is the language to learn, but remember? We have to understand a bit of how it works internally. In the following sections, we briefly cover some of the most important characteristics mentioned in the definition.
1.2 Compiled vs Interpreted
Do you remember when we started this book? One of the first things we said was about how many programming languages have been developed over time. The point is: can we classify all those languages? Is there a way to group a given language by referring to a specific characteristic? Of course, the answer to all these questions is yes, we can. For instance, one of the most important distinctions you can have is whether a programming language is a compiled or an interpreted language. Let's try to understand the main differences since these two families have different purposes as well as pros and cons.
A compiled language is one where the program has to be converted into machine readable code. We write the so called source code and then through a compiler we compile the source code to convert it and express the instructions into the readable code by the target machine. For example, an addition operation + in your source code could be translated directly to the ADD instruction in machine code. In terms of advantages, we sure have faster performance. This is ensured by the fact the we can use the native code of the targeted machine. Also, compiled languages offer quite powerful optimization during the compiling phase.
An interpreted language is one where the instructions are not directly executed by the target machine, but instead are read and executed by some other computer program called interpreter (which normally is written in the language of the native machine). For example, the same + operation would be recognized by the interpreter at run time and it would then call its own add(a,b) function with the appropriate set of instructions which would then execute the machine code ADD instruction. In terms of advantages, these languages are easier to implement. The reason is given by the fact that developing efficient (i.e. good) compilers can be very hard. For those of you who have some kind of familiarity with compilers, just think about the LTX compiler which is incredibly slow. The other good thing is that we do not need to run any compilation whatsoever. In other words, we can execute code directly "on the fly". Lastly, they are definitely more convenient for dynamic languages.
1.3 Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming language model organized around objects rather than actions and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data. OOP takes the view that what we really care about are the objects that we have defined in our work space. We want to manipulate those objects rather than arguing about the underline logic required to manipulate them.
In OOP, objects play a major role then. They are the first things you think about when designing a program. Moreover, they can also be the result of the program you are developing. In other words, we work all the time with objects: we manipulate them to achieve a given data structure or a given result, for instance.
Objects can also be grouped into even conceptually higher and more abstract structures called classes. We will talk about classes later on in the book, so for now, let's think about them as a way to have objects which belong to the same class to share some characteristics. Each object can be seen as an instance of a particular class. Each class possesses its own methods or procedures and variables which call all be applied to whatever object belongs to the given class.
1.4 High-level Programming Language
A high-level language is a programming language designed to simplify computer programming and the life of the coder. The reason we refer to this class of languages with the term "high-level" is because of the level of abstraction and the simplification associated with it. A high-level language is far away from machine code which is understood by the internal processor of a computer.
In general, these type of languages have source codes which contain easy-to-read syntax, often almost in plain English. It is only at a later stage that instructions are converted in a language which can be read by a processor.
This is a fundamental aspect since it allows the coder to write complex algorithms using a very intuitive language (i.e. syntax). To give you a taste, this is what you need to do to print the string "Hello World" in Assembly, a well known low-level programming language very close to the machine code, and in Python which is a high-level language.
As we can see, the effort is much less when using a high-level language such as Python. All we have to do to print the message Hello World is to invoke a built-in function calledprint(). For those readers who have already some kind of familiarity with Python might be aware of the recent update in its interpreter. Indeed, from Python 3.x.x the print method has become a function which we call with print(). In older versions, namely 2.x.x, the call was print 'string to print'. This book uses the more recent Python 3.x.x.
1.5 Static vs Dynamic Semantics
Let's start by thinking about the meaning of the two words: static and dynamic. Intuitively, something that is static does not change, while a dynamic entity of some sort has some probability to change over time. Also, we feel that something that is static would tend to be less flexible than something that is dynamic.
In computer science, this difference plays a major role and it affects the way we interact with the language we decided to adopt. Below, we briefly provide some intuitions about the difference between the two paradigms and their pros and cons.
One good starting point to distinguish the two is to consider the static semantic as an external world that represents the text of the program we are writing. This world does not change, hence the the label static. The dynamic semantic can be considered as the inner world that represents the hardware status (i.e. memory) at run-time. This world does change, hence the label dynamic. Effectively, it is where all happens and where the program gets executed.
Static objects are formal constructs in the code. They can be expressions, statements, structures and so on. In other words, they have no meaningful existence beyond compile-time. Dynamic objects instead are instances of values contained in those objects, locations and so on and thus they do exist at run-time level since the user interacts with these manifestations. One can now start asking what kind of interaction, if any, does exist between these two objects. A link between the worlds is called binding which is direct consequence of declaration. This allows us to easily build interactions between static objects and their dynamic counterparts.
One other fairly important concept is the environment. Both static and dynamic objects have their own environments. These incorporate all the knowledge about the objects that are defined and are aware of all the possible other relevant objects, both static and dynamic. In particular, the static environment must include what is known about each identifier from its declaration. In fact, the static environment maps each identifier to its type and the kind of declaration it came from. The static environment is invariant over time, but varies according to position within the program text. The dynamic environment relates identifiers to the dynamic objects that will be around at run-time. In other words, it maps each identifier to information about constants or variables or operations and so on. It will vary over time, as the program runs simply because there will be different objects at each point in time during the execution of the program itself.
One of the most impressive advantages of a dynamic semantics is the ability to bind a name to objects of different types and to do this at runtime (i.e. during the execution of the program). In the following example, we show how the name my_object is assigned an integer value (i.e. an integer type) and then a string value (i.e. a string type).
my_object = 9
my_object = "Hello World"
In a statically-typed language, the above sequence of statements is illegal. The reason is due to the static nature of the environment in which we define the objects. If an object (my_object) had been declared to be an integer, then this object cannot be changed at later times. In a dynamically-typed language this sequence of instructions is perfectly fine. As we can see below, we can ask Python to print the value of the object as well as the type. Type is a fairly new concept which will be discussed in details in later Sections. For now, it is a way to distinguish between different objects.
my_object = 9
print(my_object)
## 9
print(type(my_object))
##
my_object = "Hello World"
print(my_object)
## Hello World
print(type(my_object))
##
1.6 Installing Python
Python is a multi-platform software which typically comes preinstalled in Unix-like systems, like Linux and MacOS, but has to be explicitly installed in Windows systems.
Regardless of the operating system, in order to work with Python we need to have a Python interpreter. Once again, this book uses Python 3.x.x interpreter. There are a number of different ways in which we can download and install the interpreter. Below is a list of the main methods:
Python Software Foundation: Python can be obtained from the official website Python.org. There we need to download the appropriate installer for the operating system the user is using and running it on the machine. This is the best way to get Python in Windows machines.
MacOS comes with Python already installed, but typically it is an older version (namely, 2.x.x). The best way to install Python then is through an amazing open source package manager called Homebrew. The installation of Homebrew is very simple and takes just one single command from a terminal. One the package manager is installed, you can select additional libraries and make them available for the whole system. For instance, installing Python requires a simple:
brew install python3
Linux systems come with package managers which allow to select single libraries to install. There are plenty of managers and they are strictly related to the type of distribution is in use. The most common ones are yum (for Red-Hat or Fedora-like systems), dpkg and apt (for Debian-like systems).
A final method to install everything you need to start working with Python is through a suite called Anaconda. The main advantage of such thing is that it automatically installs several tools so you don't have to worry to get them later on. To give you an example, below you find an image of the Anaconda Navigator interface which shows all the available software.
1.7 How Do You Interact with Python?
In one way or another, we were able to install everything and now we are ready to start coding in Python. Now let's be fair: Python on its own is really ugly. It is just an empty and sad window with almost no colors which seems to be very unfriendly to newcomers. If you do not believe us, take a look below.
One of the most important things to do when starting to work with a programming language is to choose an effective way to interact with the code. In other words, we want to have a graphical interface which makes it easier to write the code, to spot mistakes, to debug the code, and more broadly to talk with Python. As you can imagine, there exist plenty of graphical interfaces. We refer to these software as Integrated Development Environment(s) or IDE(s). In the following lines, we offer a brief tour through the most common and the most effective IDEs you can use.
1.7.1 Spyder
Spyder is for sure one of the most famous IDEs which has been around for a while. It is directly available with Anaconda and you can lunch it by opening Anaconda Navigator. Below you can find the typical interface that Spyder offers.
As you can see, in just a single window you are informed about the folders tree (left panel), the Python code you are writing (center panel) and the different objects you have created during the current session (top-right panel). Also, in the bottom-right panel you have immediate access to the Python console which is exactly the one shown in Figure 1.3.
A very handy characteristic of Spyder is the ability to execute a single line of Python code. This enables very precise control of the flow when developing a code and it is also useful when in the process of spotting mistakes and errors. Since it comes with Anaconda, Spyder is a multi-platform software.
1.7.2 Jupyter Notebook
Jupyter Notebook (commonly just called Notebook) is an open-source web-based application which makes your browser of choice the perfect IDE in which develop all your Python codes. Notebook is a lightweight environment and it is extremely portable. It can contain live code, equations, visualizations as well as descriptive text.
Jupyter Notebook also requires a bit of knowledge in a typesetting language called Markdown. A good starting point to grasp this language is Markdown Guide. This is a very powerful tool to draft the documentation accompanying the code.
The Notebook interface is pretty simple and neat. When you lunch it, it opens up a new tab in a browser window where you can immediately start writing your Python code. This is one of the best and fastest tool to start developing code. If you want to start using it, we also recommend the so called Notebook Extensions. There are different ways you can use go with to install these extensions. The Jupyter Contributions is a very good place to learn how to add them to your default installation.
1.7.3 PyCharm
PyCharm is one of the most powerful and complete IDEs available. It comes in two versions: the Community Edition (CE) and the Professional Edition. The former is available for free and offers fewer features, the latter comes with a commercial licence. For most users, the CE is the way to go, especially when one is starting his/her journey into the world of programming languages.
As you can see, you have all the information needed to develop the code. It includes a very helpful auto completion system and a debugging tool to spot bugs and errors. PyCharm is definitely the tool to use once the code is in its final version and can be widely used and adopted both in a research environment, but also within a business unit in a firm.
1.7.4 An outsider: iPython
Remember the first picture of a Python terminal shown in Figure 1.3? Well, there is a slightly better version which is just a bit more informative than the standard terminal. It is called iPython and basically can be use for very quick deployment or just testing. Personally, we use it to check that modules have been installed correctly.
As you can see, iPython enhances the standard terminal. For instance, we do have syntax highlighting here as well as the exact number of code executions we run.
(Continues…)
Excerpted from "Python for Non-Pythonians"
by .
Copyright © 2019 Bocconi University Press EGEA S.p.A..
Excerpted by permission of Bocconi University Press.
All rights reserved. No part of this excerpt may be reproduced or reprinted without permission in writing from the publisher.
Excerpts are provided by Dial-A-Book Inc. solely for the personal use of visitors to this web site.