About Python

About Python

In this post, we will look at an overview of the Python programming language, how to install it, and run some code.

So what is Python?

Python is a powerful general-purpose programming language. It is used in web development, data science, creating software prototypes, and so on.

What sets Python apart from other languages?

This is highlighted in its philosophy:

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Woow!

So this explains why it is simple to use; it can be taught to a beginner, can be embedded into any application, and can run on all current operating systems, including Mac, Windows, and Linux. It is also one of the most powerful languages a programmer can use and is about three and five times faster to code than JavaScript and C++, respectively.

Installing Python

Check if python3 is installed by running on the terminal or the command line:

python3

This will launch the python 3 interpretor

launching_python.png

To exit from the python interpretor just type:

>>> exit()

Note: Currently Python 2 is outdated. Python 3 is the current standard and more on demand. So for someone starting out it is better to start with Python 3.

Installing Python in Windows

If you do not have Python3 installed in windows, download the installer (.exe file) from this Latest Python3 Download page and run it.

download_python_windows.png Just accept the subsequent prompts.

In case you get stuck you can follow this post

Installing python in Ubuntu

Most Ubuntu OS comewith Python preinstalled.

To check the Python3 version installed in ubuntu run:

$ python3 --version

If you want a specific version for instance Python 3.6 you can install with:

$ sudo apt-get update
$ sudo apt-get install python3.6

For more details on this you can visit this Linux Python installation post

Note: Ubuntu OS will be used in most sections below however the scripts can work also in Windows or MAC since Python is platform independent.

How to run Python

There are various ways to run python scripts.

These include:

1. The Python interactive mode

This is the python interactive interpreter also called python shell that we launched by running on the terminal:

$ python3

It provides programmers with a quick way to execute commands and try out or test code without creating a file.

python_interpreter.png

2. The operating system command-line or terminal

If you have a python file (a .py file) you can run it on the command-line or terminal

For instance,to write the “Hello, World!” program, let’s open up a command-line text editor such as nano and create a new file:

$ nano hello.py

Once the text file opens up in the terminal window we’ll type out our program:

hello_py.png

Save the file on the editor by pressing Ctrl + O then exit the editor by pressing Ctrl + X.

You could also use an editor of your choice like Notepad++ or Sublime text.

Then on the terminal run the hello.py

python_terminal_run.png

Note: When running the python file the terminals should be on the same directory that you have saved the file or you specify the file with its full path.

3. The IDE you like best

An Integrated Development Environment (IDE) is a software package that developers use to create programs. It’s meant to maximize a programmer’s productivity by incorporating closely related components with simple user interfaces. Essentially, it’s a tool that improves the process of creating, testing, and debugging source code — it makes the job easier.

Some of the tools IDEs use include:

  • A text editor
  • Compiler and/or interpreter
  • Assembly automation tools
  • Debugger.

best-python-ide-and-code-editors.png

Some of the best Python IDE. Source : What Is the Best IDE for Python Development?

For someone starting out in web development I would advise use Visual Studio Code since in it you can code in Python,Javascript, HTML AND CSS and it is free. For data science I prefer Spyder or Jupyter because they are light-weight IDEs, that means they are really faster and they use less system resources. They are also free and the GUI looks amazing and easy to use.

