Modern Programming for Data Analytics - Very Brief Intro to Python

Instructor: Shawn T. Brown

Python:

  • is an interpreted high-level general-purpose programming language.
  • is an indented language that promotes highly readable programming.
  • supports both object-oriented programming and procedural progamming models.
  • has a massive community level of support with a plethora of modules to add a wide-array of functionality
  • the most widely used programming language (31.47% according to PYPL)

Python in scientific programming

  • Python was widely thought to not be high-performance
    • modules such as Numpy, SciPy, and Pandas have ensured that Python is a high-performance language
  • Python is by far the language of choice for Artificial Intelligence applications
    • Frameworks such as TensorFlow, PyTorch, and Caffe are all Python frameworks
  • Most scientific applications and data frameworks, while maybe not written in Python provide robust Python interfaces for data and procedural workflows

Brief Python Language Basics

For those of you not familiar with Python, there are some excellent online tutorials that you can use to catchup

A simple python program


import os

def print_message_from_file(filename):
    with open(filename, "r") as f:
        message = f.read()
        print("This is the message")
        print("{}".format(message))

def print_separator(n=45):
    print("{}".format("".join(["-" for x in range(0,n)])))

def main():

    for i in range(0, 10):
        print("Hello World!#{}".format(i))

		print_separator()

    sample_list = [0, 1, 2, 3, 4,
                   5, 6, 7, 8, 9]

    for i in sample_list:
        print("Hello List!#{}".format(i))

    print_separator()

    sample_list_comp = [x for x in range(0,1)]

    for i in sample_list:
        print("Hello Comprehension!#{}".format(i))

    print_separator()

    sample_dictionary = {"english": "hat",
                         "french": "chapeau"}

    for k,v in sample_dictionary.items():
        print("The word in {} is {}".format(k,v))

    print_separator()

    filename = os.path.join(os.getcwd(), "message.txt")
    print("The File is at {}".format(filename))

    print_message_from_file(filename)

if __name__ == "__main__":
    main()
						

Available on GitHub: https://github.com/CMU-MS-DAS-Modern-Programming-Mini/simple-python-example

Classes and Object Oriented Python


class Message:
    def __init__(self, message_string):
        self.message_string = message_string

    def print_message(self):
        print("This is the class message {}".format(self.message_string))

    def __str__(self):
        return "This is overriding the str class of the fuction: {}".format(self.message_string)

    def __add__(self, msg):
        if isinstance(msg, str):
            r_msg = Message(self.message_string + msg)
        elif isinstance(msg, Message):
            r_msg = Message(self.message_string + msg.message_string)
        else:
            raise TypeError("Class Message does not know how to add" +
                            "a variable of type {}".format(type(msg)))
        return r_msg
			

Classes and Object Oriented Python


import os
from message import Message

def print_message_from_file(filename):
    with open(filename, "r") as f_to_read:
        message = f_to_read.read()
        print("This is the message")
        print("{}".format(message))

def print_separator(num_chars=45):
    print("{}".format("".join(["-" for x in range(0, num_chars)])))

def main():
    for i in range(0, 10):
        print("Hello World!#{}".format(i))

    sample_list = [0, 1, 2, 3, 4,
                   5, 6, 7, 8, 9]

    print_separator()

    for i in sample_list:
        print("Hello List!#{}".format(i))

    print_separator()

    sample_list_comp = [x for x in range(0, 1)]

    for i in sample_list_comp:
        print("Hello Comprehension!#{}".format(i))

    print_separator()

    sample_dictionary = {"english": "hat",
                         "french": "chapeau"}

    for k, val in sample_dictionary.items():
        print("The word in {} is {}".format(k, val))

    print_separator()

    filename = os.path.join(os.getcwd(), "message.txt")
    print("The File is at {}".format(filename))

    print_message_from_file(filename)

    print_separator()

    msg = Message("... this is in class.")
    msg.print_message()

    print_separator()

    print("{}".format(msg))

    print_separator()

    msg_add = msg + " | adding a string"
    msg_add.print_message()

    print_separator()

    msg2 = Message("... adding a message class")
    msg_add = msg + msg2
    msg_add.print_message()

    print_separator()
    try:
        num = 6.003432
        msg_add = msg + num
    except Exception as e_msg:
        print("There was an exception {}".format(str(e_msg)))

if __name__ == "__main__":
    main()
						

Installing and Using Python

In this section we will go through some of the Python packages available, environment and package control, and interactive Python frameworks.

A word about Python versions....

  • There are two major overarching versions of Python in circulation, Version 2.x and 3.x.
  • These two versions are generally not compatible, and have multiple syntax and functional differences.

