Getting Started with Python



In this notebook, we go through basic commands in python. Let's start with a simple command in Python.

Certainly, we can create more complex commands using print() that interested readers can find some of them here.

1. Packages

1.1 Installing Packages

Packages are an essential part of python that can make tasks easier for users. We can use the following syntax to install packages:

pip install packagename

Example: Installing numpy package.

pip install numpy

Moreover, this can be done through Conda Terminal using the following syntax:

conda install numpy

To see available packages using conda environment, one can search using

conda search packagename

Moreover, to see channels, we can use

conda config --show channels

Also, to add a new channel to the bottom of the channel list

conda config --append channels channelname

For example, we can add conda-forge to the bottom of the channel list

conda config --append channels conda-forge

Similarly, to add a new channel to the top of the channel list

For example, we can add conda-forge to the top of the channel list

conda config --add channels conda-forge

See managing channels for more details.

1.2 Importing Packages

Some useful package:

One can import all contents of a package or import a particular part of it. We recommend importing packages using the "as" feature (see blew for details). This allows importing many packages without being worried about any overlapping.

Example:

2. Control Flow

Control flow includes Conditional statements, loops, branching, ...

2.1. if Statements

We can use the following syntex to use if, elif and else.

Syntax:

if expression:
    statements
elif expression:
    statements
else:
    statements
end

Example: Checking wheter a given number $x$ is smaller than 10, equal 10 or greater than 10.

Example: Checking wheter given number $x$ and $y$ are smaller than 10, greater than 10 or none of above.

2.2. Loops

Loops are used for iterating a process. Two popular loops are for and while loops.

2.2.1. for loops

for loop is used to repeat some statements for a specified number of times.

Syntax:

for index in values:
    statements

Example: Let's generate the following sequence using Python $$\{ 0, 1, 3, 6, 10, \ldots\}$$

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

Example:

2.2.2. Nested loops

Implementing a loop inside another loop is called a nested loop. For example, we can

for loop: # Outer loop
    [doing something using the outer loop iteration]  # Optional
    for loop:   # Nested loop
        [doing something using nested loop iteration]

Example:

Note: the the second loops runs first.

Example:

2.2.3. While loops

while loop is used to repeat some statements when condition is true

Syntax:

while expression:
    statements

Example:

We can generate the sequnece $\{ 0, 1, 3, 6, 10, \ldots\}$ using while loop as well.

2.2.4. break

[source python.org]

The break statement, like in C, breaks out of the innermost enclosing for or while loop.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

Example:

Example:

3. Defining a Function

Syntax

def functionname( parameters ):
    "function_docstring"
    function_suite
    return [expression]

Example:

3.1. functions with two arguments

Example: the following function takes $x$ and $y$ and retruns $x^2$ and $y^2$.

4. Plots

4.1. Pyplot

Pyplot from matplotlib (i.e. matplotlib.pyplot) provides a wide variety of function that can be compared with MATLAB plot functions.

Example: Let's plot a line using $\{(1,2),(2,4),(3,6),(4,8)\}$.

We also can use the following command to use plot

We also can use scatter to plot discrete data. For Example,

Example: Let's plot $\cos(\pi t)$ with $0\leq t \leq 5$

Example: The hist() function automatically generates histograms and returns the bin counts or probabilities.

4.2. subplot

Sometimes, it is more convenient to include more than one plot in a figure. Doins so, we can use subplot.

An alternative way can be considered as follows:

4.3. Three-dimensional plotting

We can use mplot3d from mpl_toolkits to generate 3D plots.

Example: For example, let's plot $z=x^2+y^2$ with $-4\leq x,y\leq 4$.

For more examples of plots, please check here.

5. Symbolic computations in Python

Let us define a symbolic expression and appy some useful functions on it [source].

Function Description
expand(expr) expands the arithmetical expression expr.
simplify(expr) transforms an expression into a simpler form.
factor(expr) Factors a polynomial into irreducible polynomials.
diff(func, var, n) Returns nth derivative of func .
integrate(func, var) Evaluates Indefinite integral
integrate(func, (var, a, b)) Evaluates Definite integral
limit(function, variable, point) Evaluates Limit of symbolic expression.
series(expr, var, point, order) Taylor series of an expression at a point.
solve Equations and systems solver.
dsolve solves differential equations.

