Loops and Conditionals

In [1]:
import numpy as np
  • $\textbf{np.random.randint}$ returns an ndarray of random intergers between the given range with uniform distribution
In [2]:
a = np.random.randint(0, 10, 8); print(a);
[7 9 5 9 2 8 5 6]
  • A way of printing out each element in $\textrm{a}$ by iterating over the length using $\textbf{for}$ loop
In [3]:
for i in a:
    print(i);
7
9
5
9
2
8
5
6
In [4]:
np.shape(a)
Out[4]:
(8,)
In [5]:
np.size(a)
Out[5]:
8
  • Iterating over all elements of $\textbf{a}$ by providing the index.
  • Remember that $\textbf{np.arange}$ generates linearly spaced array by default
In [6]:
for i in np.arange(0, np.size(a)): # np.size(a) = 8
    print("a[", i, "] = ", a[i]);
a[ 0 ] =  7
a[ 1 ] =  9
a[ 2 ] =  5
a[ 3 ] =  9
a[ 4 ] =  2
a[ 5 ] =  8
a[ 6 ] =  5
a[ 7 ] =  6
In [7]:
np.arange(0, np.size(a))
Out[7]:
array([0, 1, 2, 3, 4, 5, 6, 7])
  • Create a 2D array of dimension $4 \times 5$ and test out the printing through a loop
In [8]:
b = np.random.randint(0,10, size=(4,5)); print(b);
[[2 5 9 2 8]
 [6 5 3 9 1]
 [7 4 5 4 1]
 [6 3 6 3 5]]
  • Print the array row wise
In [9]:
for i in b:
    print("b row: ", i);
b row:  [2 5 9 2 8]
b row:  [6 5 3 9 1]
b row:  [7 4 5 4 1]
b row:  [6 3 6 3 5]

Nested Loops

  • Using nested loops to output all elements of $\textrm{b}$ one at a time
  • The iterator $\textrm{i}$ iterates over all rows while $\textrm{j}$ iterates over all columns
In [10]:
# This is a nested loop
for i in b: # Loops over all the rows
    for j in i: # Loops over all the elements of a row
        print(j);
2
5
9
2
8
6
5
3
9
1
7
4
5
4
1
6
3
6
3
5
  • $\textbf{np.nditer}$ can be used to iterate over all elements.
In [11]:
for i in np.nditer(b):
    print(i);
2
5
9
2
8
6
5
3
9
1
7
4
5
4
1
6
3
6
3
5
  • While using $\textbf{np.nditer}$, by default the array is read-only. We can change that by providing the following flag:
In [12]:
for x in np.nditer(b, op_flags = ['readwrite']):
   x[...] = 2*x
   print(x)
4
10
18
4
16
12
10
6
18
2
14
8
10
8
2
12
6
12
6
10
In [13]:
np.size(b)
Out[13]:
20
In [14]:
np.shape(b)
Out[14]:
(4, 5)

Conditional Statements

  • In python indentation is important to define the scope of the code. Keywords for conditional statements are: $\textbf{if}$, $\textbf{else}$, $\textbf{elif}$, $\textbf{and}$ & $\textbf{or}$
In [15]:
print(a);
print(np.arange(0, np.size(a))); # generate linearly spaced integers and print them
[7 9 5 9 2 8 5 6]
[0 1 2 3 4 5 6 7]
  • We want to print values of a until we reach the first zero.
In [16]:
for i in np.arange(0, np.size(a)): #notice how indentation works in conditional statements
    if a[i] == 0:
        break
    else:
        print(a[i]);
7
9
5
9
2
8
5
6
  • We want to count the number of zeros in the array
In [17]:
counter = 0;
for i in np.arange(0, np.size(a)):
    if a[i] == 0:
        counter = counter + 1;
        print("zero encountered at location: ", i);
print("Total zeros encoutered =",counter);
Total zeros encoutered = 0
In [18]:
#a = np.array([5, 4, 3, 2, 1]);
a = np.random.randint(0, 20, 7);
print(a);
print(np.size(a));
print(np.arange(1, np.size(a))) # np.arange(1, 5)
i = 1
print(np.arange(0, np.size(a)-i))
[ 6  4 16 19 12  9 13]
7
[1 2 3 4 5 6]
[0 1 2 3 4 5]

Sorting

  • We sort the array $\textbf{a}$ using $\textrm{bubble sort}$ algorithm. In this we can see how to utilize nested loops and conditionals at the same time
In [19]:
# Indentation is important: pressing tab
for i in np.arange(1, np.size(a)):
    for j in np.arange(0, np.size(a)-i):
        if a[j+1]<a[j]:
            temp = a[j+1]
            a[j+1] = a[j]
            a[j] = temp
        else:
            print("No swap required")
        print(j, a)
0 [ 4  6 16 19 12  9 13]
No swap required
1 [ 4  6 16 19 12  9 13]
No swap required
2 [ 4  6 16 19 12  9 13]
3 [ 4  6 16 12 19  9 13]
4 [ 4  6 16 12  9 19 13]
5 [ 4  6 16 12  9 13 19]
No swap required
0 [ 4  6 16 12  9 13 19]
No swap required
1 [ 4  6 16 12  9 13 19]
2 [ 4  6 12 16  9 13 19]
3 [ 4  6 12  9 16 13 19]
4 [ 4  6 12  9 13 16 19]
No swap required
0 [ 4  6 12  9 13 16 19]
No swap required
1 [ 4  6 12  9 13 16 19]
2 [ 4  6  9 12 13 16 19]
No swap required
3 [ 4  6  9 12 13 16 19]
No swap required
0 [ 4  6  9 12 13 16 19]
No swap required
1 [ 4  6  9 12 13 16 19]
No swap required
2 [ 4  6  9 12 13 16 19]
No swap required
0 [ 4  6  9 12 13 16 19]
No swap required
1 [ 4  6  9 12 13 16 19]
No swap required
0 [ 4  6  9 12 13 16 19]
In [20]:
print(a);
[ 4  6  9 12 13 16 19]
  • Python has an inbuilt $\textbf{sort}$ function.
In [21]:
b = np.sort(a); 
print(b);
[ 4  6  9 12 13 16 19]
  • We can also sort multidimensional arrays using $\textbf{sort}$
In [22]:
c = np.random.randint(0, 16, size=(4,4))
print(c)
d = np.sort(c,axis =1)
print("Sorted Matrix column-wise")
print(d)
d = np.sort(c,axis =0)
print("Sorted Matrix row-wise")
print(d)
[[14  6 12  5]
 [ 0  4 12  3]
 [12 10  2  6]
 [ 9  8  1 10]]
Sorted Matrix column-wise
[[ 5  6 12 14]
 [ 0  3  4 12]
 [ 2  6 10 12]
 [ 1  8  9 10]]
Sorted Matrix row-wise
[[ 0  4  1  3]
 [ 9  6  2  5]
 [12  8 12  6]
 [14 10 12 10]]
In [ ]: