0% found this document useful (0 votes)
5 views23 pages

Shivakumar IE6400 Lecture4 STUDENT Part 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views23 pages

Shivakumar IE6400 Lecture4 STUDENT Part 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

IE6400 Foundations for Data Analytics

Engineering

Fall 2024
-- STUDENT VERSION --

Basic of Python - Part 3

Python Conditions and If statements

Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b

Exercise 1 Creating the If statement

In [76]: a = 33
b = 200

# --- Added the code here ---


if b>a:
# ---------------------------
print("b is greater than a")

b is greater than a

Exercise 2 Creating the Elif statement

In [77]: a = 33
b = 33

if b > a:
print("b is greater than a")
# --- Added the code here ---
elif a==b:
# ---------------------------
print("a and b are equal")

a and b are equal

Exercise 3 Creating the Else statement


The else keyword catches anything which isn't caught by the preceding conditions.

In [78]: a = 200
b = 33

if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
# --- Added the code here ---
else:
# ---------------------------
print("a is greater than b")

a is greater than b

In [79]: a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

b is not greater than a

Exercise 4 Short Hand If

In [80]: a = 200
b = 33

# --- Added the code here ---


if a>b: print("a is greater than b")
# ---------------------------

a is greater than b

Exercise 5 Short Hand If ... Else

In [81]: a = 2
b = 330

# --- Added the code here ---


print("A") if a>b else print("B")
# ---------------------------

In [82]: a = 330
b = 330

# --- Added the code here ---


print("A") if a>b else print("=") if a==b else print("B")
# ---------------------------

Exercise 6 Logical Operators


And operator

In [84]: a = 200
b = 33
c = 500

# --- Added the code here ---


if a > b and c > a:
# ---------------------------
print("Both conditions are True")

Both conditions are True

OR operator

In [85]: a = 200
b = 33
c = 500

# --- Added the code here ---


if a > b or a > c:
# ---------------------------
print("At least one of the conditions is True")

At least one of the conditions is True

Not operator

In [86]: a = 33
b = 200

# --- Added the code here ---


if not a > b:
# ---------------------------
print("a is NOT greater than b")

a is NOT greater than b

Exercise 7 Nested If

In [87]: x = 41

if x > 10:
print("Above ten,")

# --- Added the code here ---


if x>20:
# ---------------------------
print("and also above 20!")
else:
print("but not above 20.")

Above ten,
and also above 20!

Exercise 8 The pass Statement


In [88]: a = 33
b = 200

if b > a:
# --- Added the code here ---
pass
# ---------------------------

Python While Loops

Exercise 9 Creating the while Loop

In [89]: i = 1
# --- Added the code here ---
while i<6:
# ---------------------------
print(i)
i = i + 1

1
2
3
4
5

Exercise 10 The break Statement

In [91]: i = 1
while i < 6:
print(i)

# --- Added the code here ---


if i == 3:
break
# ---------------------------

i = i + 1

1
2
3

Exercise 11 The continue Statement

In [92]: i = 0
while i < 6:
i += 1 # same as i = i + 1

# --- Added the code here ---


if i == 3:
continue
# ---------------------------

print(i)
1
2
4
5
6

Exercise 12 The else Statement

In [93]: i = 1
while i < 6:
print(i)
i += 1

# --- Added the code here ---


else:
# ---------------------------
print("i is no longer less than 6")

1
2
3
4
5
i is no longer less than 6

Python For Loops

Exercise 13 Creating the For Loop

In [94]: fruits = ["apple", "banana", "cherry","Mango"]

# --- Added the code here ---


for x in fruits:
# ---------------------------
print(x)

apple
banana
cherry
Mango

Exercise 14 Looping Through a String

In [96]: # --- Added the code here ---


for x in "banana":
# ---------------------------
print(x)

b
a
n
a
n
a

Exercise 15 The break Statement


In [97]: fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

# --- Added the code here ---