However, in Pycharm you can do web development, data science (almost everything you'd need python for) but you need time before you find your way around it plus the free version has less features.

For more details on the Python IDEs you can visit this post

Here, we will mainly use Jupyter notebook. This is because Jupyter is easy to use, it works the same on any OS, is interactive and it is a great educational tool.

Before we go any further let's first look at Python Virtual environment.

So what is a Python Virtual Environment?

python_virtual_environment.png

A virtual environment is a Python environment such that the Python interpreter, libraries and scripts installed into it are isolated from those installed in other virtual environments, and (by default) any libraries installed in a “system” Python.

Using python virtual environment

There are several ways to install python virtual environments:

1. using venv

This comes pre-installed with python.

To create the environment run:

$ python3 -m venv /path/to/new/virtual/environment

To activate the virtual environment:

$ source /path/to/new/virtual/environment/bin/activate

For example:

python_venv.png

To deactivate the environment run:

$ deactivate

2. using virtualenv

The advantage of this is that it comes with preinstalled wheel for the virtual environments to be created from it. The wheel is used handle a compressed format of a python package (.whl) that can be used by pip to speed up the install time.

To install virtualenv run:

$ sudo pip3 install virtualenv

To create the virtualenv run:

$ virtualenv -p python3 /path/to/new/virtual/environment/

To deactivate the environment you use the deactivate command

For example:

virualenv.png

3. using virtualenv and virtualenvwrapper

This is a set of extension to virtualenv. It gives you commands like mkvirtualenv and workon for switching between different virtualenv directories.

To install run:

$ sudo pip3 install virtualenv virtualenvwrapper

With these components installed, we can now configure our shell with the information it needs to work with the virtualenvwrapper script.

Our virtual environments will all be placed within a directory in our home folder called Env for easy access.

This is configured through an environmental variable called WORKON_HOME.

We can add this to our shell initialization script and can source the virtual environment wrapper script.

To do this run:

$ echo "export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3" >> ~/.bashrc
$ echo "export WORKON_HOME=~/Env" >> ~/.bashrc
$ echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bashrc

Now, source your shell initialization script so that you can use this functionality in your current session:

$ source ~/.bashrc

You should now have directory called Env in your home folder which will hold virtual environment information.

To create the virtual environment, named project_env, run:

$ mkvirtualenv project_env

The virtual environment gets activated automatically.

mkvirtualenv.png

To deactivate it, you can use the deactivate commmand.

To activate the created environment you can run:

$ workon project_env

That is:

workon_env.png

Getting started with jupyter notebook

First let's create a virtual environment then install jupyter notebook in it:

$ mkvirtualenv jupyter_notebook
$ pip install jupyterlab

To activate the notebook (while in the virtual environment it has been installed at) run:

$ jupyter notebook

The jupyter notebook will open in a browser

You can open a new python3 notebook on which we will be running some python code.

opening_jupyter.png

Let's start off by checking out the python philososphy:

import this

import_this.png

Let's checkout some python syntax:

Variables

A Python variable is a reserved memory location to store values. A variable in a python program gives data to the computer for processing.

Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc. Variables in Python can be declared by any name or even alphabets.

How to Declare and use a Variable

An example, let's define a variable in Python and declare it as "my_variable" and print it.

my_variable=100 
print (my_variable)

Note: Python is a case-sensitive language. This means, Variable and variable are not the same.

Data Types

Python has five standard Data Types:

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

Python sets the variable type based on the value that is assigned to it. Python will change the variable type if the variable value is set to another value. For example:

var = 123      # This will create a number integer assignment
var = 'john'    # the `var` variable is now a string type.

a. Numbers

Python numbers variables are created by the standard Python method:

var = 382

The number types are shown in the table below:

TypeFormatDescription
inta=10Signed Integer
longa=345LL) Long integers, they can also be represented in octal and hexadecimal
Floata = 45.67(.) Floating point real values
Complexa = 3.14J(J) Contains integer in the range 0 to 255.

Most of the time Python will do variable conversion automatically. You can also use Python conversion functions (int(), long(), float(), complex())to convert data from one type to another. In addition, the type function returns information about how your data is stored within a variable.

num = 85
pi = 3.14159

print(type(n))  # This will return an integer
print(type(pi))  # This will return a float

b. String

Create string variables by enclosing characters in quotes. Python uses single quotes ', double quotes " , and triple quotes """ to denote literal strings.

