Basics of Python
Basics of Python
Introduction
Python is a great general-purpose programming language on its own, but with the help of a few
popular libraries (numpy, scipy, matplotlib) it becomes a powerful environment for scientific
computing.
Basic Python: Basic data types (Containers, Lists, Dictionaries, Sets, Tuples), Functions,
Classes
Numpy: Arrays, Array indexing, Datatypes, Array math, Broadcasting
Matplotlib: Plotting, Subplots, Images
IPython: Creating notebooks, typical workflows
Basics of Python
Python is a high-level, dynamically typed multiparadigm programming language. Python code is
often said to be almost like pseudocode, since it allows you to express very powerful ideas in very
few lines of code while being very readable. As an example, here is an implementation of the
classic quicksort algorithm in Python:
In [ ]: def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
print(quicksort([3,6,8,10,1,2,1]))
Python versions
There are currently two different supported versions of Python, 2.7 and 3.4. Somewhat confusingly,
Python 3.0 introduced many backwards-incompatible changes to the language, so code written for
2.7 may not work under 3.4 and vice versa. For this class all code will use Python 3.5.
You can check your Python version at the command line by running python --version.
Numbers
Integers and floats work as you would expect from other languages:
In [ ]: x = 3
print(type(x)) # Prints "<class 'int'>"
print(x) # Prints "3"
In [ ]: x += 1
print(x) # Prints "4"
x *= 2
print(x) # Prints "8"
In [ ]: y = 2.5
print(type(y)) # Prints "<class 'float'>"
print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"
Note that unlike many languages, Python does not have unary increment (x++) or decrement (x--)
operators.
Python also has built-in types for long integers and complex numbers; you can find all of the details
in the documentation (https://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-
complex).
Booleans
Python implements all of the usual operators for Boolean logic, but uses English words rather than
symbols (&&, ||, etc.):
In [ ]: t = True
f = False
print(type(t)) # Prints "<class 'bool'>"
Strings
In [ ]: hw12 = '%s %s %d' % (hello, world, 12) # sprintf style string formatting
print(hw12) # prints "hello world 12"
In [ ]: s = "hello"
print(s.capitalize()) # Capitalize a string; prints "Hello"
print(s.upper()) # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7)) # Right-justify a string, padding with spaces; prints " h
print(s.center(7)) # Center a string, padding with spaces; prints " hello "
print(s.replace('l', '(ell)')) # Replace all instances of one substring with ano
# prints "he(ell)(ell)o"
print(' world '.strip()) # Strip leading and trailing whitespace; prints "world
Containers
Python includes several built-in container types: lists, dictionaries, sets, and tuples.
Lists
A list is the Python equivalent of an array, but is resizeable and can contain elements of different
types:
As usual, you can find all the gory details about lists in the documentation
(https://docs.python.org/2/tutorial/datastructures.html#more-on-lists).
Slicing
In addition to accessing list elements one at a time, Python provides concise syntax to access
sublists; this is known as slicing:
Loops
If you want access to the index of each element within the body of a loop, use the built-in
enumerate function:
# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line
List comprehensions:
When programming, frequently we want to transform one type of data into another. As a simple
example, consider the following code that computes square numbers:
In [ ]: nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
squares.append(x ** 2)
print(squares) # Prints [0, 1, 4, 9, 16]
In [ ]: nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print(squares) # Prints [0, 1, 4, 9, 16]
In [ ]: nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares) # Prints "[0, 4, 16]"
Dictionaries
A dictionary stores (key, value) pairs, similar to a Map in Java or an object in Javascript. You can use
it like this:
In [ ]: d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some data
print(d['cat']) # Get an entry from a dictionary; prints "cute"
print('cat' in d) # Check if a dictionary has a given key; prints "True"
print('furry' in d)
You can find all you need to know about dictionaries in the documentation
(https://docs.python.org/2/library/stdtypes.html#dict).
It is easy to iterate over the keys in a dictionary:
If you want access to keys and their corresponding values, use the iteritems method:
Dictionary comprehensions: These are similar to list comprehensions, but allow you to easily
construct dictionaries. For example:
In [ ]: nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square) # Prints "{0: 0, 2: 4, 4: 16}"
Sets
A set is an unordered collection of distinct elements. As a simple example, consider the following:
Loops: Iterating over a set has the same syntax as iterating over a list; however since sets are
unordered, you cannot make assumptions about the order in which you visit the elements of the set:
Set comprehensions: Like lists and dictionaries, we can easily construct sets using set
comprehensions:
Tuples
A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one of the
most important differences is that tuples can be used as keys in dictionaries and as elements of
sets, while lists cannot. Here is a trivial example:
Functions
Python functions are defined using the def keyword. For example:
In [ ]: def sign(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
We will often define functions to take optional keyword arguments, like this:
In [ ]: def hello(name, loud=False):
if loud:
print('HELLO, %s!' % name.upper())
else:
print('Hello, %s' % name)
hello('lol')
hello('lol', loud=True)
Classes
In [ ]: class Greeter(object):
# Constructor
def init (self, name):
self.name = name # Create an instance variable
# Instance method
def greet(self, loud=False):
if loud:
print('HELLO, %s!' % self.name.upper())
else:
print('Hello, %s' % self.name)
Source: https://cs231n.github.io/python-numpy-tutorial/