Connect With Us:

Getting Started With Python

post thumb
Tutorial
by / on 06 Sep 2020

Getting Started With Python

They say the best way to learn a language is by immersion so lets kick this off with a hands on explorator lab. The purpose of this lab is to get you into the tools and give you the minimum ‘vocabulary’ to start crawling in Python. Once you start crawling you can walk, run and then fly, but this process all starts with baby steps. So lets GO!

Number 1 - Get Python

First step is you need Python. You want Python 3, you can find the download for your operating system here: https://www.python.org/downloads/

There are other ways to get Python, especially if you are planning to do a lot of data analysis or artificial intelligence related things you may want to check out Anaconda. This distribution includes the core Python language, but it also includes many data science related packages and tools. Perhaps most importantly it includes the Jupyter notebook framework which allows you to interactively work with Python code, literate descriptions of you code, generate and embed visualizations all in the same pane of glass as your python code, and then easily share your notebooks with others.

Feel free to start with either Python distribution, but this lab aims to be as simple as possible, so any screenshots, etc will be for the baseline Python distribution.

Number 2 - Lauch the Interactive Python Shell

I think the instant feedback provided by the Python Shell is immensely valuable for exploration and for beginners it gets you working with the language primatives right away. If you are already familiar with shells in general all you have to do is launch your shell of choice and type ‘python’. If you have no clue what a shell is, just go to your OS’s app launcher and type ‘IDLE’.

> python
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

When you are done with the shell you can EXIT as follows want:

>>> exit()

The first few things we will look at are filesystem related. Python has a ‘batteries included’ paradigm where the standard python distribution includes the ability to do almost all the common tasks you are likely to need. However, in general Python will not load every single piece of functionality at launch. In general you will often have to tell Python to enable a specific piece of functionality.

File System Basics

In this case to enable Operating System level functionality such as the file system access, we need to tell Python to IMPORT the ‘os’ package.

>>> import os

Now we can see where in the file system we currently are by GETting the Current Working Directory:

>>> os.getcwd()
'C:\\Users\\glintstream'

Move to the directory where we want to store our lab files at by CHanging our DIRectory:

>>> os.chdir('c:\\dev')

Investigating what directories and files are in this location by LISTng the DIRectory contents:

>>> os.listdir()
['comp-sci', 'intro-to-python']

Creating a workspace for the lab by MaKing a new DIRectory, and then CHanging to that DIRectory:

>>> os.mkdir('python-lab')
>>> os.chdir('python-lab')

Creating a descriptive README.md file for our lab by OPENing a file in Write mode, WRITEing some content, and then CLOSEing the file:

>>> readme = open('README.md','w')
>>> readme.write('# Introduction to Python Lab #')
30
>>> readme.close()

Note that when working with files it is EXTREMELY important that you always close files that you open, if not you can encounter all kinds of bad situations. In this case the the contents of the file are not actually written to the file system until the file is closed.

To see the contents of the file, we OPEN the file in Read mode, and then READ all LINES, and then CLOSE the file:

>>> content = open('README.md','r')
>>> content.readlines()
['# Introduction to Python Lab #']
>>> content.close()

Subprocesses Basics

When coding it is common to want to be able to try out different approaches, sometimes these approaches don’t work out, and you want to go back to a previous version of your code. Git. It is pretty easy to execute other executables as subprocesses when working with Python

We tell Python to IMPORT the ‘subprocess’ package

import subprocess

Next we tell the SUBPROCESS package to OPEN a Process with the ‘git’ executable and pass it ‘init’ as a parameter:

subprocess.Popen(['git','init'])

We tell the SUBPROCESS package to OPEN a Process with the ‘git’ executable and pass it ‘add’ and ‘.’ as parameters:

subprocess.Popen(['git','add','.'])

Finally we tell the SUBRPROCESS package to OPEN a Process with the ‘git’ executable and pass it the ‘commit’, ‘-m’ and ‘Initial Commit’ as parameters:

subprocess.Popen(['git','commit','-m', 'Initial Commit'])

Number 3 - 3rd Party packages

The next basic part of vocabulary you are going to need is the ability to access the web. It is possible to do this with built in Python packages but the most commonly used web access package is not part of the standard Python distribution. This serves as a good place to cover the important concept of how you can work with 3rd party packages.

If you havent done so already you should exit the Python interactive shell:

>>> exit()

