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¶
|
Conditional jump |
|
Iterate over sequences |
|
Define a conditional loop |
Macros and Functions¶
|
Define a new function |
|
Store functions and statements |
if¶
- Purpose:
Conditional jump.
- Syntax:
if condition:
statements
elif condition:
statements
else:
statements
- Description:
The
ifstatement allows conditional execution of code blocks. Theconditionis evaluated and ifTrue, the correspondingstatementsare executed.- Examples:
Simple if statement:
if x > 0: y = np.sqrt(x) else: y = 0Multiple conditions:
if x > 0: result = 'positive' elif x < 0: result = 'negative' else: result = 'zero'- Note:
Python uses
elifinstead ofelseif, and requires colons and indentation instead ofend.
for¶
- Purpose:
Iterate over sequences.
- Syntax:
for variable in iterable:
statements
- Description:
The
forloop iterates over elements in aniterable(list, array, range, etc.). Thevariabletakes 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
whileloop repeatsstatementsas long as theconditionremainsTrue.- Examples:
Simple while loop:
i = 1 while i <= 10: print(f'Count: {i}') i += 1Convergence 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
Falseto avoid infinite loops.
def¶
- Purpose:
Define a new function.
- Syntax:
def function_name(input1, input2, ...):
statements
return output1, output2, ...
- Description:
The
defkeyword defines a new function with specified inputs. Usereturnto specify outputs. Functions can be defined in .py files or interactively.- Examples:
Simple function:
def square(x): return x**2Multiple inputs and outputs:
def add_subtract(a, b): sum_val = a + b diff_val = a - b return sum_val, diff_valFunction 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
defandreturn. 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
importto 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
importstatements to access module contents.