\[ \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 | 874 words | 9 min read

7.1.1. Materials#

REPETITION STRUCTURES#

01_repetition_structures.py 02_while_loop.py 03_for_loop.py 04_nested_loops.py 05_control_statements.py

Repetition structures are also known as iteration structures or loops.

keywords : while, for

While loop#

A while loop is used to repeatedly execute a block of statements as long as the condition is True.

Definite while loop: a loop that has a fixed number of iterations

  • initialize a control variable before entering the loop

  • check the control variable and enter the loop if the condition is True

  • update the control variable inside the loop such that the condition will eventually become False

Infinite while loop - a loop that never ends

  • occurs when the condition is always True or the condition is not updated

  • to stop an infinite loop, press Ctrl + C

Indefinite while loop - a loop that does not have a fixed number of iterations

  • the number of iterations is determined by the user input

  • the loop continues until a specific condition is met

Sentinel-controlled loop - a distinct value that signals the end of the loop

  • the sentinel value is used to stop the loop

  • the sentinel value should be distinct from other values in the sequence

  • example:

    • \(0\) or \(-1\) to signal the end of the loop

    • q or Q or quit to quit the program

    • ‘done’ to stop entering values

    • EOF (end of file) to signal the end of the file

For loop#

A for loop is used to iterate over a sequence or other iterable objects.

Table 7.2 Loops Differences#

For loop

While loop

is used when the number of iterations is known

is used when the number of iterations is not known

is more concise and readable

is more flexible and powerful

Nested loop#

A loop inside another loop.

Loop control statements#

These statements change the execution from its normal sequence.

  • break: Terminates the loop statement and transfers execution to the statement immediately following the loop.

  • continue: Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

  • pass: Does nothing.

  • return: Exits the function and returns a value.

NUMPY ARRAYS#

06_numpy_arrays.py

Lists#

A list is a collection of elements of different types stored in non-contiguous memory locations.

List manipulation:#

For a mutable sequence m , index i, iterable object t, and arbitrary object x:

  • m[i] = x replaces the element at index i with x

  • m.append(x) adds x to the end of the list

  • m.insert(i, x) inserts x at index i

  • m.remove(x) removes the first occurrence of x

  • m.pop(i) removes the element at index i

  • m.clear() removes all elements

  • m.extend(t) adds the elements of t to the end of the list

  • m += t adds the elements of t to the end of the list

  • m *= n repeats the list n times

  • m.reverse() reverses the list

  • m.sort() sorts the list

  • m.copy() returns a shallow copy of the list

  • m.index(x) returns the index of the first occurrence of x

  • m.count(x) returns the number of occurrences of x

  • m.clear() removes all elements

  • len(m) returns the number of elements in m

  • min(m) returns the smallest element in m

  • max(m) returns the largest element in m

  • sum(m) returns the sum of elements in m

  • sorted(m) returns a new sorted list

Indexing and Slicing:

  • m[i] returns the element at index i

  • m[i:j] returns the elements from index i to j-1

  • m[i:j:k] returns the elements from index i to j-1 with step k

  • m[-i] returns the element at index -i

  • m[-i:] returns the elements from index -i to the end of the list

  • m[:-i] returns the elements from the beginning of the list to index -i

  • m[::-1] returns the elements in reverse order

Indexing and Slicing exercise:

Table 7.3 String indexing in Python#

H

e

l

l

o

W

o

r

l

d

,

H

a

i

l

P

u

r

d

u

e

!

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

-25

-24

-23

-22

-21

-20

-19

-18

-17

-16

-15

-14

-13

-12

-11

-10

-9

-8

-7

-6

-5

-4

-3

-2

-1

# string initialization
s = "Hello World, Hail Purdue!"

s[0] = 'H'

s[18:24] = 'Purdue'
s[-7:-1] = 'Purdue'

s[0:5] = 'Hello'
s[:5]  = 'Hello'

s[-1]        = '!'
s[24]        = '!'
s[-1:]       = '!'
s[24:]       = '!'
s[len(s)-1]  = '!'
s[-1:len(s)] = '!'

s[:-1] = 'Hello World, Hail Purdue'
s[:24] = 'Hello World, Hail Purdue'

s[::-1]      = '!eudruP liaH ,dlroW olleH'
s[-1:-26:-1] = '!eudruP liaH ,dlroW olleH'

Arrays#

An array is a collection of elements of the same type stored in contiguous memory locations. Here is the link to the Python Official Documentation on NumPy

  1. One-dimensional array: A collection of elements of the same type stored in a single row.

  2. Two-dimensional array: A collection of elements of the same type stored in multiple rows and columns.

  3. Multidimensional array: A collection of elements of the same type stored in multiple rows, columns, and depth.

  4. Accessing elements in an array:

    • One-dimensional array: array_name[index]

    • Two-dimensional array: array_name[row][column]

    • Multidimensional array: array_name[depth][row][column]

Arrays using NumPy#

  1. Creating an array using NumPy:

    • Import the NumPy library as np

    • Create an array using the np.array() function

  2. NumPy array attributes:

    • shape Returns the dimensions of the array.

    • size Returns the total number of elements in the array.

    • ndim Returns the number of dimensions of the array.

    • dtype Returns the data type of the elements in the array.

  3. NumPy array functions:

    • np.zeros(shape) Creates an array of zeros with the specified shape.

    • np.ones(shape) Creates an array of ones with the specified shape.

    • np.full(shape, value) Creates an array of the specified shape filled with the specified value.

    • np.arange(start, stop, step) Creates an array with a range of values from start to stop with the specified step.

    • np.linspace(start, stop, num) Creates an array with a range of values from start to stop with the specified number of elements.

    • np.random.rand(shape) Creates an array of random values with the specified shape.

    • np.reshape(array, new_shape) Reshapes the array to the specified new shape.

    • np.transpose(array) Transposes the array.

    • np.concatenate((array1, array2), axis) Concatenates two arrays along the specified axis.

    • np.vstack((array1, array2)) Stacks arrays vertically.

    • np.hstack((array1, array2)) Stacks arrays horizontally.

    • np.split(array, indices_or_sections) Splits the array into multiple sub-arrays.

    • np.max(array) Returns the maximum value in the array.

    • np.min(array) Returns the minimum value in the array.

    • np.mean(array) Returns the mean of the values in the array.

    • np.median(array) Returns the median of the values in the array.

  4. NumPy array operations:

    • Element-wise operations: Perform operations on corresponding elements of two arrays.

    • Broadcasting: Perform operations on arrays of different shapes by broadcasting the smaller array to match the larger array’s shape.

    • Dot product: Perform matrix multiplication using the dot() function.