Dec 03, 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 updatedto 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
orQ
orquit
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.
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#
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 xm.append(x)
adds x to the end of the listm.insert(i, x)
inserts x at index im.remove(x)
removes the first occurrence of xm.pop(i)
removes the element at index im.clear()
removes all elementsm.extend(t)
adds the elements of t to the end of the listm += t
adds the elements of t to the end of the listm *= n
repeats the list n timesm.reverse()
reverses the listm.sort()
sorts the listm.copy()
returns a shallow copy of the listm.index(x)
returns the index of the first occurrence of xm.count(x)
returns the number of occurrences of xm.clear()
removes all elementslen(m)
returns the number of elements in mmin(m)
returns the smallest element in mmax(m)
returns the largest element in msum(m)
returns the sum of elements in msorted(m)
returns a new sorted list
Indexing and Slicing:
m[i]
returns the element at index im[i:j]
returns the elements from index i to j-1m[i:j:k]
returns the elements from index i to j-1 with step km[-i]
returns the element at index -im[-i:]
returns the elements from index -i to the end of the listm[:-i]
returns the elements from the beginning of the list to index -im[::-1]
returns the elements in reverse order
Indexing and Slicing exercise:
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
One-dimensional array: A collection of elements of the same type stored in a single row.
Two-dimensional array: A collection of elements of the same type stored in multiple rows and columns.
Multidimensional array: A collection of elements of the same type stored in multiple rows, columns, and depth.
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#
Creating an array using NumPy:
Import the NumPy library as
np
Create an array using the
np.array()
function
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.
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.
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.