Statements and macros

Statements describe algorithmic actions that can be executed. There are two different types of control statements, conditional and repetitive. The first group defines conditional jumps whereas the latter one defines repetition until a conditional statement is fulfilled. In Python, functions and modules are used to define new functionality or to store a sequence of statements in .py files.

Control statements

if

Conditional jump

for

Iterate over sequences

while

Define a conditional loop

Macros and Functions

def

Define a new function

module

Store functions and statements

if

Purpose:

Conditional jump.

Syntax:

if condition:
    statements
elif condition:
    statements
else:
    statements
Description:

The if statement allows conditional execution of code blocks. The condition is evaluated and if True, the corresponding statements are executed.

Examples:

Simple if statement:

if x > 0:
    y = np.sqrt(x)
else:
    y = 0

Multiple conditions:

if x > 0:
    result = 'positive'
elif x < 0:
    result = 'negative'
else:
    result = 'zero'
Note:

Python uses elif instead of elseif, and requires colons and indentation instead of end.

for

Purpose:

Iterate over sequences.

Syntax:

for variable in iterable:
    statements
Description:

The for loop iterates over elements in an iterable (list, array, range, etc.). The variable takes on each value from the iterable in sequence.

Examples:

Simple counting loop:

for i in range(1, 11):  # 1 to 10
    print(f'Iteration {i}')

Loop over array elements:

A = np.array([1, 4, 9, 16])
for element in A:
    print(element)

Nested loops:

A = np.zeros((3, 3))
for i in range(3):
    for j in range(3):
        A[i, j] = i + j
Note:

Python uses range() for numeric sequences and requires colons and indentation.

while

Purpose:

Define a conditional loop.

Syntax:

while condition:
    statements
Description:

The while loop repeats statements as long as the condition remains True.

Examples:

Simple while loop:

i = 1
while i <= 10:
    print(f'Count: {i}')
    i += 1

Convergence loop:

error = 1
tolerance = 1e-6
while error > tolerance:
    # ... computation ...
    error = abs(new_value - old_value)
Note:

Be careful to ensure the condition eventually becomes False to avoid infinite loops.

def

Purpose:

Define a new function.

Syntax:

def function_name(input1, input2, ...):
    statements
    return output1, output2, ...
Description:

The def keyword defines a new function with specified inputs. Use return to specify outputs. Functions can be defined in .py files or interactively.

Examples:

Simple function:

def square(x):
    return x**2

Multiple inputs and outputs:

def add_subtract(a, b):
    sum_val = a + b
    diff_val = a - b
    return sum_val, diff_val

Function with no return value:

def plot_data(x, y):
    plt.figure()
    plt.plot(x, y)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()
Note:

Python functions use def and return. Multiple return values are returned as tuples.

module

Purpose:

Store functions and statements.

Syntax:

# filename: my_module.py
"""Module documentation"""

import numpy as np

def function1():
    # function definition
    pass

# module-level code
statements
Description:

Modules are .py files that contain Python code. They can include functions, classes, and executable statements. Use import to access module contents.

Examples:

Simple module (saved as analysis.py):

"""Data analysis module"""
import numpy as np
import matplotlib.pyplot as plt

def load_data(filename):
    return np.loadtxt(filename)

def plot_results(data):
    plt.figure()
    plt.plot(data)
    plt.show()

# Module-level code (runs when imported)
print("Analysis module loaded")

Using the module:

import analysis

data = analysis.load_data('data.txt')
analysis.plot_results(data)

Alternative import:

from analysis import load_data, plot_results

data = load_data('data.txt')
plot_results(data)
Note:

Modules create their own namespace. Use import statements to access module contents.