Common Python Istallations

  • All Linux distributions come with Python initially installed as part of the operating system
    • Generally, this is now Python version 3.x

    If you would like to install Python3 on Ubuntu

    										
    										apt-get install python3.7
    									
    									

    If you would like to install Python3 on Centos

    										
    										yum install python3.7
    									
    									

    To find out if and what version of Python is installed:

    										
    									 	> which python
    										/usr/bin/python
    										> python --version
    										Python 3.7.6
    									
    									

Anaconda Python - A Complete, Comprehensive Python Solution

Running Python

There are several ways that you can execute Python programs

Running Python Interactively

You can just open a terminal and start running Python

Running Python Programs

You can run a Python program by invoking Python on the script

Running Jupyter Notebooks

Jupyter Notebooks are in credibly powerful tool for running interactive Python in a web browser

To startup a Jupyter Notebook (assuming Jupyter is installed with your Python distro):

  • Open a terminal
  • Invoke Jupyter
    										
    											> jupyter notebook
    										
    									
  • Your default web browser should automatically open to Jupyter
    • If it does not, open a browser and enter the URL: http://localhost:8888/tree

Python Modules

Python comes with a large community of modules that are enhance the functionality

Here we will introduce a few popular modules and how to use them.

Including a Module

To include a module in your code:

Add the entire module ot your software

										
      import numpy
      x = numpy.zeros(100)
									
									

To add the module and give it an alias

										
      import numpy as np
      x = np.zeros(100)
									
									

To only include a function or class from a module

										
      from numpy import zeros
      x = zeros(100)
									
									

Basic helpful Python Modules

Numerical Processing Modules

(we will go into more detail later in the course)

  • NumPy - A fundemintal package for scientific computing with Python
  • SciPy - An collection of open source software for scientific computing in Python
  • Pandas - a fast, powerful, flexible and easy to use open source data analysis and manipulation tool.

Visualization Modules

Here are some modules that will be useful for visualizing data

  • matplotlib - A data tool for creating static, animated, and interactive visualizations
  • plotly (Open Source Version) - A graphing library for making publication-quality graphics
  • seaborn - Statistical Data visualization
  • bokeh - A viusaliztion library for bliding powerful interactive data applications

Other Powerful Modules

Here are a few more modules that are fairly useful for you to know about

  • Requests - HTTP requests for Humans
  • zipfile - module for working directly with Zip files
  • Flask - A web development platform for Python
  • SQLAlchemy - A Python SQL Toolkit and Object Relational Mapper

Installing and Managing Modules

Here we will discuss installing modules and managing python environmnets

Pip - the official tool for installing Python Packages

Pip provides a command line tool that allows you to automatically install python modules from PyPi and other custom sources.

virtualenv - managing environments in Python

  • Every python program comes with a set of modules that it may need to run
  • One can define various environments with various python versions and modules version
  • This tool can create a completely local, user-defined python environment

Exporting your environment with Pip

You can actually export your environment and module requirements to a file so that when someone else downloads the package, they can immediately install necessary modules

Anaconda Python

conda - an open source environment management system designed to work with Anaconda.

The Conda Cheat Sheet - is a really easy resource to follow to find all of the useful commands in using conda.

Anaconda Python also comes with a GUI package manager if you would like to use that on your local desktop

Documenting your Python Code

Documenting your code is crucial to others understanding it (and frankly you remembering what you did)

Some useful documentation systems with Python

DocStrings

  • A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition.
  • Such a docstring becomes the __doc__ special attribute of that object.
  • DocStrings are technically free format, but many packages can automatically generate documentation from them

In our previous example:


	import os

	def print_message_from_file(filename):
		"""
		Prints a message from contents for a

			Arguments:
				filename - A string giving the name of the files
				           that is in the current directory

			Returns:
			  Returns no value, prints the message to stdout
		"""

			with open(filename, "r") as f:
					message = f.read()
					print("This is the message")
					print("{}".format(message))
		 ...
							

Let's look at the rest of the code here

Python Coding Standards

  • The PEP 8 -- Style Guide for Python Code
  • Adopted by Guido and the Python core team to provide consistency in programming styles
  • The style guide provides a number of rules and best practices that have been developed over time to make readable
  • Very important in a team development setting to provide consistency
  • Augment with team agreed upon guidelines

PyLint - A tool for ensuring code adheres to code standards

  • Command line to provides a report on compiance with Pep8
  • Can be added to continuous inegration to automatically test all code
  • Sometimes gives suggestions that can be ignored

PyLint - A tool for ensuring code adheres to code standards

Developing in Python