Example: (expand, simplify and factor)

Example: (diff)

Example: (integrate)

Example: Let's compute

Example: Evaluate Taylor series of

Example: Let's solve the following equations

Example: Let's solve the differential equation $y'' - y = e^x$.

We also can find the eigenvalues of a marix using Python

Example: Matrices

Finally, we can print outputs in $\LaTeX$ format.

Example:

6. Data Structures

6.1. Lists

Syntax Description
list.append(x) Add an item to the end of a list.
list.extend(iterable) Extend a list by appending all the items from the iterable.
list.insert(i, x) Insert an item at a given position of a list.
list.remove(x) Remove the first item from a list whose value is equal to x.
list.pop([i]) Remove the item at the given position in a list, and return it.
list.clear() Remove all items from a list.
list.index(x[, start[, end]]) Return zero-based index in a list of the first item whose value is equal to x.
list.count(x) Return the number of times x appears in the list
list.sort(key=None, reverse=False) Sort the items of the list in place.
list.reverse() Reverse the elements of the list in place.
list.copy() Return a shallow copy of the list.

Here are all of the methods of list objects (source):

Example:

Example:

Example:

Example:

Example:

6.2. Using Lists as Queues

We also can use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose.

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For Example:

6.3. List Comprehensions

For Example, assume we want to create a set $$S_n=\left\{\frac{1}{1+n^2} \right\}_{n>=0}.$$

We also can generate $S_n$ using either of the following commands

Example: let's contruct the following set $$ S=\left\{\left(x,y\right)~|~\left(x,y\right)\in \mathbb{Z}_2\times\mathbb{Z}_2~ \&~ x\neq y\right\} $$

We could generate this set using nested loops as well

7. Linear algebra

A $m$ by $n$ matrix in Python is basically a list of a list as a matrix having $m$ rows and $n$ columns. For Example:

7.1. Matrix

Syntax Description
mat(data[, dtype]) Interpret the input as a matrix.
matrix(data[, dtype, copy])
asmatrix(data[, dtype]) Interpret the input as a matrix.
bmat(obj[, ldict, gdict]) Build a matrix object from a string, nested sequence, or array.
empty(shape[, dtype, order]) Return a new matrix of given shape and type, without initializing entries.
zeros(shape[, dtype, order]) Return a matrix of given shape and type, filled with zeros.
ones(shape[, dtype, order]) Matrix of ones.
eye(n[, M, k, dtype, order]) Return a matrix with ones on the diagonal and zeros elsewhere.
identity(n[, dtype]) Returns the square identity matrix of given size.
repmat(a, m, n) Repeat a 0-D to 2-D array or matrix MxN times.
rand(*args) Return a matrix of random values with given shape.
randn(*args) Return a random matrix with data from the “standard normal” distribution.

We can create a matrix using numpy.matrix as well. Example:

To access an entry of this matrix we can

Note: Unlike MATLAB, here indeces start from 0

7.1.1. zeros

Syntax: numpy.zeros(shape, dtype=float, order='C')

Notes:

Example: We also create matrices using nested loops.

The size of this matrix can be also found as

Example: Let's transpose matrix A.

We can generate a matrix using zip function as well. For Example:

We can delete some elements of a list using del function. For Example:

We can also use numpy.matrix to create matrices. For Example:

7.1.2. Sparse matrices

We can use scipy to define sparse matrices. For Example:

7.2. Dictionaries

A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output. We are going to explain this using an Example:

8. DataFrames

We highly recommend reading getting started tutorials from pandas. However, in this section, we briefly introduce some of the key functions of Pandas Datafrme.

8.1. Importing Data from a Website

Each column in the above Datafrme is a Series. For example,

To see some general stats regarding the df, we can use describe()

We can transpose a dataframe using .T.

8.2 Summary Statistics

To find the maximum and minimum of this series,

Moreover, mean, median, sum, and count

Furthermore, value_counts() returns a Series containing counts of unique values.

8.3 GroupBy

A DataFrame can be grouped using a mapper or by a Series of columns. For example, to see the average goal scored from each nationality. We can use the following syntax.

Similarly, to see all goals scored from each nationality. We can use the following syntax.