\[ \begin{align}\begin{aligned}\newcommand\blank{~\underline{\hspace{1.2cm}}~}\\% Bold symbols (vectors) \newcommand\bs[1]{\mathbf{#1}}\\% Differential \newcommand\dd[2][]{\mathrm{d}^{#1}{#2}} % use as \dd, \dd{x}, or \dd[2]{x}\\% Poor man's siunitx \newcommand\unit[1]{\mathrm{#1}} \newcommand\num[1]{#1} \newcommand\qty[2]{#1~\unit{#2}}\\\newcommand\per{/} \newcommand\squared{{}^2} \newcommand\cubed{{}^3} % % Scale \newcommand\milli{\unit{m}} \newcommand\centi{\unit{c}} \newcommand\kilo{\unit{k}} \newcommand\mega{\unit{M}} % % Percent \newcommand\percent{\unit{{\kern-4mu}\%}} % % Angle \newcommand\radian{\unit{rad}} \newcommand\degree{\unit{{\kern-4mu}^\circ}} % % Time \newcommand\second{\unit{s}} \newcommand\s{\second} \newcommand\minute{\unit{min}} \newcommand\hour{\unit{h}} % % Distance \newcommand\meter{\unit{m}} \newcommand\m{\meter} \newcommand\inch{\unit{in}} \newcommand\foot{\unit{ft}} % % Force \newcommand\newton{\unit{N}} \newcommand\kip{\unit{kip}} % kilopound in "freedom" units - edit made by Sri % % Mass \newcommand\gram{\unit{g}} \newcommand\g{\gram} \newcommand\kilogram{\unit{kg}} \newcommand\kg{\kilogram} \newcommand\grain{\unit{grain}} \newcommand\ounce{\unit{oz}} \newcommand\pound{\unit{lbs}} % % Temperature \newcommand\kelvin{\unit{K}} \newcommand\K{\kelvin} \newcommand\celsius{\unit{{\kern-4mu}^\circ C}} \newcommand\C{\celsius} \newcommand\fahrenheit{\unit{{\kern-4mu}^\circ F}} \newcommand\F{\fahrenheit} % % Area \newcommand\sqft{\unit{sq\,\foot}} % square foot % % Volume \newcommand\liter{\unit{L}} \newcommand\gallon{\unit{gal}} % % Frequency \newcommand\hertz{\unit{Hz}} \newcommand\rpm{\unit{rpm}} % % Voltage \newcommand\volt{\unit{V}} \newcommand\V{\volt} \newcommand\millivolt{\milli\volt} \newcommand\mV{\milli\volt} \newcommand\kilovolt{\kilo\volt} \newcommand\kV{\kilo\volt} % % Current \newcommand\ampere{\unit{A}} \newcommand\A{\ampere} \newcommand\milliampereA{\milli\ampere} \newcommand\mA{\milli\ampere} \newcommand\kiloampereA{\kilo\ampere} \newcommand\kA{\kilo\ampere} % % Resistance \newcommand\ohm{\Omega} \newcommand\milliohm{\milli\ohm} \newcommand\kiloohm{\kilo\ohm} % correct SI spelling \newcommand\kilohm{\kilo\ohm} % "American" spelling used in siunitx \newcommand\megaohm{\mega\ohm} % correct SI spelling \newcommand\megohm{\mega\ohm} % "American" spelling used in siunitx % % Capacitance \newcommand\farad{\unit{F}} \newcommand\F{\farad} \newcommand\microfarad{\micro\farad} \newcommand\muF{\micro\farad} % % Inductance \newcommand\henry{\unit{H}} \newcommand\H{\henry} \newcommand\millihenry{\milli\henry} \newcommand\mH{\milli\henry} % % Power \newcommand\watt{\unit{W}} \newcommand\W{\watt} \newcommand\milliwatt{\milli\watt} \newcommand\mW{\milli\watt} \newcommand\kilowatt{\kilo\watt} \newcommand\kW{\kilo\watt} % % Energy \newcommand\joule{\unit{J}} \newcommand\J{\joule} % % Composite units % % Torque \newcommand\ozin{\unit{\ounce}\,\unit{in}} \newcommand\newtonmeter{\unit{\newton\,\meter}} % % Pressure \newcommand\psf{\unit{psf}} % pounds per square foot \newcommand\pcf{\unit{pcf}} % pounds per cubic foot \newcommand\pascal{\unit{Pa}} \newcommand\Pa{\pascal} \newcommand\ksi{\unit{ksi}} % kilopound per square inch \newcommand\bar{\unit{bar}} \end{aligned}\end{align} \]

Apr 28, 2026 | 838 words | 8 min read

12.1.1. Materials#

CONTROL STRUCTURES#

Here is the link to the Python’s Official Documentation on Control Flow constructs.

Control structures determine the flow of execution in a program.

01_control_structures.py 02_conditional_structures.py

Sequential Execution#

This is the default mode of execution where statements are executed line by line.

Conditional Statements#

These are used to execute a block of code based on a condition.

  • if - executes a block of code if the condition is True

  • if-else - executes a block of code if the condition is True, otherwise executes another block of code

  • if-elif-else - executes a block of code if the condition is True, otherwise checks another condition

  • nested if - if statement inside another if statement

Looping Statements#

These are used to execute a block of code repeatedly.

  • for - iterates over a sequence of items

  • while - executes a block of code as long as the condition is True

Control Statements#

These are used to control the flow of execution in a program.

  • break - exits the loop

  • continue - skips the current iteration

  • pass - does nothing

  • return - exits the function

Exception Statements#

These are used to signal errors. Exception handling is covered more fully in later modules.

  • assert - raises an exception if a condition is False

  • raise - raises an exception

CONDITIONAL STRUCTURES#

Conditional Structures, also known as selection structures or decision structures.

Keywords : if, elif, else

Single alternative example#

Write a program that prints a warning message if the temperature is greater than \(\qty{30}{\celsius}\).

temperature = int(input("Enter the temperature: "))
if temperature > 30:
    print("It's hot outside")
print("End of program")

Dual alternative example#

Write a program that prints a warning message if the temperature is greater than \(\qty{30}{\celsius}\), otherwise print a message that it’s a nice day.

temperature = int(input("Enter the temperature: "))

if temperature > 30:
    print("It's hot outside")
else:
    print("It's a nice day")
print("End of program")

Multiple alternative example#

Write a program that prints a warning message if the temperature is greater than \(\qty{30}{\celsius}\), a message that it’s a nice day if the temperature is between \(\qty{20}{\celsius}\) and \(\qty{30}{\celsius}\), and a message that it’s cold outside if the temperature is less than \(\qty{20}{\celsius}\).

temperature = int(input("Enter the temperature: "))
if temperature > 30:
    print("It's hot outside")
elif temperature >= 20 and temperature <= 30:
    print("It's a nice day")
else:
    print("It's cold outside")
print("End of program")

Nested example#

Write a program that prints a warning message if the temperature is greater than \(\qty{30}{\celsius}\) and the humidity is greater than \(\qty{50}{\percent}\), otherwise print a message that it’s a nice day.

temperature = int(input("Enter the temperature: "))
humidity = int(input("Enter the humidity: "))
if temperature > 30:
    if humidity > 50:
        print("It's hot and humid")
    else:
        print("It's hot but not humid")
else:
    print("It's a nice day")
print("End of program")

USER DEFINED FUNCTIONS#

03_user_defined_functions.py 04_user_defined_functions_execute.py

Functions are reusable code blocks that perform a specific task.

Types of functions:

  • Built-in functions - functions that are built into Python

  • User-defined functions - functions defined by the user

Built-in functions#

Examples: print(), range(), input() etc.

User defined functions (UDFs)#

  • def keyword is used to define a function

  • function name should be descriptive and meaningful (follows the same rules as variable names)

  • function call is required to execute the function

  • function can be called multiple times

  • function can be defined inside another function

Function Arguments and Parameters#

  • Arguments are values passed to a function

  • Parameters are variables used to define a function and are optional

  • Arguments are assigned to parameters based on their position

  • Arguments can be passed as positional arguments or keyword arguments

  • Default parameters are used when no argument is passed

Table 12.1 Positional and Keyword Arguments#

Positional arguments

Keyword arguments

Arguments passed to a function based on their position

Arguments passed to a function based on their name

Order of arguments is important

Order of arguments is not important

Number of arguments should match the number of parameters

Number of arguments should match the number of parameters

Note

  • All positional arguments must be placed before keyword arguments

  • The argument variable name and the parameter variable name do not have to match, just the positional order matters

Default parameters#

  • Default parameters are used when no argument is passed

  • Default parameters should be at the end

Return statement#

  • return statement is used to return a value from a function

  • return statement is optional

  • return statement can return multiple values

  • return statement can be used to exit a function

  • no other statement is executed after the return statement

Importing UDFs from another Python file#

The same import syntax covered in IMPORT METHODS for standard library modules works for user-created files too. This allows you to define functions in one Python file and use them in other Python files without copying and pasting code.

Note

Both files must be in the same directory for this to work.

Below is an example where we define a function in a file called helper_functions.py and then import it in another file called main.py to use it.

Listing 12.1 helper_functions.py#
def calculate_area(length, width):
    # this function calculates the area of a rectangle
    area = length * width
    return area

Using from X import Y syntax (imports the function directly by name):

Listing 12.2 main.py#
from helper_functions import calculate_area

length = int(input("Enter the length: "))
width = int(input("Enter the width: "))
area = calculate_area(length, width)

print(area)

Alternatively, using import X syntax (accesses the function via the module name):

Listing 12.3 main.py#
import helper_functions

length = int(input("Enter the length: "))
width = int(input("Enter the width: "))
area = helper_functions.calculate_area(length, width)

print(area)

Benefits of using functions#

  • Code reusability

  • Modularity

  • Easy debugging and maintenance

  • Better readability, organization, and efficiency

Function recursion (not covered in this course)#

  • Recursion is a technique in which a function calls itself

  • Base case is required to prevent infinite recursion

  • Recursion is used to solve complex problems and simplify code

VARIABLE SCOPE#

05_variable_scope.py

  • Scope is the region of the program where a variable is recognized

  • Scope can be local or global

    • Local scope - variables declared inside a function are local variables and can only be accessed inside that function

    • Global scope - variables declared outside a function are global variables and can be accessed throughout the program

  • Avoid using global variables as they can be modified from anywhere in the program and can lead to bugs

  • Use local variables instead to avoid conflicts and bugs in the program

  • Use the global keyword to modify a global variable inside a function

  • Known constants are acceptable to use as global variables such as gravity (g = 9.81) in physics calculations.