Introduction to Python Programming#

This tutorial is designed to provide you with a basic foundation in the fundamental concepts of Python we will use during this course.

Table of Contents#

  1. Function Declarations

  2. for and while Loops

  3. Package Installation and Import

  4. Lists and Arrays

  5. Numerical Solution of Differential Equations with scipy

  6. Test yourself

Function Declarations#

Defining a Function#

In Python, a function is defined using the def keyword. Here is a simple example:

def my_function(parameter):
    return parameter * 2

Calling a Function#

To call a function, use its name followed by parentheses containing the necessary arguments:

result = my_function(5)
print(result)  # Displays 10

for and while Loops#

for Loop#

The for loop is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string).

for i in range(5):
    print(i)

while Loop#

The while loop continues as long as a condition is true.

counter = 0
while counter < 5:
    print(counter)
    counter += 1

Package Installation and Import#

Installing Packages#

To install a package, you can use pip:

pip install package_name

Importing Packages#

To import a package, use the import keyword:

import numpy as np
import pandas as pd

Lists and Arrays#

Python List#

A list is an ordered and modifiable collection of elements.

my_list = [1, 2, 3, 4, 5]

Example of creating a list with a for loop:

my_list = []
for i in range(5):
    my_list.append(i)
print(my_list)  # Displays [0, 1, 2, 3, 4]

Another method to add elements to a list:

You can also add elements to a list using the + operator to concatenate lists:

my_list = []
for i in range(5):
    my_list = my_list + [i]
print(my_list)  # Displays [0, 1, 2, 3, 4]

Numpy Array#

A numpy array is similar to a list but is optimized for numerical operations.

import numpy as np

my_array = np.array([1, 2, 3, 4, 5])

Differences#

  • Performance: Numpy arrays are faster for numerical operations.

  • Functionality: Numpy arrays offer additional features for mathematical calculations.

Index Management in Arrays#

Numpy arrays allow flexible index management to access elements. Here are some examples:

import numpy as np

array = np.array([10, 20, 30, 40, 50])

# Access elements from index 0 to the end
print(array[0:])  # Displays [10 20 30 40 50]

# Access elements from index 1 to 3 (exclusive)
print(array[1:3])  # Displays [20 30]

# Access elements from index 2 to the end with a step of 2
print(array[2::2])  # Displays [30 50]

Data Filtering in Lists or Arrays#

You can filter data in lists or arrays using logical tests.

Filtering in a List#

my_list = [1, 2, 3, 4, 5]

# Filter elements greater than 2
filtered_list = [x for x in my_list if x > 2]
print(filtered_list)  # Displays [3, 4, 5]

Filtering in a Numpy Array#

import numpy as np

my_array = np.array([10, 20, 30, 40, 50])

# Filter elements greater than 20
filtered_array = my_array[my_array > 20]
print(filtered_array)  # Displays [30 40 50]

Numerical Solution of Differential Equations with scipy#

scipy offers several methods for numerically solving differential equations. Here are some examples:

Using odeint#

odeint is a function for solving ordinary differential equations (ODEs).

from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt

# Define the differential equation dy/dt = -2y
def model(y, t):
    dydt = -2 * y
    return dydt

# Initial conditions
y0 = 1
t = np.linspace(0, 5, 100)

# Solve the ODE
y = odeint(model, y0, t)

# Plot the solution
plt.plot(t, y)
plt.xlabel('Time')
plt.ylabel('y(t)')
plt.show()

Using solve_ivp#

solve_ivp is a more modern and flexible function for solving ODEs.

from scipy.integrate import solve_ivp
import numpy as np
import matplotlib.pyplot as plt

# Define the differential equation dy/dt = -2y
def model(t, y):
    dydt = -2 * y
    return dydt

# Initial conditions
y0 = [1]
t_span = (0, 5)
t_eval = np.linspace(0, 5, 100)

# Solve the ODE
sol = solve_ivp(model, t_span, y0, t_eval=t_eval)

# Plot the solution
plt.plot(sol.t, sol.y[0])
plt.xlabel('Time')
plt.ylabel('y(t)')
plt.show()

Using Transfer Functions#

You can also use transfer functions to solve linear systems.

from scipy import signal
import matplotlib.pyplot as plt

# Define the transfer function
numerator = [1]
denominator = [1, 2]
system = signal.TransferFunction(numerator, denominator)

# Step response
t, y = signal.step(system)

# Plot the response
plt.plot(t, y)
plt.xlabel('Time')
plt.ylabel('Step Response')
plt.show()

These methods are very powerful for modeling and analyzing dynamic systems.

Test yourself#

Propose a simple programming code that incorporates these different concepts and meets the following requirement: verify that the settling time at 5% of a 1st order system defined by the following differential equation \(\tau \dot{x}(t) + x(t) = K.e(t)\) is \(3\tau\). Perform the numerical experiment with \(\tau=1s\) and \(K=10\).

An example of solution is here.