Before you can ‘import’ a Python package in your own code, it needs to be ‘installed’ on your workstation. ‘Installed’ in this case basically means the file with contents of the package needs to be in specific locations that the Python distribution is aware of. This model is pretty simple but it leads to a challenge: Over time you will have many different Python projects on your workstation with many different unrelated 3rd party packages. Keeping track of what project uses what 3rd party packages can very quickly become virtually impossible. To help with this, typically in Python you are going to create a separate ‘Virtual Environment’ for each of your Python projects. This way each project’s 3rd Party dependencies will be available to the individual project but isolated from all other projects.

Virtual Environments

A Python virtual environment is actually a fairly simple affair, basically it is two parts: 1. A completely separate directory with the entire Python distribution is copied somewhere onto your hard drive. 2. The system path environment variable for the current process is updated so that its first entry is the path to the virtual env’s Python executable

You can create this from a standard shell (as opposed to the Python Interactive Shell):

Tell PYTHON to use the Module VENV to create a new virtual environment in the directory .PROJECT-VIRTUAL-ENVIRONMENT

> python -m venv .project-virtual-environment

You have to actually enable to new virtual environment before you can use it, by executing the ACTIVATE (activate.bat on windows, activate.sh on linux) script in the .PROJECT-VIRTUAL-ENVIRONMENT’s SCRIPT directory

> .\.project-virtual-environment\Scripts\activate

When you are done with the virtual environment you can disable it by executing the DEACTIVATE command:

> deactivate

Package Installer for Python

Python has a built in tool for installing packages called ‘pip’. Pip basically searches Python’s Package Archive (PyPA), finds the pacakge you are interested in, and downloads the package to a location when the currently executing Python can find it.

Tell PIP to INSTALL the REQUESTS package

pip install requests

Tell PIP To LIST all the packages that are currenty

pip list

It is common to want to export the list of packages needed by a Python project. Typically this is used when you need to want to share a project with others, its more convient to just provide a list of packages they need rather than providing an entire copy of the your whole virtual environment. This is especially common when using Source Control, to avoid checking in large number of extraneous python scripts and binaries.

Tell PIP to FREEZE the current requirements and redirect the listing to a file called REQUIREMENTS.TXT

pip freeze > requirements.txt

Later you can install the current requirements of a Python project

Tell PIP to INSTALL Requirements from the file REQUIREMENTS.TXT

pip install -r requirements.txt

Number 4 - Python Modules

Typically one is going to execute a program multiple times across multiple days, in those cases it doesnt really make sense to retype your program over and over again in the Python Interactive Shell. In these cases you would save your program as a Python module.

A Python module is just a text file with the extension ‘.py’

Create a new file named ‘hello.py’ and open this file in your text editor of choice. Add the following text to the file:

print('hello from a python module')

From your standard shell (as opposed to the Python Interactive Shell, tell PYTHON to execute HELLO.PY

> python .\hello.py
hello from a python module

Parameters

A program that doesn’t allow inputs is very limited, it will always do the same exact thing everytime it is executed. There are many ways to provide inputs to programs but a common one is via command line arguements.

The ‘sys’ module has the facility to access arguements passed to a python module.

IMPORT the SYS package

import sys

Set the variable called NAME using the SYS package’s 2nd(tricky) ARGuement Value

name = sys.argv[1]

PRINT the string HELLO concatenated to the value of the variable called NAME

print('hello, ' + name)

Tell PYTHON to execute HELLO.PY with the argument STRANGER

> python .\hello.py Stranger
hello, Stranger

Interacting with the web

From here on out for the rest of this lab you can chose wether you prefer to program Python from the interactive shell or via python file, the same commands work either way.

IMPORT the REQUESTS package

>>> import requests

Use the REQUESTS package to execute a http GET of the resource HTTPS://WWW.GOOGLE.COM and store it in a variable called RESPONSE

>>> response = requests.get('https://www.google.com')

From here you can examine various fields on the RESPONSE, such as the STATUS_CODE or the TEXT:

>>> response.status_code
200
>>> response.text
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en">...

Number 5 - Do something with these fundamental building blocks

You have learned how to:

  1. Use the Interactive Python Shell
  2. Import and Use Built-in Python Packages
  3. Install, Import an Use 3rd Party Python Packages
  4. Use external command line tools from Python
  5. Create Python Modules
  6. Pass command line arguments to Python Modules
  7. Do basic file operations
  8. Do basic web requests
  9. Print text to the standard output

You should be able to:

  1. Create a Python Module that takes an url as input and saves the raw html of the website to a file
  2. Take the url of an image as an input and download the image and send it to an image compression command line tool like ImageMagik
Tags:
comments powered by Disqus