Python - Data Engineering
Python - Data Engineering
Python
Indentation
Data Types
Text-type str
Numeric Types int, float, complex
If you want to specify the data type, you can use the
following constructor functions.
fi
Operators
1) Arithmetic Operators
2) Assignment Operators
3) Comparison Operators
4) Logical Operators
5) Identity Operators
6) Membership Operators
7) Bitwise Operators
1) Arithmetic Operators
2) Assignment Operators
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
3) Comparison Operators
4) Logical Operators
5) Identity Operators
6) Membership Operators
7) Bitwise Operators
List
create list:
list items
Ordered
List items have a defined order and that order will not
change.
newly added items will be placed at the end of list.
Changeable
The list is changeable, meaning that we can change, add and
remove items in a list. After it has been created.
Allow duplicates
Since lists are indexed, lists can have items with the same
value.
List length
To determine how many items a list has, use len() function
ex - len(mylist)
Type
From Python's perspective, lists are defined as objects with
the data type 'list'
ex -
thisislist = list(("apple", "banana", "cherry"))
round-brackets
print(thisislist)
Python Collections(Arrays)
Tuple
create tuple:
Tuple items
10
Ordered
Tuple items have a defined order and that order will not
change.
newly added items will be placed at the end of Tuple.
Changeable
The Tuple is changeable, meaning that we can change, add and
remove items in a Tuple. After it has been created.
Allow duplicates
Since Tuples are indexed, Tuples can have items with the same
value.
Tuple length
To determine how many items a Tuple has, use len() function
ex - len(myTuples)
Set
Create set:
myset = {"apple", "banana", "cherry"}
Set items
A set is collection which is unordered, unchangeable and do
not allow duplicate values.
Note - Set items are unchangeable, but you can remove items
and add new items
Unordered
The items in a set do not have a defined order.
Set items can appear in a different order every time you use
them, and can not be referred to by index or key.
Unchangeable
You can not change its items, but you can remove items and add
new items.
11
set length
To determine how many items a set has, use the len() function.
Type
From Python's perspective, Sets are defined as objects with
the data type 'Set'
ex -
thisisSet = Set(("apple", "banana", "cherry"))
round-brackets
print(thisisSet)
12
Dictionaries
Create Dictionary:
thisisdict = {
"brand":"ford",
"model":"Mustang"
"year":"1964"
}
Dictionary
Are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and
do not allow duplicates. '''(As of Python version 3.7,
dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.)'''
Dictionary items
Dictionary items are ordered, changeable and does not allow
duplicates.
ex -
#Print the "brand" value of the dictionary
print(thisisdict["brand"])
Ordered or unordered?
Unordered means that the items does not have a defined order,
you cannot refer to an item by using an index.
13
Changeable
We can change, add or remove items after the dictionary has
been created.
dict length
To determine how many items a dict has, use the len()
function.
thisisdict = {
"brand":"ford",
"model":"Mustang"
"year":"1964"
}
Type
From Python's perspective, dicts are defined as objects with
the data type 'dict'
14
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
If statement
ex -
a = 33
b = 200
if b > a:
print("b is greater than a")
Elif
ex -
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
15
Else
ex -
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Short hand if
Ex -
Q - One line if statement:
If you have only one statement to execute, one for if and one
for else, you can put it all on the same line:
Ex -
Q - One line if…else statement:
a = 2
b = 330
print("A") if a > b else print(“B")
16
And
Ex -
Q - test if a is greater than b AND if c is greater than a:
a = 200
b = 33
c = 500
If a > b and c > a:
print(“Both conditions are True”)
Or
Ex -
Q - Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
If a > b or a >c:
print(“At least one of the conditions is True”)
Nested if
Ex -
x = 41
If x > 10:
print(“Above Ten,”)
If x > 20:
print(“and also above 20!”)
else:
print(“but not above 20”)
17
Ex -
a = 33
b = 200
If b>a:
Pass
Python Loops
• While loops
• For loops
Ex -
Q - Print I as long as i is less than 6:
i = 1
While i < 6:
print(i)
i += 1
18
With the break statement we can stop the loop even if the
while condition is True:
Ex -
i = 1
While i < 6:
print(i)
If i == 3:
break
i += 1
Ex -
i = 0
While i < 6:
i += 1
If I == 3:
continue
print(i)
With the else statement we can run a block of code once when
the condition no longer is true:
Ex -
Q - Print a message once the condition is false:
ii = 1
While i < 6:
print(i)
I += 1
else:
print(“i is no longer less than 6”)
19
With the for loop we can execute a set of statements, once for
each item in a list, tuple, set etc.
Ex -
Ex -
For x in “banana”:
print(x)
With the break we can stop the loop before it has looped
through all the items:
Ex - 1
20
If x == “banana”:
break
Ex - 2
Q - Exit the loop when x is “banana”, but this time the break
comes before the print:
Ex -
Ex -
21
For x in range(2,6):
print(x)
Ex -
For x in range(2,30,3):
print(x)
Ex -
For x in range(6):
print(x)
Else:
print(“finally finished!”)
22
Ex -
Q - Break the loop when x is 3, and see what happens with the
else block:
For x in range(6):
If x == 3: break
print(x)
Else:
print(“Finally finished!”)
Nested loops
Ex -
For x in adj:
For y in fruits:
print(x,y)
For loops cannot be empty, but if you for some reason have a
for loop with no content, put in the pass statement to avoid
getting an error.
Ex -
For x in [0,1,2]
pass
23
Try Except
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute, regardless of the result
of the try and except blocks.
Exception Handling
Ex -
Try:
print(x)
Except:
print(“An exception occurred!”)
Since the try block raises an error, the except block will be
executed.
Without the try block, the program will crash and raise an
error.
Many exception
Ex -
Try:
print(x)
24
Except NameError:
print(“Variable x is not defined”)
Except:
print(“Something else went wrong”)
Else
Ex -
Try:
print(“Hello”)
Except:
print(“Something went wrong”)
Else:
print(“Nothing went wrong”)
Finally
Ex - 1
Try:
print(x)
Except:
print(“Something went wrong”)
Finally:
print(“The ‘try except’ is finished ”)
25
Ex - 2
Try:
F = open(“demofile.txt”)
Try:
F.write(“lorum ipsum”)
except:
print(“Something went wrong when writing the file”)
Finally:
F.close()
Except:
print(“Something went wrong when opening the file”)
Raise an exception
Ex -
x = -1
If x < 0:
Raise Exception(“Sorry, no numbers below zero”)
Ex -
26
x = “Hello”
The key function for working with files I Python is the open()
function.
The open() function takes two parameters; filename, and mode.
There are four different methods(modes) for opening a file:
Syntax -
f = open(“demofile.txt”)
27
F = open(“D:\\myfiles\welcome.txt”, “r”)
print(f.read())
Ex -
F = open(“demofile.txt”, “r”)
print(f.read(5))
Ex - open(“demofile.txt”, “r”)
print(f.readline())
print(f.readline())
Ex -
F = open(“demofile2.txt”, “a”)
F.write(“Now the file has more content!”)
f.close()
Ex -
F = open(“demofile3.txt”, “w”)
F.write(“Whoops!, I have deleted the content!”)
f.close()
28
Delete a File or Folder
To delete a file, you must import the OS module, and run its
os.remove() function.
Ex -
Q - avoid getting an error while deleting.
Import os
If os.path.exists(“demo file.txt”):
os.remove(“demofile.txt”)
Else:
print(“The file does not exists”)
Ex -
import os
Os.rmdir(“myfolder”)
29
Python functions
A function is a block of code which only runs when it is
called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a function
Ex -
Def my_function():
Print(“Hello from a function”)
Calling a function
Ex -
Def my_function():
print(“Hello”)
my_function()
Arguments
30
Ex -
Def my_function(fname):
print(fname + “refsnes”)
My_function(“Emil”)
my_function(“Tobias”)
Parameters or Arguments?
The term parameter and argument cam be used for the same
thing: Information are passed into function.
Note -
From function’s perspective:
Number of arguments
Ex -
Q - This function expects 2 arguments, and gets 2 arguments:
my_function(“Emil”, “Refsnes”)
31
If you do not know how many arguments that will be passed into
your function, add a * before the parameter name in the
function definition.
Ex -
Q - If the number of arguments is unknown, add a * before the
parameter name:
Def my_function(*kids):
print(“The youngest child is ” + kids[2])
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Ex -
32
Def my_function(**kid):
print(“His lsat name is ” +kid[“lname”])
Ex -
my_function(“Sweden”)
my_function()
my_function(“Brazil”)
33
Ex -
Def my_function(food):
For x in food:
print(x)
my_function(fruits)
Return Values
Def my_function(x):
Return 5 * x
print(my_function(3))
34