Only the triple quoted strings """ will automatically continue across the end of line statement.

firstName = 'john'
lastName = "smith"
message = """This is a string that will span across multiple lines. Using newline characters
and no spaces for the next lines. The end of lines within this string also count as a newline when printed"""
print(type(message))  # This will return a string
print(message)            # This will return the message text

c. Lists

Lists are a very useful variable type in Python. A list can contain a series of values. List variables are declared by using brackets [ ] following the variable name.

A = [ ] # This is a blank list variable
B = [1, 23, 45, 67] # this list creates an initial list of 4 numbers.
C = [2, 4, 'john'] # lists can contain different variable types.

All lists in Python are zero-based indexed.

mylist = ['Rhino', 'Grasshopper', 'Flamingo', 'Bongo']
B = len(mylist) # This will return the length of the list which is 3. The index is 0, 1, 2, 3.
print(mylist[1]) # This will return the value at index 1, which is 'Grasshopper'
print(mylist[0:2]) # This will return the first 3 elements in the list.

You can assign data to a specific element of the list using an index into the list. The list index starts at zero. Data can be assigned to the elements of an array as follows:

mylist = [0, 1, 2, 3]
mylist[0] = 'Rhino'
mylist[1] = 'Grasshopper'
mylist[2] = 'Flamingo'
mylist[3] = 'Bongo'
print(mylist[1])

Note: Lists aren’t limited to a single dimension.

developer.rhino3d.com/guides/rhinopython/py..

d. Tuples

Tuples are a group of values like a list and are manipulated in similar ways. But, tuples are fixed in size once they are assigned. Tuples are defined by parenthesis ().

animals = ('Lion', 'Elephant', 'Leopard', 'Snail')

e. Dictionaries

Dictionaries in Python are lists of Key:Value pairs. This is a very powerful datatype to hold a lot of related information that can be associated through keys. The main operation of a dictionary is to extract a value based on the key name. Dictionaries can also be used to sort, iterate and compare data.

Dictionaries are created by using braces ({}) with pairs separated by a comma (,) and the key values associated with a colon(:). In Dictionaries the Key must be unique.

Syntax:

dictionary = {'key' : 'value', 'key_2': 'value_2'}

Here is a quick example on how dictionaries might be used:

room_num = {'john': 425, 'tom': 212}
room_num['john'] = 645     # set the value associated with the 'john' key to 645
print(room_num['tom'])       # print the value of the 'tom' key.
room_num['isaac'] = 345    # Add a new key 'isaac' with the associated value
print(room_num.keys())       # print out a list of keys in the dictionary
print('isaac' in room_num)   # test to see if 'issac' is in the dictionary.  This returns true.

Nested Dictionaries

In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary.

nested_dict = { 'dictA': {'key_1': 'value_1'},
                          'dictB': {'key_2': 'value_2'}}

For example:

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

print(people)

Output:

{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

Python Conditional Statements

Conditional Statement in Python perform different computations or actions depending on whether a specific Boolean constraint evaluates to true or false.

Conditional statements are handled by IF statements in Python.

if condition

Python if Statement is used for decision-making operations. It contains a body of code which runs only when the condition given in the if statement is true. If the condition is false, then the optional else statement runs which contains some code for the else condition.

Python if Statement Syntax:

if expression
 Statement

Example:

x,y =2,4
if(x < y):
    st= "x is less than y"
print (st)

Output:

x is less than y

if else condition

The "else condition" is usually used when you have to judge one statement on the basis of other. If one condition goes wrong, then there should be another condition that should justify the statement or logic.

It's syntax:

if expression
 Statement
else 
 Statement

Example:

x,y =8,4
if(x < y):
    st= "x is less than y"
else:
    st= "x is greater than y"
print (st)

Output:

x is greater than y

elif condition statement

When you have more than two coditions, you can use the elif statement.

The syntax is:

if expression
 Statement
elif expression
 Statement
else 
 Statement

Example:

x,y =8,8

    if(x < y):
        st= "x is less than y"

    elif (x == y):
        st= "x is same as y"

    else:
        st="x is greater than y"
    print(st)

For more about this check this post on Python Conditional Statements.

Python loops

A loop statement allows us to execute a statement or group of statements multiple times.

Loop Types include:

  1. While loop
  2. For loop
  3. Nested loop

a. While Loop:

In python, while loop is used to execute a block of statements repeatedly until a given a condition is satisfied.

Syntax :

while expression:
    statement(s)

For example:

count = 0
while (count < 3):   
    count = count + 1
    print("Hello Geek")

b. for in Loop

For loops are used for sequential traversal. For example: traversing a list or string or array.

Syntax:

for iterator_var in sequence:
    statements(s)

Example:

n = 4
for i in range(0, n):
    print(i)

Output :

0
1
2
3

c. Nested loop

You can use one or more loop inside any another while, for or do..while loop.

Syntax for nested for loop:

for iterator_var in sequence:
    for iterator_var in sequence:
        statements(s)
        statements(s)

Syntax for a nested while loop:

while expression:
    while expression:
        statement(s)
        statement(s)

Example of a nested for loop:

for i in range(1, 5):
    for j in range(i):
         print(i, end='  ')
    print()

Output:

1
2 2
3 3 3
4 4 4 4

Note: In loop nesting we can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa.

For more details on loops check this articles out:

Loop Control Statements

Loop control statements change execution from its normal sequence.

a. break statement

Terminates the loop statement and transfers execution to the statement immediately following the loop.

# First Example
for letter in 'Python':     
   if letter == 'h':
      break
   print('Current Letter :', letter)

# Second Example
var = 10                    
while var > 0:              
   print('Current variable value :', var)
   var = var -1
   if var == 5:
      break

print("Good bye!")

The output of the above is:

Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!

b. continue statement

The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.

 # First Example
for letter in 'Python':    
   if letter == 'h':
      continue
   print('Current Letter :', letter)

# Second Example
var = 10                   
while var > 0:              
   var = var -1
   if var == 5:
      continue
   print('Current variable value :', var)
print("Good bye!")

c. pass statement

The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet

For example:

for letter in 'Python': 
   if letter == 'h':
      pass
      print('This is pass block')
   print('Current Letter :', letter)

print("Good bye!")

Check this link on Loop Control Statements to learn more on python control statements.

Python functions

In Python, a function is a group of related statements that performs a specific task.

Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.

Furthermore, it avoids repetition and makes the code reusable.

Syntax of Function:

def function_name(parameters):
    """docstring"""
    statement(s)

Above shown is a function definition that consists of the following components.

  1. Keyword def that marks the start of the function header.
  2. A function name to uniquely identify the function.
  3. Parameters (arguments) through which we pass values to a function. They are optional.
  4. A colon (:) to mark the end of the function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
  7. An optional return statement to return a value from the function.

Example:

def greet(name):
    """
    This function greets to
    the person passed in as
    a parameter
    """
    print("Hello, " + name + ". Good morning!")

# To call the function
greet('Paul')

Output:

Hello, Paul. Good morning!

To learn more on Python functions check out this article on Python Functions

Python OOP

Python is an object oriented programming language. Unlike procedure oriented programming, where the main emphasis is on functions, object oriented programming stresses on objects.

An object is a collection of data (variables) and methods (functions) that act on those data. Similarly, a class is a blueprint for that object.

Example:

class Parrot:

    # class attribute
    species = "bird"

    # instance attribute
    def __init__(self, name, age):
        self.name = name
        self.age = age

# instantiate the Parrot class
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)

# access the class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))

# access the instance attributes
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))

Woow. This is a lot. Let's go through it step by step:

  • Class definitions begin with a class keyword.

  • In the above program, we created a class with the name Parrot. Then, we define attributes. The attributes are a characteristic of an object.

  • These attributes are defined inside the init method of the class. It is the initializer method that is first run as soon as the object is created.

  • Then, we create instances of the Parrot class. Here, blu and woo are references (value) to our new objects.

  • We can access the class attribute using class.species. Class attributes are the same for all instances of a class. Similarly, we access the instance attributes using blu.name and blu.age. However, instance attributes are different for every instance of a class.

Methods

Methods are functions defined inside the body of a class. They are used to define the behaviors of an object.

Example:

class Parrot:

    # instance attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # instance method
    def sing(self, song):
        return "{} sings {}".format(self.name, song)

    def dance(self):
        return "{} is now dancing".format(self.name)

# instantiate the object
blu = Parrot("Blu", 10)

# call our instance methods
print(blu.sing("'Happy'"))
print(blu.dance())

Output:

Blu sings 'Happy'
Blu is now dancing

In the above program, we define two methods i.e sing() and dance(). These are called instance methods because they are called on an instance object i.e blu.

To learn more on Python OOP checkout this Python3 Programmiing Language

Python Scripts, Modules, Libraries and Packages

Scripts are runnable Python programs that do something when executed.

Modules are Python files that are intended to be imported into scripts and other modules so that their defined members—like classes and functions—can be used.

Packages are a collection of related modules that aim to achieve a common goal.

The Python standard library is a collection of packages and modules that can be used to access built-in functionality. In an ideal world, you’d import any necessary modules into your Python scripts without any issues.

Note: A lot of this subjective

For more details on all this checkout this tutorial on Python scripts, modules and packages