\[ \begin{align}\begin{aligned}\newcommand\blank{~\underline{\hspace{1.2cm}}~}\\% Bold symbols (vectors) \newcommand\bs[1]{\mathbf{#1}}\\% 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{\%}} % % Angle \newcommand\radian{\unit{rad}} \newcommand\degree{\unit{{}^\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}} % % Temperature \newcommand\kelvin{\unit{K}} \newcommand\K{\kelvin} \newcommand\celsius{\unit{{}^\circ C}} \newcommand\C{\celsius} \newcommand\fahrenheit{\unit{{}^\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 % % 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} \]

Oct 24, 2024 | 747 words | 7 min read

6.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

  • 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 30 degrees 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 30 degrees 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 30 degrees Celsius, a message that it’s a nice day if the temperature is between 20 and 30 degrees Celsius, and a message that it’s cold outside if the temperature is less than 20 degrees 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 30 degrees Celsius and the humidity is greater than 50%, 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#

  • 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 6.2 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

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

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 determines the visibility of a variable

  • 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.