if x == "banana":
break
#
# ---------------------------

apple
banana

In [98]: fruits = ["apple", "banana", "cherry"]


for x in fruits:
# --- Added the code here ---
if x == "banana":
break
# ---------------------------

print(x)

apple

Exercise 16 The continue Statement

In [99]: fruits = ["apple", "banana", "cherry"]


for x in fruits:
# --- Added the code here ---
if x == "banana":
continue
# ---------------------------

print(x)

apple
cherry

Exercise 17 The range() Function

In [100… # --- Added the code here ---


for x in range(6):
# ---------------------------
print(x)

0
1
2
3
4
5

In [101… # --- Added the code here ---


for x in range(2,6):
# ---------------------------
print(x)
2
3
4
5

In [103… # --- Added the code here ---


for x in range(2,30,3):
# ---------------------------
print(x)

2
5
8
11
14
17
20
23
26
29

Exercise 18 Else in For Loop

In [104… for x in range(6):


print(x)
# --- Added the code here ---
else:
# ---------------------------
print("Finally finished!")

0
1
2
3
4
5
Finally finished!

In [107… for x in range(6):


# --- Added the code here ---
if x==3: break
# ---------------------------
print(x)
else:
print("Finally finished!")

0
1
2

Exercise 19 Nested Loops

In [108… adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
# --- Added the code here ---
for y in fruits:
# ---------------------------
print(x, y)

red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

Exercise 20 The pass Statement

In [109… for x in [0, 1, 2]:


pass

Python Functions

Exercise 21 Creating a Function

In [1]: # --- Added the code here ---


def my_function():
# ---------------------------
print('Northeastern University')

In [2]: # No arguments
my_function()

Northeastern University

Exercise 22 Arguments

In [110… # Single arguments

# --- Added the code here ---


def my_function(campus):
# ---------------------------
print('Northeastern University ' + str(campus))

In [111… my_function('Boston')
my_function('Vancouver')
my_function('Seattle')

Northeastern University Boston


Northeastern University Vancouver
Northeastern University Seattle

Multiple Arguments

In [112… # Multiple arguments

# --- Added the code here ---


def my_function(a,b):
# ---------------------------
print(str(b) + ' ' + str(a))

In [113… my_function('University', 'Northeastern')

Northeastern University

Exercise 23 Arbitrary Arguments, *args

In [114… # --- Added the code here ---


def my_function(*cname):
# ---------------------------
print("Northeastern University " + cname[2])

my_function("Boston", "Vancouver", "Seattle")

Northeastern University Seattle

Exercise 24 Keyword Arguments

In [3]: def my_function(cname3, cname2, cname1):


print("Northeastern University " + cname3)

# --- Added the code here ---


my_function(cname1 = "Boston", cname2 = "Vnacouver", cname3 = "Seatle")
# ---------------------------

Northeastern University Seatle

In [4]: def my_function(a,b):


print(str(a) + ' ' + str(b))

# --- Added the code here ---


my_function(b='University', a='Northeastern')
# ---------------------------

Northeastern University

Exercise 25 Arbitrary Keyword Arguments, **kwargs

In [116… # --- Added the code here ---


def my_function(**kid):
print("His last name is " + kid["lname"])
# ---------------------------

my_function(fname = "Tobias", lname = "Sky")

His last name is Sky

Exercise 26 Default Parameter Value

In [117… # Default parameter:

# --- Added the code here ---


def my_function(a,b='University'):
# ---------------------------
print(str(a) + ' ' + str(b))
my_function('Northeastern')
my_function('Northeastern', 'Boston')

Northeastern University
Northeastern Boston

In [118… # --- Added the code here ---


def my_function(country = "Norway"):
# ---------------------------
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

I am from Sweden
I am from India
I am from Norway
I am from Brazil

Exercise 27 Passing a List as an Argument

In [5]: def my_function(food):


for x in food:
print(x)

# --- Added the code here ---


fruits = ["apple", "banana", "cherry"]
# ---------------------------

my_function(fruits)

apple
banana
cherry

Exercise 28 Return Values

In [6]: def my_function(x):


# --- Added the code here ---
return 5*x
# ---------------------------

print(my_function(3))
print(my_function(5))
print(my_function(9))

15
25
45

In [7]: def add(a,b):


y = a + b
return y

add(1,2)

3
Out[7]:
In [8]: # Return a list
def vector(a,b):
y=list(range(a,(b+1)))
return y

z = vector(10,40)
print(z)

[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40]

In [9]: # Return a dictionary


def dictionary(a,b):
y={'University':a,'City':b}
return y

z=dictionary('NEU','Boston')
print(z)

{'University': 'NEU', 'City': 'Boston'}

Exercise 29 The pass Statement

In [10]: def myfunction():


pass

myfunction()

Python Lambda

Syntax - lambda arguments : expression

Exercise 30 Creating the Lambda functions

In [11]: # --- Added the code here ---


x = lambda a:a+10
# ---------------------------

print(x(5))
print(x(7))
print(x(9))

15
17
19

In [12]: # --- Added the code here ---


x = lambda a,b:a*b
# ---------------------------

print(x(5, 6))
print(x(7, 5))
print(x(3, 4))

30
35
12
In [13]: # --- Added the code here ---
x = lambda a, b, c : a+b+c
# ---------------------------

print(x(5, 6, 2))
print(x(1, 2, 3))
print(x(3, 3, 3))

13
6
9

Python NumPy

Exercise 31 NumPy Getting Started

Installation of NumPy

In [ ]: #!pip install numpy

Import NumPy

In [14]: import numpy as np

Checking NumPy Version

In [15]: import numpy as np

print(np.__version__)

1.21.5

Exercise 32 Creating a NumPy Array

In [17]: import numpy as np

# --- Added the code here ---


arr = np.array([1, 2, 3, 4, 5])
# ---------------------------

print(arr)

print(type(arr))

[1 2 3 4 5]
<class 'numpy.ndarray'>

In [19]: import numpy as np

# --- Added the code here ---


arr = np.array((1, 2, 3, 4, 5))
# ---------------------------

print(arr)
[1 2 3 4 5]

Dimensions in Arrays

0-D Arrays

In [20]: import numpy as np

arr = np.array(42)

print(arr)

42

1-D Arrays

In [24]: import numpy as np

# --- Added the code here ---


arr = np.array([1, 2, 3, 4, 5])
# ---------------------------

print(arr)

[1 2 3 4 5]

2-D Arrays

In [23]: import numpy as np

# --- Added the code here ---


arr = np.array([[1, 2, 3], [4, 5, 6]])
# ---------------------------

print(arr)

[[1 2 3]
[4 5 6]]

3-D arrays

In [27]: import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(arr)

[[[1 2 3]
[4 5 6]]

[[1 2 3]
[4 5 6]]]

Exercise 33 Check Number of Dimensions

In [29]: import numpy as np


a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

# --- Added the code here ---


print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
# ---------------------------

0
1
2
3

Exercise 34 Higher Dimensional Arrays

In [120… import numpy as np

# --- Added the code here ---


arr = np.array([1, 2, 3, 4], ndmin=5)
# ---------------------------

print(arr)
print('Number of dimensions :',arr.ndim)

[[[[[1 2 3 4]]]]]
Number of dimensions : 5

Exercise 35 Access Array Elements

In [31]: import numpy as np

arr = np.array([1, 2, 3, 4])

# --- Added the code here ---


print(arr[0])
# ---------------------------

In [32]: import numpy as np

arr = np.array([1, 2, 3, 4])

# --- Added the code here ---


print(arr[1])
# ---------------------------

In [33]: import numpy as np

arr = np.array([1, 2, 3, 4])

# --- Added the code here ---


print(arr[2] + arr[3])
# ---------------------------
7

Access 2-D Arrays

In [34]: import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print(arr)

# --- Added the code here ---


print('2nd element on 1st row: ', arr[0,1])
# ---------------------------

[[ 1 2 3 4 5]
[ 6 7 8 9 10]]
2nd element on 1st row: 2

In [122… import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print(arr)

# --- Added the code here ---


print('5th element on 2nd row: ', arr[1,4])
# ---------------------------

[[ 1 2 3 4 5]
[ 6 7 8 9 10]]
5th element on 2nd row: 10

Access 3-D Arrays

In [ ]: import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

print(arr)

# --- Added the code here ---


print(arr[])
# ---------------------------

Negative Indexing

In [35]: import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

# --- Added the code here ---


print('Last element from 2nd dim: ', arr[1,-1])
# ---------------------------

Last element from 2nd dim: 10

Exercise 36 Slicing arrays


In [36]: import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

# --- Added the code here ---


print(arr[1:5])
# ---------------------------

[2 3 4 5]

In [39]: import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

# --- Added the code here ---


print(arr[4:])
# ---------------------------

[5 6 7]

In [40]: import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

# --- Added the code here ---


print(arr[:4])
# ---------------------------

[1 2 3 4]

Negative Slicing

In [41]: import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

# --- Added the code here ---


print(arr[-3:-1])
# ---------------------------

[5 6]

Exercise 37 Slicing 2-D Arrays

In [42]: import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

# --- Added the code here ---


print(arr[1,1:4])
# ---------------------------

[7 8 9]

In [123… import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

# --- Added the code here ---


print(arr[0:2,2:])
# ---------------------------

[[ 3 4 5]
[ 8 9 10]]

In [44]: import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

# --- Added the code here ---


print(arr[0:2,1:4])
# ---------------------------

[[2 3 4]
[7 8 9]]

Exercise 38 Get the Shape of an Array

In [38]: import numpy as np

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

# --- Added the code here ---


print(arr.shape)
# ---------------------------

(2, 4)

In [124… import numpy as np

arr = np.array([1, 2, 3, 4], ndmin=5)

print(arr)
print('shape of array :', arr.shape)

[[[[[1 2 3 4]]]]]
shape of array : (1, 1, 1, 1, 4)

Exercise 39 Reshaping arrays

Reshape From 1-D to 2-D

In [46]: import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

# --- Added the code here ---


newarr = arr.reshape(4,3)
# ---------------------------

print(newarr)

[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Reshape From 1-D to 3-D

In [48]: import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

# --- Added the code here ---


newarr = arr.reshape(2,3,2)
# ---------------------------

print(newarr)

[[[ 1 2]
[ 3 4]
[ 5 6]]

[[ 7 8]
[ 9 10]
[11 12]]]

Exercise 40 Flattening the arrays

In [49]: import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

# --- Added the code here ---


newarr = arr.reshape(-1)
# ---------------------------

print(newarr)

[1 2 3 4 5 6]

Exercise 41 Joining NumPy Arrays

In [51]: import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

# --- Added the code here ---


arr = np.concatenate((arr1, arr2))
# ---------------------------

print(arr)

[1 2 3 4 5 6]

In [125… import numpy as np

arr1 = np.array([[1, 2], [3, 4]])

arr2 = np.array([[5, 6], [7, 8]])

# --- Added the code here ---


arr = np.concatenate((arr1, arr2), axis=1)
# ---------------------------

print(arr)

[[1 2 5 6]
[3 4 7 8]]

Exercise 42 Joining Arrays Using Stack Functions

In [54]: import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

# --- Added the code here ---


arr = np.stack((arr1, arr2), axis=1)
# ---------------------------

print(arr)

[[1 4]
[2 5]
[3 6]]

Stacking Along Rows

In [55]: import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

# --- Added the code here ---


arr = np.hstack((arr1, arr2))
# ---------------------------

print(arr)

[1 2 3 4 5 6]

Stacking Along Columns

In [126… import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

# --- Added the code here ---


arr = np.vstack((arr1, arr2))
# ---------------------------

print(arr)

[[1 2 3]
[4 5 6]]

Stacking Along Height (depth)


In [57]: import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

# --- Added the code here ---


arr = np.dstack((arr1, arr2))
# ---------------------------

print(arr)

[[[1 4]
[2 5]
[3 6]]]

Exercise 43 Splitting NumPy Arrays

In [58]: import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])

# --- Added the code here ---


newarr = np.array_split(arr, 3)
# ---------------------------

print(newarr)

[array([1, 2]), array([3, 4]), array([5, 6])]

In [59]: import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])

# --- Added the code here ---


newarr = np.array_split(arr, 4)
# ---------------------------

print(newarr)

[array([1, 2]), array([3, 4]), array([5]), array([6])]

Exercise 44 Creating the NumPy zeros

1-dimensional array using zeros

In [60]: import numpy as np

# --- Added the code here ---


one_dim_array = np.zeros(4)
# ---------------------------

print(one_dim_array)

[0. 0. 0. 0.]

2-dimensional array using zeros


N x M array

In [61]: import numpy as np

two_dim_array = np.zeros((2, 3))


print(two_dim_array)

[[0. 0. 0.]
[0. 0. 0.]]

1 x N array

In [62]: import numpy as np

one_row_array = np.zeros((1, 4))


print(one_row_array)

[[0. 0. 0. 0.]]

N x 1 array

In [63]: import numpy as np

one_col_array = np.zeros((4, 1))


print(one_col_array)

[[0.]
[0.]
[0.]
[0.]]

1-dimensional int-type array

In [64]: import numpy as np

one_dim_int_array = np.zeros(3, dtype=np.int64)


print(one_dim_int_array)

[0 0 0]

2-dimensional int-type array

In [65]: import numpy as np

two_dim_int_array = np.zeros((2, 4), dtype=np.int64)


print(two_dim_int_array)

[[0 0 0 0]
[0 0 0 0]]

Exercise 45 Creating the NumPy ones

1-dimensional array using ones

In [66]: import numpy as np

# --- Added the code here ---


one_dim_array = np.ones(4)
# ---------------------------

print(one_dim_array)

[1. 1. 1. 1.]

2-dimensional array using ones

In [67]: import numpy as np

two_dim_array = np.ones((4, 2))


print(two_dim_array)

[[1. 1.]
[1. 1.]
[1. 1.]
[1. 1.]]

Exercise 46 NumPy arange function

In [68]: # --- Added the code here ---


np.arange(start=1, stop=10, step=3)
# ---------------------------

array([1, 4, 7])
Out[68]:

Exercise 47 NumPy linspace function

In [71]: import numpy as np

# --- Added the code here ---


np.linspace(3.0, 4.0, num=7)
# ---------------------------

array([3. , 3.16666667, 3.33333333, 3.5 , 3.66666667,


Out[71]:
3.83333333, 4. ])

In [72]: # --- Added the code here ---


np.linspace(3.0,4.0, num=7, endpoint=False)
# ---------------------------

array([3. , 3.14285714, 3.28571429, 3.42857143, 3.57142857,


Out[72]:
3.71428571, 3.85714286])

In [74]: # --- Added the code here ---


np.linspace(3.0,4.0, num=7, retstep=True)
# ---------------------------

(array([3. , 3.16666667, 3.33333333, 3.5 , 3.66666667,


Out[74]:
3.83333333, 4. ]),
0.16666666666666666)

Exercise 48 NumPy eye function

In [75]: # Identity matrix

# --- Added the code here ---


np.eye(6)
# ---------------------------

array([[1., 0., 0., 0., 0., 0.],


Out[75]:
[0., 1., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0.],
[0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 1.]])

Revised Date: July 18, 2024

You might also like