Author: Theodore Odeluga
The source files for this project can be downloaded from here
Python is incredible. In the 3 decades or so since the first version was released, like it’s natural-world namesake, this straight-to-the-point, no-frills programming tool has stealthily crept up on the competition and slowly crushed it like hapless prey.
By the mid-1990s, when Java and JavaScript were both vying for dominance of the web, Guido Van Rossum’s elegant creation was keeping a relatively low profile and quietly becoming one of the most popular programming languages in the world.
Now, with a global influence reminiscent of the days when Visual Basic was the go-to introduction for anyone new to code, this general-purpose computing resource has become the ideal first-timer's choice among students and the de facto standard for data science, machine learning and cyber security.
The simplicity of Python’s syntax has been likened to documentation that actually runs as code – no surprise then for its consistent maintenance of a top 10 position in polls such as the Stack Overflow Developer Survey for several years running.
While this article won’t be a general introduction to programming (you can find that here instead), it will familiarize you with certain fundamentals in code as defined by Python.
I have to point out here that as you’ve noticed, most of the material on this site is JavaScript-based and this reflects my greater experience with JS. But here’s the thing – when I later picked up Python, I noticed I became more productive more quickly than I have with any other language. The advantage I believe is that Python is closer to human language than JS (literally communicating in almost human terms, where writing a line of code is like writing a sentence – that “documentation that actually runs as code” thing). Every language has its up sides and down sides – but developer ease-of-use is definitely a selling point of Python.
Setting up your local development environment
Before we get started, a few simple steps are required for set up.
First of all, Python can be downloaded from here.
Just go through the steps prompted by the installer and accept the defaults.
You can test the success of your installation by typing the following on the command line after the path as displayed here.
C:\Users\user> python --version
As you can imagine, a lot of tools support Python.
IDLE is the native product that traditionally ships with the language.
Other Integrated Development Environments include the Community Edition of PyCharm or Visual Studio among others.
Here’s a list of even more choices.
For lightweight text editors, Visual Studio Code is probably the most widely used.
Personally, I prefer Notepad++ , a simple but versatile program that gives you exactly what you need (useful code highlighting) without any distractions (such as a busy interface).
Feel free to use whichever product is your utility of choice. It probably supports Python right out of the box.
As a cross-platform language, Python of course runs on all major operating systems. This includes Windows , MacOS and of course Linux .
Ubuntu is my favorite distro from the Linux ecosystem and working with Python along with this OS is personally recommended.
The material created for this article was done with Windows but everything discussed is largely transferable to the other OSs.
As an aside, in the case of MacOS and Linux, you’ll probably find Python is already installed, but please bear in mind any preloaded copy may not be the most up to date. I would recommend that you don’t rely on anything pre-installed but instead always use a virtual environment whenever you’re working on a project so you can keep up with any changes to requirements.
I will go into more detail about virtual environments later in the tutorial.
Installing and running Python code is accomplished through typing short instructions on the command line.
This is the fastest way to work when it comes to creating software and with practice, leads to greater efficiency.
This is particularly true when installing dependencies. Let's look at the first one we require for Python.
Pip
Pip (Preferred Installation Program) is a Python module that should be installed during setup.
This is the tool for installing Python dependencies and should be routinely used whenever writing or running new code to ensure everything is complete and up to date.
You can find instructions on installing pip from the following.
Here’s how you would update a module using pip (more about modules below).
pip install --upgrade package-name
Virtual environments
As many libraries, frameworks and tools for Python are open-source and therefore constantly changing, you’ll find occasional conflict and incompatibility between products that are meant to work together.
This is normal as while the independent teams who develop these tools do their best to keep such adversity to a minimum, they can’t always guarantee a change in one codebase won’t break the finely balanced functionality of another.
One recommended way to overcome this issue is to work in a virtual environment.
As with other utilities, this capability comes in the form of a module which can be downloaded, installed and run with your code each time it requires additional dependencies.
You can learn more about the venv virtual environment package (including how to install it) here.
To include a module in your code you’d write something like the following at the top of your Python file, where each module name is preceded by the keyword “import” or “from”.
In the case of using the keyword “from”, you would follow this with the name of the larger module – which would effectively be the container of the smaller one and then use the word “import”, for the smaller module contained in the larger.
import statement to include a module - example:
from pathlib import Path
Modules are essentially standalone Python programs, where you don’t have to include all of their source code in your main application code. You also don’t need to include the .py extension after each name when referencing them.
The massive benefit of using separate modules (external to your main program but referenced from within your program by import statements) is that you have access to all their functionality without having to write that extra functionality yourself. You can simply call it by writing one or two lines of code.
As suggested above, you should get into the habit of always working within a virtual environment and preceding all development work by first running pip against all dependencies to ensure they’re up to date (make sure your computer is online when you do this so it can connect with the relevant remote resource and perform the download).
The additional advantage of working with virtual environments (apart from working with the latest versions of tools they give you access to) is that no matter what version your operating system, whether it directly supports your required dependencies or not, you’ll have no issue working with additional third-party code, as the environment acts like a sandbox around your own code and the additional source.
Likewise, anyone following the same approach with your product will have no problem running the finished program.
A typical approach in working on a project with venv would be using the command line as follows.
Be aware not to include the > symbol as displayed here if you copy from this page. This symbol is automatically generated by the command line.
On the command line create your project folder, navigate into the project folder, then create your environment.
> mkdir myproject
> cd myproject
> py -3 -m venv venv
The command line will then revert back to its original appearance, simply displaying the path.
At that point, while in the project folder, you would then activate your environment with the following command.
> venv\Scripts\activate
After entering the above command, the project will run within the environment (the path will display the text (venv) before the start of the path).
Deactivate the environment once you’re finished with running your program by typing the keyword 'deactivate' at the end of the path.
C:\Users\user\project deactivate
To assist users (and other developers) you could list all your project’s dependencies in the requirements.txt file.
Learn more about requirements.txt here.
Let's get on with writing some code.
You can write Python directly into the Windows Command Terminal by first invoking the Python interpreter with this command.
C:\Users\user> python
Please bear in mind the following caveats however, when using certain symbols.
Do not include the following symbols in your code if you copy and paste directly from this page.
>>> This symbol appears automatically when you type code directly into the Windows Command Terminal and move to the next line.
... Similarly, this symbol also appears automatically.
Please avoid copying these symbols from this page or remove them before running your code if you do so accidentally.
Writing code directly on the command line is better for shorter Python programs.
Larger applications are best written in a text file and run from the command line with the following.
Example: C:\Users\user> python mypythonprogram.py
If you have any issues, please refer back to the files in the project package.
Variables and datatypes
Python comes with several useful datatypes.
Int
This type works with whole numbers.
myint = 58
Long
This variable type also works with integers and in Python comes with a 32-bit (digit) limit.
mylong = 12345678910111213141516
Float
As with other languages this variable type works with decimals and is used for precision.
myfloat = float(10)
Output: 10.0
Complex numbers
This type holds numbers containing both known and “unknown” numbers (often hidden by a letter standing in for the value of the hidden number).
b = complex('1+2j')
print(b)
String
As per other languages, the string datatype in Python works with alphanumeric text.
mystring = "Hello"
Statements
Python is one of the easiest languages for writing statements in. Here are some simple examples.
Single line statement
mystatement = 10
Multi-line statement
b = 1
multi = 1 + 2 \
+ b
print(multi)
Compound statement
mynumber = ten = 10
Expression statement
a = 3
c = a = 1 + 2
print(c)
Delete statement
>>> myvariable = 3
>>> del myvariable
>>> print(myvariable)
Output:
Traceback (most recent call last):
File "", line 1, in
NameError: name 'myvariable' is not defined
Return statement
>>> def return_my_age():
... return 58
...
>>> return_my_age()
58
>>>
As seen in the earlier section on imports, import statement.
import mymodule
The pass statement acts as a placeholder for future code
for x in [0, 1, 2]:
print(x)
pass
# print(x * 10)
for x in [0, 1, 2]:
# print(x)
pass
print(x * 10)
The pass statement is a bit of a strange one because it doesn't do anything.
I won't go into detail about it here but you can read more about it here.
Continue and break statement.
for a in range(20):
if a == 20:
break
print(a)
Functions
Functions are easy to define in Python. Here’s a function without an argument.
def printme():
print('hello')
Here's one with.
>>> message = 'hello'
>>> def greeting(message):
... print(message)
...
>>> greeting(message)
hello
>>>
A lambda in Python is a small anonymous function. Here’s an example.
>>> mylambda = lambda: 3.14159265
>>> print(mylambda())
3.14159265
Note in the above code there is no function name.
After using the keyword lambda, a value is provided as the functions only content.
The mylambda variable is a separate object and isn't directly associated to the function's definition.
It simply assigns itself the nameless function's value.
Parameters and arguments
Here’s another example of a Python function with an argument.
As per other languages, this makes Python functions more dynamic as well as reusable.
>>> def greeting(message):
... print(message)
... hello = 'hello'
...
>>> greeting('hello')
hello
>>>
Comments
Here’s how comments are created in Python.
Single line comment.
# This is the format for a single line comment in Python.
This is the style for multiline comments.
"""
This is the format for a detailed
comment in Python that can span
multiple lines.
"""
Data structures
List
A list is an array-like structure in Python for storing multiple instances of the same data type.
# Lists in Python are like arrays in other languages
cats = ['cheetah', 'lynx', 'puma']
print('cats[0] = ' + cats[0])
print('cats[1] = ' + cats[1])
print('cats[2] = ' + cats[2])
print(cats)
Array
Of course, arrays can also be used in Python.
Cats = ["Panther", "Leopard", "Tiger"]
Tuple
The most important aspect of tuples is that they are immutable – meaning their data cannot be changed.
Tuples are ideal for storing static information.
my_tuple_cats = ('cheetah', 'leopard', 'puma')
print(my_tuple_cats[0])
print(my_tuple_cats[1])
print(my_tuple_cats[2])
print(my_tuple_cats)
# Go back one from the end
print(my_tuple_cats[-2])
Dictionary
Dictionaries in Python are like JSON structures – they are based on key-value pairs.
The content of a dictionary can change but does not allow duplication.
# Dictionaries are like JSON structures. They are constructed from key-value pairs.
my_dictionary = {'StarWars': 'DarthVader', 'StarTrek': 'Spock',
'Superman': 'LexLuthor', 'JamesBond': 'Blofeld',
'SpiderMan': 'PeterParker', 'BatMan': 'BruceWayne'}
# Assign a value to the dictionary
franchise = 'PiratesOfTheCarribean'
my_dictionary[franchise] = 'JackSparrow'
print(my_dictionary)
Set
Another Python data structure that disallows duplication.
movieset = {"lights", "camera", "microphone"}
Conditional statements
Python implements conditional statements like so:
If
one = 1
two = 2
if one < two:
print("one is less than two")
Else
one = 1
two = 2
if one < two:
print("one is less than two")
else:
print("no numbers provided.")
Elif
earth = 'round'
shape = 'round'
if earth == shape:
print("true")
elif earth != shape:
print("false")
You can write conditional statements on one line.
python = "fun"
if python == "fun": print("python is fun to code in!")
Nested if statement
pi = 3.14159265
if pi > 3:
print("pi is greater than 3")
if pi > 4:
print("pi isn't greater than 4?!?")
else:
print("pi = the ratio of a circles circumference to its diameter")
Logical operators
Not operator
a = 1
b = 2
print(a > b)
# Output: false
print(not a > b)
# Output: true
And operator
two = 2
three = 3
five = 5
if five > three and three > two:
print("Both conditions are True")
Or operator
one = 1
two = 2
three = 3
if two > one or three > two:
print("Either statement is true.")
One thing to watch out for when writing subsequent lines of Python is indentation. The language is particularly strict around this and can generate frustrating error messages in code that (looks) correct when it isn’t.
Generally, every time you write a subsequent line of Python code directly under the previous, the next line should be indented by two to four spaces (not tabs).
You can learn more about the rules of formatting Python with the PEP8 style guide.
Loops
There are a number of useful loop types in Python. Here are some examples.
For loop
cats = ["lion", "tiger", "tabby"]
for c in cats:
print(c)
Use a range
i = 0
some_list = [1, 2, 3, 4]
for i in range(0, len(some_list)):
print(some_list[i])
Classes and objects
They say everything in Python is an object (true for any language to be fair) but creating classes in Python is pretty straightforward.
class Employee:
def __init__(self, name, role):
self.name = name
self.role = role
Here’s an instance of a defined class (otherwise known as an ‘object’ (copy of a class)).
coder = Employee("Theo", "Programmer")
print(coder.name)
print(coder.role)
Here’s an example of inheritance
class Manager(Employee):
def __init__(self, name, role, grade):
self.name = name
self.role = role
self.grade = grade
boss = Manager("Alex", "Director", "Senior")
print(boss.name)
print(boss.role)
print(boss.grade)
I go into more detail about OOP in the introduction to programming. The article uses JavaScript as the context but the principles discussed also apply to Python.
Extending Python - libraries and frameworks
The real power of Python comes from its rich ecosystem of libraries, frameworks, modules and additional tools. Below is a brief overview and introduction to some of the more prominent ones.
Pandas
Pandas was created by Wes McKinney and is a library for manipulating data. One powerful object in Pandas, arguably the most used is the DataFrame object.
In the code below, a DataFrame uses the to_dict() method to convert an object named 'data' to a dictionary.
Prior to this, 'data' used the Pandas read_csv method to capture the data of a CSV file named ip_list_2.csv.
The end result is an output showing a list of cities, countries and IP addresses.
import pandas as pd
# Read in data from csv doc
data = pd.read_csv("data/ip_list_2.csv")
print(data)
# Convert DataFrame to dictionary
to_dictionary = pd.DataFrame.to_dict(data[['ip', 'city', 'country']])
# Query dictionary,
def get_data_from_ip():
print('Please enter your IP')
my_ip = input('here:')
print(data[data['ip'].str.match(my_ip)])
if data.empty:
print('IP is not contained in the list')
get_data_from_ip()
As this tutorial is a general introduction to Python tools and techniques, a more detailed account of Pandas is beyond the scope of the material. However, if you’re considering a career in data science, this particular library is arguably a singular mandatory requirement for your skillset. You can learn more about Pandas here.
Numpy
Numpy was created by Travis Oliphant and is used for working with arrays. In the wild, as the name implies, the strong focus of its use is in specialized mathematics. Creating arrays in Numpy is similar to the approach used for Python itself.
import numpy as np
primes_of_ninety_nine = [3, 11]
primes = np.array(primes_of_ninety_nine)
print(primes)
In the above code a simple list of prime numbers is converted to an array before being output.
You can learn more about Numpy here.
Matplotlib
Matplotlib is used for data visualization. Numpy, introduced above, is actually an extension of this library and the two are often used together to form powerful solutions for scientific projects.
Below, the numbers in the list are fed to the pyplot object plt. This uses its show method which will result in a graphic displaying a slightly broken, upward moving line from the bottom left to the top right, with a series of values on the y axis.
import matplotlib.pyplot as plt plt.plot([1,2,4,5,10,20,25,50,100])
plt.ylabel('multiples of 10')
plt.show()
Check out these other useful extensions.
Conclusion
I hope this has been a useful and enjoyable introduction to a highly versatile language that will no doubt continue to dominate the software world for many years to come. You can learn more about Python itself here.
I would encourage you to explore it further to develop your skills, future project ideas and the inspiration which you’ll no doubt get for your future career and personal work. Be bold, imaginative and innovative with this technology. There is no limit. Python is ideal for prototyping and trying out new ideas – so get started today.
Thanks for reading and please come back soon. All the best.