Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Programming

The document provides an overview of Python programming, highlighting its rapid growth, versatility, and accessibility for learners from various backgrounds. It covers Python's history, career opportunities, installation procedures, and fundamental programming concepts such as variables, data types, and string manipulation. Additionally, it discusses Python tools and modules that enhance coding efficiency and debugging.

Uploaded by

t6rabek.raufov
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Programming

The document provides an overview of Python programming, highlighting its rapid growth, versatility, and accessibility for learners from various backgrounds. It covers Python's history, career opportunities, installation procedures, and fundamental programming concepts such as variables, data types, and string manipulation. Additionally, it discusses Python tools and modules that enhance coding efficiency and debugging.

Uploaded by

t6rabek.raufov
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

Python Programming

Dr Mohammad Gouse Galety


Dean, Computer Science Program,
Samarkand International University of Technology

1
Introduction
• It’s a fastest growing
language,
• in terms number of
developers are using it,
• number of libraries we have,
• number of organizations are
using,
• Anybody can learn python
even if you are from non-
technical.
• number of areas are we are
implementing like machine
learning, GUI, SW
development, web
development.
• It’s also called as general
purpose language.
2
History What is python?
• Python was conceived in the • Python is programming
late 1980s by Guido van
Rossum at Centrum Wiskunde language, and it’s an
& Informatica (CWI) in the interpreted, object
Netherlands as a successor to oriented, and high level
the ABC language. programming language.
• Its implementation began in (It support procedure
December 1989. oriented programming
• Java came in 1995. also)
• Python has multiple versions
like Python 1.0 in January
1994, Python 2.0 in October
2000, and Python 3.0 in
December 2008.

3
• Python Career Opportunities • Types of Python Jobs

• Future of Python
• Python is one of the new technologies.
The future is bright for Python with:

4
• Top Organizations Using Python • Python Tools
• Python Dis Module
• With its extreme popularity and • To convert bytecode into a more human-readable
powerfulness, Python is preferred by format.
unicorns too: • Python Tabnanny Module
• Python tabnanny checks code for ambiguous
indentation.
• It tells us about any weird combinations of tabs and
spaces in the code.
• Python Profile Module
• We may sometimes like to know which parts of our
code take the longest. we try to find bottlenecks in
our code.
• Python PDB Module
• Why Must You Learn Python • Pdb is the standard Python debugger.
• It helps us debug our code line by line

5
• Installation & setup • Sublime as python editor – some of you
• To install python, go to the google , type do not like heavy software like pycharm,
“download python for windows”. so, you need to lightweight software like
• Choose this link :” sublime to write python codes, for that,
https://www.python.org/downloads/” you need to download sublime, its free
• After downloading python and installing, to software.
ensure that, whether it’s working or not,
• go to search box of windows and type python • Open sublime, go to the “tools” menu and
and choose python command line and type choose “build system” and select
simple calculation 2+3 and press enter, “Python”.
obviously you will get answer 5, so your
python is working successfully. • Type the program and save the program
• Writing program in command line interface is like “test.py”
not good, so we need to install Pycharm IDE, • .py is the extension of the python
so try to download and install Pycharm IDE.
programs and press “ctrl+b” to execute
• To work with simple programs even you can
open python IDLE from search and you can do the program.
calculations like calculator.
• To install pycharm, go to the google , type
“download pycharm”.
• Choose this link :”
https://www.jetbrains.com/pycharm/downloa
d/#section=windows”
6
• Other ways to install Ex:
1. a=3
1. Download python from python.org & install. 2. A=4
2. Download pycharm ide from jetbrains.com & install. 3. print a
(Or) 4. print A
1. Download anaconda for packages inbuilt which support python
like matplotlib, visualization, numpy, etc. from anaconda.com. • Many Values to Multiple Variables
• Python allows you to assign values to multiple variables in one line:
2. After installing anaconda, go to search box of windows and Ex:
type anaconda prompt. 1. x, y, z = "Orange", "Banana", "Cherry"
3. download jupyter notebook to do coding. 2. print(x)
3. print(y)
4. In prompt type jupyter notebook and press enter button then 4. print(z)
it will open jupyter notebook in browser.
5. To open a new notebook click on New dropdown box at right • One Value to Multiple Variables
corner and select python3. • And you can assign the same value to multiple variables in one line:
• Variables • Ex:
• Variables need not be declared first in python. 1. x = y = z = "Orange"
2. print(x)
• They can be used directly.
3. print(y)
• Variables in python are case-sensitive as most of the other
4. print(z)
programming languages.
• A variable can have a short name (like x and y) or a more • Unpack a Collection
descriptive name (age, carname, total_volume). • If you have a collection of values in a list, tuple etc. Python allows you
• Rules for Python variables: extract the values into variables.
• A variable name must start with a letter or the underscore • Ex:
character 1. fruits = ["apple", "banana", "cherry"]
• A variable name cannot start with a number 2. x, y, z = fruits
3. print(x)
• A variable name can only contain alpha-numeric characters
4. print(y)
and underscores (A-z, 0-9, and _ )
5. print(z)
• Variable names are case-sensitive (age, Age and AGE are
three different variables)

7
• Output • Python has the following data types built-in by default, in these
• The print statement is often used to output variables. categories:
• To combine both text and a variable, Python uses the + character: • Text Type: str
• Ex: • Numeric Types: int, float, complex
1. x = “Catholic University in Erbil"
2. print("Python is " + x) • Sequence Types: list, tuple, range
• Mapping Type: dict
1. x = "Python is " • Set Types: set, frozenset
2. y = "awesome"
3. z= x+y • Boolean Type: bool
4. print(z) • BinaryTypes:bytes,bytearray, memoryview

• Expressions
• Arithmetic operations in python can be performed by using arithmetic • Getting the Data Type
operators and some of the in-built functions. • You can get the data type of any object by using the type() function:
1. a=2 Ex:
2. b=3 1. x = 5
3. c=a+b 2. print(type(x))
4. print c
5. d=a*b Output:<class 'int’>
6. print d
• x = "Hello World" str
• Datatypes • x = 20.5 float
• Datatypes are defining set of data with predefined values. • x = 1j complex
• Types of Datatypes • x = ["apple", "banana", "cherry"] list
1. System Defined Datatypes • x = ("apple", "banana", "cherry") tuple
2. User Defined Datatypes • x = range(6) range
• System Defined Datatypes (Primitive) • x = {"name" : "John", "age" : 36} dict
• These datatypes are defined by a system, also called as primitive datatypes. • x = {"apple", "banana", "cherry"} set
• Different languages can have different size of primitive datatypes. • x = frozenset({"apple", "banana", "cherry"}) frozenset
• Number of bits allocated for each primitive datatype depends on OS, compiler, • x = True bool
and programming language, like 2 bytes for int type. • x = b"Hello" bytes
• Ex: int, float, char, double, bool, etc., • x = bytearray(5) bytearray
• User Defined Datatypes (Non-Primitive) • x = memoryview(bytes(5)) memoryview
• These datatypes are defined by a user, also called non-primitive datatypes.
• Helps in providing more flexibility and comfort.
• Ex: Student s = new Student();

8
• Setting the Specific Data Type • Numbers
• There are three numeric types in Python:
• If you want to specify the data type, you can • int
use the following constructor functions: • float
1. x = str("Hello World") • complex
• Variables of numeric types are created when you assign a value to them:
2. print(x) 1. x = 1 # int
3. print(type(x)) 2. y = 2.8 # float

• Comments
3. z = 1j # complex
• To verify the type of any object in Python, use the type() function:
• Comments can be used to explain Python 1.
2.
print(type(x))
print(type(y))
code. 3. print(type(z))

• Comments can be used to make the code Type Conversion
• You can convert from one type to another with the int(), float(), and complex()
more readable. methods:
1. x = 1 # int
• Comments can be used to prevent 2. y = 2.8 # float
execution when testing code. 3. z = 1j # complex
4. #convert from int to float:
• Creating a Comment 5. a = float(x)

• Comments starts with a #, and Python will 6.


7.
#convert from float to int:
b = int(y)
ignore them: 8. #convert from int to complex:

• Ex: 9.
10.
c = complex(x)
print(a)
• #This is a comment. 11. print(b)
12. print(c)
• print("Hello, World!") 13. print(type(a))
14. print(type(b))
15. print(type(c))

9
• Random Number • Multiline Strings
• Python does not have a random() function to • You can assign a multiline string to a variable by
make a random number, but Python has a built- using three quotes (“”” “””/’’’ ‘’’):
in module called random that can be used to 1. a = """The Catholic University in Erbil (CUE) is a
make random numbers. non-profit institution of higher education and
• Ex: Import the random module, and display a scientific research providing recognized degrees
in the arts and sciences."""
random number between 1 and 9: 2. print(a)
1. import random
2. print(random.randrange(1, 10))
• Strings • Strings are Arrays
• Like many other popular programming
• Single or double quotation marks surround languages, strings in Python are arrays of bytes
strings in Python. representing unicode characters.
1. ‘Hello' is the same as "hello". • However, Python does not have a character
• You can display a string literal with the print() data type, a single character is simply a string
function: with a length of 1.
1. print("Hello") • Square brackets can be used to access
2. print('Hello’) elements of the string.
• Assign String to a Variable • Get the character at position 1 (remember that
• Assigning a string to a variable is done with the the first character has the position 0):
variable name followed by an equal sign and 1. a = "Hello, World!"
the string: 2. print(a[1])
1. a = "Hello"
2. print(a)

10
• Looping through a String • Check if NOT
• Since strings are arrays, we can loop through • To check if a certain phrase or character is NOT
the characters in a string, with a for loop. present in a string, we can use the keyword not
• Loop through the letters in the word “Galety": in.
1. for x in "banana": • Check if "expensive" is NOT present in the
2. print(x) following text:
1. txt = "The best things in life are free!"
• String Length 2. print("expensive" not in txt)
• To get the length of a string, use the len()
function. • Use it in an if statement - print only if
1. a = “Galety Mohammad Gouse" "expensive" is NOT present:
2. print(len(a)) 1. txt = "The best things in life are free!"
• Check String 2. if "expensive" not in txt:
• To check if a certain phrase or character is 3. print("No, 'expensive' is NOT present.")
present in a string, we can use the keyword in. • Slicing
1. txt = " Galety Mohammad Gouse" • You can return a range of characters by using
2. print(“Gouse" in txt) the slice syntax.
• Specify the start index and the end index,
• Use it in an if statement - Print only if “Gouse" separated by a colon, to return a part of the
is present:. string.
1. txt = " Galety Mohammad Gouse" • Get the characters from position 2 to position 5
2. if “Gouse" in txt: (not included):
3. print("Yes, ‘Gouse' is present.")
1. b = "Hello, World!"
2. print(b[2:5])
11
• Slice From the Start • Modify Strings
• By leaving out the start index, the range • Upper Case
will start at the first character: • The upper() method returns the string in
• Get the characters from the start to upper case:
position 5 (not included): 1. a = "Hello, World!"
1. b = "Hello, World!" 2. print(a.upper())
2. print(b[:5]) • Lower Case
• The lower() method returns the string in
• Slice To the End lower case:
• By leaving out the end index, the range 1. a = "Hello, World!"
will go to the end: 2. print(a.lower())
• Get the characters from position 2, and all • Remove Whitespace
the way to the end: • Whitespace is the space before and/or after
1. b = "Hello, World!" the actual text, and very often you want to
2. print(b[2:]) remove this space.
• The strip() method removes any whitespace
• Negative Indexing from the beginning or the end:
• Use negative indexes to start the slice 1. a = " Hello, World! "
from the end of the string: 2. print(a.strip()) # returns "Hello, World!“
• Get the characters: From: "o" in "World!" • Replace String
(position -5) • The replace() method replaces a string with
another string:
1. b = "Hello, World!"
1. a = "Hello, World!"
2. print(b[-5:-2]) 2. print(a.replace("H", "J"))
12
• Split String • String Format
• The split() method splits the string into • As we learned in the Python Variables
substrings if it finds instances of the chapter, we cannot combine strings and
separator. numbers like this:
1. a = "Hello, World!" 1. age = 36
2. b = a.split(",") 2. txt = "My name is John, I am " + age
3. print(b) 3. print(txt)
4. Output: ['Hello', ' World!’] • Output:
• String Concatenation • Traceback (most recent call last):
• File "demo_string_format_error.py", line 2,
• To concatenate, or combine, two strings in <module>
you can use the + operator. • txt = "My name is John, I am " + age
• Ex: Merge variable a with variable b into • TypeError: must be str, not int
variable c.
1. a = "Hello" • But we can combine strings and numbers
2. b = "World" by using the format() method!
3. c=a+b • The format() method takes the passed
4. print(c) arguments, formats them, and places
• Ex:To add a space between them, add a " “ them in the string where the placeholders
{} are:
1. a = "Hello" 1. age = 36
2. b = "World" 2. txt = "My name is John, and I am {}"
3. c=a+""+b 3. print(txt.format(age))
4. print(c) • Output: My name is John, and I am 36
13
1. quantity = 3 • Escape Character
2. itemno = 567 • To insert characters that are illegal in a string,
use an escape character.
3. price = 49.95
• An escape character is a backslash \ followed
4. myorder = "I want {} pieces of item {} for {} by the character you want to insert.
dollars." • An example of an illegal character is a double
5. print(myorder.format(quantity, itemno, quote “ inside a string that is surrounded by
double quotes:
price))
• You will get an error if you use double quotes
• Output: I want 3 pieces of item 567 for inside a string that is surrounded by double
49.95 dollars. quotes.
• You can use index numbers {0} to be sure the 1. txt = "We are the so-called "Vikings" from the
north.“
arguments are placed in the correct • Output: File"demo_string_escape_error.py", line
placeholders: 1 txt = "We are the so-called "Vikings" from the
north."
1. quantity = 3 • SyntaxError: invalid syntax
2. itemno = 567 • To fix this problem, use the escape character
3. price = 49.95 \":
1. txt = "We are the so-called \"Vikings\" from the
4. myorder = "I want to pay {2} dollars for {0} north."
pieces of item {1}." 2. print(txt)
5. print(myorder.format(quantity, itemno, • Output: We are the so-called "Vikings" from the
north.
price))
• Output: I want to pay 49.95 dollars for 3
pieces of item 567 14
Method Description
• Escape Characters capitalize() Converts the first character to upper case
Code Result
• Other escape characters used in Python: casefold() Converts string into lower case
\' Single Quote center() Returns a centered string
1. txt = 'It\'s alright.' count() Returns the number of times a specified value occurs in a string
2. print(txt) \\ Backslash
encode() Returns an encoded version of the string
\n New Line endswith() Returns true if the string ends with the specified value
3. txt = "This will insert one \\ (backslash)." \r Carriage Return expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
4. print(txt) \t Tab
format() Formats specified values in a string
\b Backspace format_map() Formats specified values in a string
1. txt = "Hello\nWorld!" index() Searches the string for a specified value and returns the position of where it was found
\f Form Feed
2. print(txt) isalnum() Returns True if all characters in the string are alphanumeric
\ooo Octal value isalpha() Returns True if all characters in the string are in the alphabet
1. txt = "Hello\rWorld!" \xhh Hex value isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
2. print(txt) isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
1. txt = "Hello\tWorld!" islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
2. print(txt) isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
1. #This example erases one character (backspace): istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
2. txt = "Hello \bWorld!" join() Joins the elements of an iterable to the end of the string
3. print(txt) ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
1. #A backslash followed by three integers will result in a octal value:
maketrans() Returns a translation table to be used in translations
2. txt = "\110\145\154\154\157" partition() Returns a tuple where the string is parted into three parts
3. print(txt) replace() Returns a string where a specified value is replaced with a specified value

rfind() Searches the string for a specified value and returns the last position of where it was found

1. #A backslash followed by an 'x' and a hex number represents a hex value: rindex() Searches the string for a specified value and returns the last position of where it was found
2. txt = "\x48\x65\x6c\x6c\x6f" rjust() Returns a right justified version of the string
3. print(txt) rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
• String Methods rstrip() Returns a right trim version of the string
• Python has a set of built-in methods that you can use on strings. split() Splits the string at the specified separator, and returns a list
• Note: All string methods returns new values. They do not change the original string. splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
15
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
1. txt = "hello, and welcome to my world." • Booleans
2. x = txt.capitalize() • Booleans represent one of two values:
3. print (x) True or False.
• In programming you often need to know if
1. txt = "Hello, And Welcome To My World!" an expression is True or False.
2. x = txt.casefold()
• Ex:
3. print(x)
• print(10 > 9)
• print(10 == 9)
1. #Print the word "banana", taking
up the space of 20 characters, • print(10 < 9)
with "banana" in the middle • When you run a condition in an if
2. txt = "banana" statement, Python returns True or False.
3. ​x = txt.center(20) • Ex:
4. ​print(x) • a = 200
• b = 33
1. Return the number of times the value • if b > a:
"apple" appears in the string. • print("b is greater than a")
2. txt = "I love apples, apple are my favorite • else:
fruit"
• print("b is not greater than a")
3. x = txt.count("apple")
4. print(x)
5.
16
• Functions can Return a Boolean • Python also has many built-in
• You can create functions that returns a functions that return a boolean
Boolean Value: value, like the isinstance() function,
• Ex: which can be used to determine if an
1. def myFunction() : object is of a certain data type:
2. return True
3. print(myFunction()) • Ex: Check if an object is an integer or
• You can execute code based on the not.
Boolean answer of a function. 1. x = 200
• Ex: Print "YES!" if the function returns 2. print(isinstance(x, int))
True, otherwise print "NO!“.
1. def myFunction() :
2. return True
3. if myFunction():
4. print("YES!")
5. else:
6. print("NO!")
17
• Operators • Assignment Operators
• Operators are used to perform • Assignment operators are used to
operations on variables and values. assign values to variables.
• Python divides the operators in the Operator Example Same As
following groups: = x=5 x=5

1. Arithmetic operators += x += 3 x=x+3

2. Assignment operators -= x -= 3 x=x-3


*= x *= 3 x=x*3
3. Comparison operators
/= x /= 3 x=x/3
4. Logical operators
%= x %= 3 x=x%3
5. Identity operators
//= x //= 3 x = x // 3
6. Membership operators
**= x **= 3 x = x ** 3
7. Bitwise operators &= x &= 3 x=x&3

• Arithmetic Operators |= x |= 3 x=x|3


^= x ^= 3 x=x^3
• Arithmetic operators are used with
>>= x >>= 3 x = x >> 3
numeric values to perform common <<= x <<= 3 x = x << 3
mathematical operations.

18
• Comparison Operators • Identity Operators
• Comparison operators are used to compare • Identity operators are used to compare the
two values. objects, not if they are equal, but if they are
Operator Name Example actually the same object, with the same
== Equal x == y
memory location.
Operator Description Example
!= Not equal x != y
is Returns True if both variables are the same object x is y
> Greater than x>y
is not Returns True if both variables are not the same object x is not y
< Less than x<y

>= Greater than or equal to x >= y


• Ex:
<= Less than or equal to x <= y 1. x = ["apple", "banana"]
2. y = ["apple", "banana"]
3. z=x
• Logical Operators 4. print(x is z)
• Logical operators are used to combine 5. # returns True because z is the same object
conditional statements. as x
6. print(x is y)
Operator Description Example
7. # returns False because x is not the same
and Returns True if both statements are true x < 5 and x < 10 object as y, even if they have the same
content
or Returns True if one of the statements is true x < 5 or x < 4
8. print(x == y)
not Reverse the result, returns False if the result not(x < 5 and x < 10) 9. # to demonstrate the difference betweeen
is true "is" and "==": this comparison returns True
because x is equal to y
19
1. x = ["apple", "banana"] • Membership Operators
2. y = ["apple", "banana"] • Membership operators are used to test
3. z=x if a sequence is presented in an object.
4. print(x is not z) Operator Description Example

5. # returns False because z is the same in Returns True if a sequence with the specified value is present x in y
in the object
object as x not in Returns True if a sequence with the specified value is not x not in y
present in the object
6. print(x is not y)
7. # returns True because x is not the • Ex:
same object as y, even if they have 1. x = ["apple", "banana"]
the same content 2. print("banana" in x)
8. print(x != y) 3. # returns True because a sequence with
9. # to demonstrate the difference the value "banana" is in the list
between "is not" and "!=": this • Ex:
comparison returns False because x is 1. x = ["apple", "banana"]
equal to y 2. print("pineapple" not in x)
3. # returns True because a sequence with
the value "pineapple" is not in the list
20
• Bitwise Operators • List Items
• Bitwise operators are used to compare (binary) numbers.
Operator Name Description
• List items are ordered, changeable, and allow
& AND Sets each bit to 1 if both bits are 1
duplicate values.
| OR Sets each bit to 1 if one of two bits is 1 • List items are indexed, the first item has index
^ XOR Sets each bit to 1 if only one of two bits is 1 [0], the second item has index [1] etc.
• Ordered
~ NOT Inverts all the bits
<< Zero fill left Shift left by pushing zeros in from the right and let the leftmost bits fall off

>>
shift
Signed right Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost
• When we say that lists are ordered, it means
shift bits fall off that the items have a defined order, and that
order will not change.
• Non-Primitive Data structures
• In non-primitive data structures, we can store multiple values,
• If you add new items to a list, the new items
but in variable (primitive) you can store only one value. will be placed at the end of the list.
• Lists • Changeable (mutable)
• Lists are used to store multiple items in a single variable. • The list is changeable, meaning that we can
• Lists are one of 4 built-in data types in Python used to store change, add, and remove items in a list after it
collections of data, the other 3 are Tuple, Set, and Dictionary,
all with different qualities and usage. has been created.
• Lists are created using square brackets [].
• Lists are mutable. So, you can change the values of the created
• Allow Duplicates
list. • Since lists are indexed, lists can have items with
• Ex: the same value.
• x = ["apple", "banana", "cherry"] • Ex:
• print(x) • x = ["apple", "banana", "cherry", "apple",
• Output: ['apple', 'banana', 'cherry’] "cherry"]
• Ex: • print(thislist)
• Y=[1,”a”,True,2,”b”,False]
• Ouput: ['apple', 'banana', 'cherry', 'apple', 'cherry']
21
• List Length • Access Items
• To determine how many items a list has, use the len() • List items are indexed, and you can access them by
function. referring to the index number.
• Ex: • Ex:
• x = ["apple", "banana", "cherry"] • x = ["apple", "banana", "cherry"]
• print(len(x)) • print(x[1])
• Output: 3
• Negative Indexing
• List Items - Data Types • Negative indexing means start from the end.
• List items can be of any data type. • -1 refers to the last item, -2 refers to the second last
• Ex: item etc.
• x = ["apple", "banana", "cherry"] • Ex:
• y = [1, 5, 7, 9, 3] • x = ["apple", "banana", "cherry"]
• z = [True, False, False] • print(x[-1])
• print(x)
• print(y)
• print(z)
• Range of Indexes
Output: • You can specify a range of indexes by specifying where
• ['apple', 'banana', 'cherry']
to start and where to end the range.
• [1, 5, 7, 9, 3] • When specifying a range, the return value will be a new
• [True, False, False] list with the specified items.
• Ex:
• A list can contain different data types. A list with strings, • x = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
integers and Boolean values. "mango"]
• print(x[2:5])
• Ex:
• #This will return the items from position 2 to 5.
• x = ["abc", 34, True, 40, "male"]
• #Remember that the first item is position 0,
• print(x)
• #and note that the item in position 5 is NOT included
22
• By leaving out the start value, the range • Range of Negative Indexes
will start at the first item. • Specify negative indexes if you want to start
• Ex: the search from the end of the list.
1. x = ["apple", "banana", "cherry", "orange", • Ex:
"kiwi", "melon", "mango"] 1. x = ["apple", "banana", "cherry", "orange",
2. print(x[:4]) "kiwi", "melon", "mango"]
3. #This will return the items from index 0 to 2. print(x[-4:-1])
index 4. 3. #Negative indexing means starting from
4. #Remember that index 0 is the first item, the end of the list.
and index 4 is the fifth item 4. #This example returns the items from index
5. #Remember that the item in index 4 is NOT -4 (included) to index -1 (excluded)
included 5. #Remember that the last item has the
index -1.
• By leaving out the end value, the range
will go on to the end of the list. • Check if Item Exists
• Ex: • To determine if a specified item is present
1. x = ["apple", "banana", "cherry", "orange", in a list use the in keyword.
"kiwi", "melon", "mango"] • Ex:
2. print(x[2:]) 1. x = ["apple", "banana", "cherry"]
3. #This will return the items from index 2 to 2. if "apple" in x:
the end. 3. print("Yes, 'apple' is in the fruits list")
4. #Remember that index 0 is the first item,
and index 2 is the third

23
• Change Item Value • Insert Items
• To change the value of a specific item, refer to the index • To insert a new list item, without replacing any of the
number. existing values, we can use the insert() method.
• Ex: • The insert() method inserts an item at the specified
1. x = ["apple", "banana", "cherry"] index.
2. x[1] = "blackcurrant" • Ex:
3. print(x) 1. x= ["apple", "banana", "cherry"]
2. x.insert(2, "watermelon")
• Change a Range of Item Values 3. print(x)
• To change the value of items within a specific range, • Output: ['apple', 'banana', 'watermelon', 'cherry’]
define a list with the new values, and refer to the range
of index numbers where you want to insert the new • Append Items
values. • To add an item to the end of the list, use the append()
• Ex: method.
1. x = ["apple", "banana", "cherry", "orange", "kiwi",
"mango"]
• Ex:
2. x[1:3] = ["blackcurrant", "watermelon"] 1. x = ["apple", "banana", "cherry"]
3. print(x) 2. x.append("orange")
4. Output: ["apple", "blackcurrant", "watermelon“, "orange", 3. print(x)
"kiwi", "mango"]
• Extend List
• If you insert more items than you replace, the new • To append elements from another list to the current
items will be inserted where you specified, and the list, use the extend() method.
remaining items will move accordingly.
• Ex: • Ex: Add the elements of y to x.
1. x = ["apple", "banana", "cherry"] 1. x = ["apple", "banana", "cherry"]
2. x[1:2] = ["blackcurrant", "watermelon"] 2. y = ["mango", "pineapple", "papaya"]
3. print(x) 3. x.extend(y)
4. Output: ["apple", "blackcurrant", "watermelon", "cherry"] 4. print(x)

24
• Add Any Iterable • The del keyword also removes the specified index.
• The extend() method does not have to append lists, • Ex:
you can add any iterable object (tuples, sets, 1. x = ["apple", "banana", "cherry"]
dictionaries etc.). 2. del x[0]
• Ex: Add elements of a tuple to a list. 3. print(x)
1. x = ["apple", "banana", "cherry"]
2. y = ("kiwi", "orange") • The del keyword can also delete the list completely.
3. x.extend(y) • Ex:
4. print(x) 1. x = ["apple", "banana", "cherry"]
2. del x
• Remove Specified Item
• The remove() method removes the specified item. • Clear the List
• Ex: Remove banana • The clear() method empties the list.
1. x = ["apple", "banana", "cherry"] • The list still remains, but it has no content.
2. x.remove("banana") • Ex:
3. print(x) 1. x= ["apple", "banana", "cherry"]
2. x.clear()
• Remove Specified Index 3. print(x)
• The pop() method removes the specified index.
• Ex: Remove the second item • Loop Through a List
1. x= ["apple", "banana", "cherry"] • You can loop through the list items by using a for loop.
2. x.pop(1) • Ex: Print all items in the list, one by one.
3. print(x) 1. y = ["apple", "banana", "cherry"]
• If you do not specify the index, the pop() method 2. for x in y:
removes the last item. 3. print(x)
• Ex:
1. x = ["apple", "banana", "cherry"]
2. x.pop()
3. print(x)
25
• Loop Through the Index Numbers • Looping Using List Comprehension
• You can also loop through the list items by • List Comprehension offers the shortest syntax for
referring to their index number. looping through lists.
• Use the range() and len() functions to create a • A shorthand for loop that will print all items in a
suitable iterable. list.
• Ex: • Ex:
• x = ["apple", "banana", "cherry"] • y= ["apple", "banana", "cherry"]
• for i in range(len(x)): • [print(x) for x in y]
• print(x[i])
• List Comprehension
• The iterable created in the example above is [0, 1,
2]. • List comprehension offers a shorter syntax when
you want to create a new list based on the values
• Using a While Loop of an existing list.
• You can loop through the list items by using a • Ex:
while loop. • fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
• Use the len() function to determine the length of • newlist = []
the list, then start at 0 and loop your way through • for x in fruits:
the list items by refering to their indexes. • if "a" in x:
• Remember to increase the index by 1 after each • newlist.append(x)
iteration. • print(newlist)
• Ex: • Output: ['apple', 'banana', 'mango’]
• x = ["apple", "banana", "cherry"]
• i=0
• while i < len(x):
• print(x[i])
• i=i+1
26
• Iterable • You can set the outcome to whatever you
• The iterable can be any iterable object, like a like.
list, tuple, set etc. • Ex:
• You can use the range() function to create an • fruits = ["apple", "banana", "cherry", "kiwi",
iterable. "mango"]
• Ex: • newlist = ['hello' for x in fruits]
• y = [x for x in range(10)] • print(newlist)
• print(y) • Output: ['hello', 'hello', 'hello', 'hello', 'hello’]
• Ex: Accept only numbers lower than 5 • The expression can also contain conditions,
• y = [x for x in range(10) if x < 5] not like a filter, but as a way to manipulate
• print(y) the outcome.
• Expression • Ex: Return "orange" instead of "banana“.
• The expression is the current item in the • fruits = ["apple", "banana", "cherry", "kiwi",
iteration, but it is also the outcome, which you "mango"]
can manipulate before it ends up like a list item • newlist = [x if x != "banana" else "orange" for x in
in the new list. fruits]
• print(newlist)
• Ex: • Output: ['apple', 'orange', 'cherry', 'kiwi', 'mango’]
• fruits = ["apple", "banana", "cherry", "kiwi",
"mango"] • The expression in the example above says:
• newlist = [x.upper() for x in fruits] • "Return the item if it is not banana, if it is banana
return orange".
• print(newlist)
• Output:['APPLE', 'BANANA', 'CHERRY', 'KIWI',
'MANGO']

27
• Sort Lists • Case Insensitive Sort
• Sort List Alphanumerically-List objects have a • By default, the sort() method is case sensitive,
sort() method that will sort the list resulting in all capital letters being sorted before
alphanumerically, ascending, by default. lower case letters.
• Ex: • Ex:
• x = ["orange", "mango", "kiwi", "pineapple", • x = ["banana", "Orange", "Kiwi", "cherry"]
"banana"] • x.sort()
• x.sort() • print(x)
• print(x) • Output: ['Kiwi', 'Orange', 'banana', 'cherry’]
• Sort the list numerically
• Ex: • So, if you want a case-insensitive sort function,
• x = [100, 50, 65, 82, 23] use str.lower as a key function.
• x.sort() • Ex:
• print(x) • x = ["banana", "Orange", "Kiwi", "cherry"]
• Sort Descending-To sort descending, use the • x.sort(key = str.lower)
keyword argument reverse = True . • print(x)
• Ex: • Output: ['banana', 'cherry', 'Kiwi', 'Orange’]
• x = ["orange", "mango", "kiwi", "pineapple", • Reverse Order
"banana"]
• x.sort(reverse = True) • What if you want to reverse the order of a list,
• print(x) regardless of the alphabet?
• Ex: • The reverse() method reverses the current sorting
• x = [100, 50, 65, 82, 23] order of the elements.
• x.sort(reverse = True) • Ex:
• print(x) • x = ["banana", "Orange", "Kiwi", "cherry"]
• x.reverse()
• print(x)
28
• Copy a List • Join Two Lists
• You cannot copy a list simply by typing • There are several ways to join, or
list2 = list1, because: list2 will only be a concatenate, two or more lists in
reference to list1, and changes made in Python.
list1 will automatically also be made in • One of the easiest ways are by using
list2. the + operator.
• There are ways to make a copy, one • Ex:
way is to use the built-in List method • x = ["a", "b", "c"]
copy(). • y = [1, 2, 3]
• Ex: • z=x+y
• x = ["apple", "banana", "cherry"] • print(z)
• y = x.copy() • Another way to join two lists is by
• print(y) appending all the items from list2 into
• Another way to make a copy is to use list1, one by one.
the built-in method list(). • Ex:
• x = ["apple", "banana", "cherry"] • a = ["a", "b" , "c"]
• y = list(x) • b = [1, 2, 3]
• print(y) • for x in b:
• a.append(x)
• print(a) 29
• Or Use the extend() method to add • Tuple Items
list2 at the end of list1. • Tuple items are ordered, unchangeable,
1. list1 = ["a", "b" , "c"] and allow duplicate values.
2. list2 = [1, 2, 3] • Tuple items are indexed, the first item has
3. list1.extend(list2) index [0], the second item has index [1]
etc.
4. print(list1)
• Ordered
• When we say that tuples are ordered, it
• Tuples means that the items have a defined
• Tuples are used to store multiple items in order, and that order will not change.
a single variable.
• Tuple is one of 4 built-in data types in • Unchangeable
Python used to store collections of data, • Tuples are unchangeable, meaning that
the other 3 are List, Set, and Dictionary, all we cannot change, add or remove items
with different qualities and usage. after the tuple has been created.
• A tuple is a collection which is ordered and • Allow Duplicates
unchangeable. • Since tuples are indexed, they can have
• Tuples are written with round brackets (). items with the same value.
• Ex: • Ex:
1. x = ("apple", "banana", "cherry") 1. x = ("apple", "banana", "cherry", "apple",
2. print(x) "cherry")
• Output: (‘apple’, ‘banana’, ‘cherry’) 2. print(x)

30
• Tuple Length • The tuple() Constructor
• To determine how many items a tuple has, use the len() function. • Using the tuple() method to make a tuple.
• Ex: • Ex:
• x = ("apple", "banana", "cherry")
1. x=("apple", "banana", "cherry")
• print(len(x))
2. thistuple = tuple(x)
• Create Tuple With One Item
3. print(thistuple)
• To create a tuple with only one item, you have to add a comma (,)
after the item, otherwise Python will not recognize it as a tuple. • Access Tuple Items
• Ex: • You can access tuple items by referring to the index number, inside
1. x = ("apple",) square brackets.
2. print(type(x))
• Ex:
• #NOT a tuple 1. thistuple = ("apple", "banana", "cherry")
1. x = ("apple") 2. print(thistuple[1])
2. print(type(x))
• Negative Indexing
• Tuple Items - Data Types • Negative indexing means start from the end.
• Tuple items can be of any data type.
• -1 refers to the last item, -2 refers to the second last item etc.
• Ex:
1. tuple1 = ("apple", "banana", "cherry") • Ex:
2. tuple2 = (1, 5, 7, 9, 3) 1. thistuple = ("apple", "banana", "cherry")
3. tuple3 = (True, False, False) 2. print(thistuple[-1])
4. print(tuple1)
5. print(tuple2) • Range of Indexes
6. print(tuple3) • You can specify a range of indexes by specifying where to start and where
to end the range.
• A tuple can contain different data types.
• Ex: • When specifying a range, the return value will be a new tuple with the
specified items.
1. tuple1 = ("abc", 34, True, 40, "male")
2. print(tuple1) • Ex:
1. thistuple = ("apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango")
2. print(thistuple[2:5]) 31
• Check if Item Exists • Add Items
• To determine if a specified item is present in a • Since tuples are immutable, they do not have a
tuple use the in keyword. build-in append() method, but there are other
• Ex: ways to add items to a tuple.
1. x = ("apple", "banana", "cherry") • Convert into a list: you can convert it into a list,
2. if "apple" in x: add your item(s), and convert it back into a
3. print("Yes, 'apple' is in the fruits tuple") tuple.
• Ex:
• Update Tuples 1. thistuple = ("apple", "banana", "cherry")
• Tuples are unchangeable, meaning that you 2. y = list(thistuple)
cannot change, add, or remove items once the 3. y.append("orange")
tuple is created.(But there are some 4. thistuple = tuple(y)
workarounds.)
• Add tuple to a tuple: You are allowed to add
• Change Tuple Values tuples to tuples, so if you want to add one item,
• Once a tuple is created, you cannot change its (or many), create a new tuple with the item(s),
values. Tuples are unchangeable, or immutable as and add it to the existing tuple:
it also is called.
• But there is a workaround. You can convert the • Ex:
tuple into a list, change the list, and convert the list 1. thistuple = ("apple", "banana", "cherry")
back into a tuple. 2. y = ("orange",)
• Ex: 3. thistuple += y
1. x = ("apple", "banana", "cherry") 4. print(thistuple)
2. y = list(x)
3. y[1] = "kiwi"
4. x = tuple(y)
5. print(x)

32
• Remove Items • Using Asterisk*
• Tuples are unchangeable, so you cannot remove items • If the number of variables is less than the number of
from it, but you can use the same workaround as we values, you can add an * to the variable name and the
used for changing and adding tuple items. values will be assigned to the variable as a list.
• Convert the tuple into a list, remove "apple", and • Ex:
convert it back into a tuple. 1. fruits = ("apple", "banana", "cherry", "strawberry",
• Ex: "raspberry")
1. thistuple = ("apple", "banana", "cherry") 2. (green, yellow, *red) = fruits
2. y = list(thistuple) 3. print(green)
3. y.remove("apple") 4. print(yellow)
4. thistuple = tuple(y) 5. print(red)
5. print(thistuple) • If the asterisk is added to another variable name than
the last, Python will assign values to the variable until
• Unpacking a Tuple the number of values left matches the number of
• When we create a tuple, we normally assign values to it. variables left.
This is called "packing" a tuple. • Ex:
• Ex: 1. fruits = ("apple", "mango", "papaya", "pineapple",
"cherry")
1. fruits = ("apple", "banana", "cherry")
2. (green, *tropic, red) = fruits
2. print(fruits)
3. print(green)
• in Python, we are also allowed to extract the values 4. print(tropic)
back into variables. This is called "unpacking“.
5. print(red)
• Ex:
1. fruits = ("apple", "banana", "cherry") • Loop Through a Tuple
2. (green, yellow, red) = fruits • You can loop through the tuple items by using a for
3. print(green) loop.
4. print(yellow) • Ex:
5. print(red) 1. y = ("apple", "banana", "cherry")
• Note: The number of variables must match the number 2. for x in y:
of values in the tuple, if not, you must use an asterisk to 3. print(x)
collect the remaining values as a list. 33
• Join Two Tuples • Set Items
• To join two or more tuples you can use the + operator. • Set items are unordered, unchangeable, and do not allow
• Ex: duplicate values.
• tuple1 = ("a", "b" , "c") • Unordered
• tuple2 = (1, 2, 3) • Unordered means that the items in a set do not have a defined
• tuple3 = tuple1 + tuple2 order.
• print(tuple3)
• Unchangeable
• Multiply Tuples • Sets are unchangeable, meaning that we cannot change the
• If you want to multiply the content of a tuple a given number of items after the set has been created, but you can add new
times, you can use the * operator. items.
• Ex: • Duplicates Not Allowed
• fruits = ("apple", "banana", "cherry")
• Sets cannot have two items with the same value.
• mytuple = fruits * 2
• print(mytuple) • Ex:
• x = {"apple", "banana", "cherry", "apple"}
• Set • print(x)
• Sets are used to store multiple items in a single variable.
• Get the Length of a Set
• Set is one of 4 built-in data types in Python used to store
collections of data, the other 3 are List, Tuple, and Dictionary, all • To determine how many items a set has, use the len() method.
with different qualities and usage. • Ex:
• A set is a collection which is unordered, unchangeable, and • x= {"apple", "banana", "cherry"}
unindexed.(Sets are unordered, so you cannot be sure in which • print(len(x))
order the items will appear, it will show in a random order)
• Sets are written with curly brackets {}. • Set Items - Data Types
• Ex: • Set items can be of any data type.
1. thisset = {"apple", "banana", "cherry"} • Ex:
2. print(thisset) • set1 = {"apple", "banana", "cherry"}
• Output: {'banana', 'apple', 'cherry’} • set2 = {1, 5, 7, 9, 3}
• set3 = {True, False, False}

34
• A set can contain different data types. • Change Items
• Ex: • Once a set is created, you cannot change its items, but you can
• set1 = {"abc", 34, True, 40, "male"} add new items.
• type() • Add Items
• From Python's perspective, sets are defined as objects with the • Once a set is created, you cannot change its items, but you can
data type 'set‘. add new items by using the add() method.
• Ex: • Ex:
• x = {"apple", "banana", "cherry"} • x= {"apple", "banana", "cherry"}
• print(type(x)) • x.add("orange")
• print(x)
• The set() Constructor • Output: {'orange', 'cherry', 'apple', 'banana'}
• It is also possible to use the set() constructor to make a set.
• Ex: • Add Sets
• x = set(("apple", "banana", "cherry")) # note the double round- • To add items from another set into the current set, use the
brackets update() method.
• print(x) • Ex:
• x = {"apple", "banana", "cherry"}
• Access Items • y = {"pineapple", "mango", "papaya"}
• You cannot access items in a set by referring to an index or a • x.update(y)
key.
• print(x)
• But you can loop through the set items using a for loop, or ask
if a specified value is present in a set, by using the in keyword. • Add Any Iterable
• Ex: • The object in the update() method does not have to be a set, it
• y = {"apple", "banana", "cherry"} can be any iterable object (tuples, lists, dictionaries etc.).
• for x in y: • Ex:
• print(x) • thisset = {"apple", "banana", "cherry"}
• Ex: Check if "banana" is present in the set. • mylist = ["kiwi", "orange","mongo"]
• x = {"apple", "banana", "cherry"} • thisset.update(mylist)
• print("banana" in x) • print(thisset)

35
• Remove Item • The clear() method empties the set.
• To remove an item in a set, use the remove(), or • thisset = {"apple", "banana", "cherry"}
the discard() method. • thisset.clear()
• Ex: Remove "banana" by using the remove() • print(thisset)
method.
• thisset = {"apple", "banana", "cherry"} • The del keyword will delete the set completely.
• thisset.remove("banana") • Ex:
• print(thisset) • thisset = {"apple", "banana", "cherry"}
• Note: If the item to remove does not exist, • del thisset
remove() will raise an error. • print(thisset)
• Ex: Remove "banana" by using the discard() • You can loop through the set items by using a
method.
• thisset = {"apple", "banana", "cherry"}
for loop.
• thisset.discard("banana") • Ex:
• print(thisset) • thisset = {"apple", "banana", "cherry"}
• Note: If the item to remove does not exist, • for x in thisset:
discard() will NOT raise an error. • print(x)
• Note: You can also use the pop() method to • Join Two Sets
remove an item, but this method will remove the • There are several ways to join two or more sets in
last item. Remember that sets are unordered, so Python.
you will not know what item that gets removed.
• Ex: • You can use the union() method that returns a
new set containing all items from both sets, or the
• thisset = {"apple", "banana", "cherry"} update() method that inserts all the items from
• x = thisset.pop() one set into another.
• print(x) #removed item
• print(thisset) #the set after removal
36
• The union() method returns a new set with all • The intersection() method will return a new set,
items from both sets. that only contains the items that are present in
• Ex: both sets.
• set1 = {"a", "b" , "c"} • Ex:
• set2 = {1, 2, 3} • x = {"apple", "banana", "cherry"}
• set3 = set1.union(set2) • y = {"google", "microsoft", "apple"}
• print(set3) • z = x.intersection(y)
• Output: {3, 'b', 2, 1, 'c', 'a'} • print(z)
• The update() method inserts the items in set2 into • The symmetric_difference_update() method will
set1. keep only the elements that are NOT present in
• Ex: both sets.
• set1 = {"a", "b" , "c"} • Ex:
• set2 = {1, 2, 3} • x = {"apple", "banana", "cherry"}
• set1.update(set2) • y = {"google", "microsoft", "apple"}
• print(set1) • x.symmetric_difference_update(y)
• print(x)
• Note: Both union() and update() will exclude any
duplicate items. • The symmetric_difference() method will return a
• The intersection_update() method will keep only new set, that contains only the elements that are
the items that are present in both sets. NOT present in both sets.
• Ex:
• Ex: • x = {"apple", "banana", "cherry"}
• x = {"apple", "banana", "cherry"} • y = {"google", "microsoft", "apple"}
• y = {"google", "microsoft", "apple"} • z = x.symmetric_difference(y)
• x.intersection_update(y) • print(z)
• print(x)
• Output: {'apple'}

37
• Dictionary • Changeable
• Dictionaries are used to store data values in • Dictionaries are changeable, meaning that we
key:value pairs. can change, add or remove items after the
• A dictionary is a collection which is ordered*, dictionary has been created.
changeable and does not allow duplicates. • Duplicates Not Allowed
• Dictionaries are written with curly • Dictionaries cannot have two items with the
brackets {} and have keys and values. same key.
• Ex: • Ex:
• thisdict = { • thisdict = {
• “name": “Mohammad", • “name": “Mohammad",
• “Education": “Ph.D.", • “Education": “Ph.D.",
• "year": 2012 • "year": 2012,
• } • “year”:2013
• print(thisdict) • }
• Output: {'brand': 'Ford', 'model': • print(thisdict)
'Mustang', 'year': 1964}
• Dictionary items are presented in • Dictionary Length
key:value pairs and can be referred to • To determine how many items a dictionary has,
by using the key name. use the len() function.
• Ex: • Ex:
• thisdict = { • thisdict = {
• “name": “Mohammad", • “name": “Mohammad",
• “Education": “Ph.D.", • “Education": “Ph.D.",
• "year": 2012 • "year": 2012
• } • }
• print(thisdict[“Education"]) • print(len(thisdict))
• Output: Ph.D. 38
• Dictionary Items - Data Types • There is also a method called get() that will give you the same result.
• The values in dictionary items can be of any data type. • Ex:
• Ex: • thisdict = {
• x={ • "brand": "Ford",
• "brand": "Ford", • "model": "Mustang",
• "electric": False, • "year": 1964
• "year": 1964, • }
• "colors": ["red", "white", "blue"] • x = thisdict.get("model")
• } • print(x)
• print(x) • Get Keys
• Output: {'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white',
'blue’]} • The keys() method will return a list of all the keys in the dictionary.
• Ex:
• type()
• thisdict = {
• From Python's perspective, dictionaries are defined as objects with the • "brand": "Ford",
data type 'dict’.
• "model": "Mustang",
• Ex:
• "year": 1964
• thisdict = {
• }
• "brand": "Ford",
• x = thisdict.keys()
• "model": "Mustang",
• print(x)
• "year": 1964
• } • Add a new item to the original dictionary.
• print(type(thisdict)) • Ex:
• Accessing Items • car = {
• "brand": "Ford",
• You can access the items of a dictionary by referring to its
key name, inside square brackets []. • "model": "Mustang",
• "year": 1964
• Ex:
• }
• thisdict = {
• x = car.keys()
• "brand": "Ford",
• print(x) #before the change
• "model": "Mustang",
• car["color"] = "white"
• "year": 1964
• print(x) #after the change
• }
• Output: dict_keys(['brand', 'model', 'year’])
• x = thisdict["model"]
dict_keys(['brand', 'model', 'year', 'color'])
• print(x)
39
• Get Values • Add a new item to the original dictionary
• The values() method will return a list of all the • Ex:
values in the dictionary. • car = {
• Ex: • "brand": "Ford",
• thisdict = { • "model": "Mustang",
• "brand": "Ford", • "year": 1964
• "model": "Mustang", • }
• "year": 1964 • x = car.values()
• } • print(x) #before the change
• x = thisdict.values() • car["color"] = "red"
• print(x) • print(x) #after the change
• Output: dict_values(['Ford', 'Mustang', 1964]) • Output:dict_values(['Ford', 'Mustang', 1964])
• Make a change in the original dictionary. dict_values(['Ford', 'Mustang', 1964, 'red’])
• Ex: • Get Items
• car = { • The items() method will return each item in a
• "brand": "Ford", dictionary, as tuples in a list.
• "model": "Mustang", • Ex:
• "year": 1964 • thisdict = {
• } • "brand": "Ford",
• x = car.values() • "model": "Mustang",
• print(x) #before the change • "year": 1964
• car["year"] = 2020 • }
• print(x) #after the change • x = thisdict.items()
• Output: dict_values(['Ford', 'Mustang', 1964]) • print(x)
dict_values(['Ford', 'Mustang', 2020]) • Output: dict_items([('brand', 'Ford'), ('model',
'Mustang'), ('year', 1964)])
40
• Check if Key Exists • Removing Items
• To determine if a specified key is present in a • There are several methods to remove items from
dictionary use the in keyword. a dictionary.
• Ex: • The pop() method removes the item with the
• thisdict = { specified key name.
• "brand": "Ford", • Ex:
• "model": "Mustang", • thisdict = {
• "year": 1964 • "brand": "Ford",
• } • "model": "Mustang",
• if "model" in thisdict: • "year": 1964
• print("Yes, 'model' is one of the keys in the thisdict • }
dictionary") • thisdict.pop("model")
• Update Dictionary • print(thisdict)
• The update() method will update the dictionary • The popitem() method removes the last inserted
with the items from the given argument. item (in versions before 3.7, a random item is
removed instead).
• The argument must be a dictionary, or an iterable
object with key:value pairs. • Ex:
• Ex: • thisdict = {
• thisdict = { • "brand": "Ford",
• "brand": "Ford", • "model": "Mustang",
• "model": "Mustang", • "year": 1964
• "year": 1964 • }
• } • thisdict.popitem()
• thisdict.update({"year": 2020}) • print(thisdict)
• print(thisdict)

41
• The del keyword removes the item with the specified key name. • Loop Through a Dictionary
• Ex: • You can loop through a dictionary by using a for loop.
• thisdict = { • When looping through a dictionary, the return value are the keys of the
• "brand": "Ford", dictionary, but there are methods to return the values as well.
• "model": "Mustang", • Ex:
• "year": 1964 • thisdict = {
• } • "brand": "Ford",
• del thisdict["model"] • "model": "Mustang",
• print(thisdict) • "year": 1964
• The del keyword can also delete the dictionary completely. • }
• Ex: • for x in thisdict:
• thisdict = { • print(x)
• "brand": "Ford", • To print all values in the dictionary, one by one.
• "model": "Mustang", • Ex:
• "year": 1964 • thisdict = {
• } • "brand": "Ford",
• del thisdict • "model": "Mustang",
• print(thisdict) #this will cause an error because "thisdict" no longer exists. • "year": 1964
• The clear() method empties the dictionary. • }
• Ex: • for x in thisdict:
• thisdict = { • print(thisdict[x])
• "brand": "Ford", • You can also use the values() method to return values of a dictionary.
• "model": "Mustang", • Ex:
• "year": 1964 • thisdict = {
• } • "brand": "Ford",
• thisdict.clear() • "model": "Mustang",
• print(thisdict) • "year": 1964
• }
• for x in thisdict.values():
• print(x)

42
• You can use the keys() method to • Copy a Dictionary
return the keys of a dictionary. • You cannot copy a dictionary simply by
• Ex: typing dict2 = dict1, because: dict2 will
• thisdict = { only be a reference to dict1, and
• "brand": "Ford", changes made in dict1 will
• "model": "Mustang", automatically also be made in dict2.
• "year": 1964 • There are ways to make a copy, one
• } way is to use the built-in Dictionary
• for x in thisdict.keys(): method copy().
• print(x) • Ex:
• Loop through both keys and values, by • thisdict = {
using the items() method. • "brand": "Ford",
• Ex: • "model": "Mustang",
• thisdict = { • "year": 1964
• "brand": "Ford", • }
• "model": "Mustang", • mydict = thisdict.copy()
• "year": 1964 • print(mydict)
• }
• for x, y in thisdict.items():
• print(x, y)
43
• Another way to make a copy is to use the built-in function dict(). • Conditions and If statements
• Ex:
• thisdict = {
• Python supports the usual logical conditions from
• "brand": "Ford", mathematics:
• "model": "Mustang", 1. Equals: a == b
• "year": 1964
2. Not Equals: a != b
• }
• mydict = dict(thisdict) 3. Less than: a < b
• print(mydict) 4. Less than or equal to a <= b
• Nested Dictionaries 5. Greater than: a > b
• A dictionary can contain dictionaries, this is called nested dictionaries. 6. Greater than or equal to a >= b
• Ex: • These conditions can be used in several ways, most
• myfamily = { commonly in "if statements" and loops.
• "child1" : {
• "name" : "Mohammad", • An "if statement" is written by using the if keyword.
• "year" : 2019 • Ex:
• },
• "child2" : {
• a = 33
• "name" : "Rafi", • b = 200
• "year" : 2020 • if b > a:
• },
• print("b is greater than a")
• "child3" : {
• "name" : "Jabeen", • Indentation
• "year" : 2021 • Python relies on indentation (whitespace at the
• } beginning of a line) to define scope in the code.
• } Other programming languages often use curly-
• print(myfamily) brackets for this purpose.
• Output: {'child1': {'name': 'Mohammad', 'year': 2004}, 'child2': {'name': 'Rafi',
'year': 2007}, 'child3': {'name': 'Jabeen', 'year': 2011}}

44
• Elif • Shorthand If ... Else
• The elif keyword is pythons' way of saying "if the previous conditions • If you have only one statement to execute, one for if, and one for else,
were not true, then try this condition". you can put it all on the same line.
• Ex: • Ex:
• a = 33 • a=2
• b = 33 • b = 330
• if b > a: • print("A") if a > b else print("B")
• print("b is greater than a")
• elif a == b: • One line if else statement, with 3 conditions.
• print("a and b are equal")
• Ex:
• Else • a = 330
• b = 330
• The else keyword catches anything which isn't caught by the preceding
• print("A") if a > b else print("=") if a == b else print("B")
conditions.
• Ex: • And
• a = 200
• The and keyword is a logical operator and is used to combine
• b = 33
conditional statements.
• if b > a:
• print("b is greater than a") • Ex:
• elif a == b: • a = 200
• print("a and b are equal") • b = 33
• else: • c = 500
• print("a is greater than b") • if a > b and c > a:

• Shorthand If print("Both conditions are True")

• If you have only one statement to execute, you can put it on the same • Or
line as the if statement. • The or keyword is a logical operator and is used to combine conditional
• Ex: statements.
• a = 200 • Ex:
• b = 33
• a = 200
• if a > b: print("a is greater than b")
• b = 33
• c = 500
• if a > b or a > c:
• print("At least one of the conditions is True")

45
• Nested If • Python Loops
• You can have if statements inside if statements, • Python has two primitive loop commands:
this is called nested if statements. 1. while loops
• Ex: 2. for loops
• x = 41
• if x > 10:
• The while Loop
• print("Above ten,") • With the while loop we can execute a set of
• if x > 20:
statements as long as a condition is true.
• print("and also above 20!") • Ex:
• else: • i=1
• print("but not above 20.") • while i < 6:
• print(i)
• The pass Statement • i += 1
• if statements cannot be empty, but if you for
some reason have an if statement with no • The break Statement
content, put in the pass statement to avoid • With the break statement we can stop the loop
getting an error. even if the while condition is true.
• Ex: • Ex:
• a = 33 • i=1
• b = 200 • while i < 6:
• if b > a: • print(i)
• pass • if (i == 3):
• break
• i += 1

46
• The continue Statement • The break Statement
• With the continue statement we can stop the current • With the break statement we can stop the loop before
iteration and continue with the next. it has looped through all the items.
• Ex: • Ex:
• i=0 • fruits = ["apple", "banana", "cherry"]
• while i < 6: • for x in fruits:
• i += 1 • print(x)
• if i == 3: • if x == "banana":
• continue • break
• print(i)
• # Note that number 3 is missing in the result
• The range() Function
• The range() function returns a sequence of numbers,
• The else Statement starting from 0 by default, and increments by 1 (by
• With the else statement we can run a block of code default), and ends at a specified number.
once when the condition no longer is true. • To loop through a set of code a specified number of
• Ex: times, we can use the range() function.
• i=1 • Ex:
• while i < 6: • for x in range(6):
• print(i) • print(x)
• i += 1 • Note that range(6) is not the values of 0 to 6, but the
• else: values 0 to 5.
• print("i is no longer less than 6") • The range() function defaults to 0 as a starting value,
however it is possible to specify the starting value by
• For Loops adding a parameter: range(2, 6), which means values
• A for loop is used for iterating over a sequence. from 2 to 6 (but not including 6)
• Ex: • Ex:
• fruits = ["apple", "banana", "cherry"] • for x in range(2, 6):
• for x in fruits: • print(x)
• print(x)
47
• The range() function defaults to increment the • Ex: Break the loop when x is 3 and see
sequence by 1, however it is possible to specify what happens with the else block.
the increment value by adding a third • for x in range(6):
parameter: range(2, 30, 3). • if x == 3: break
• Ex: • print(x)
• for x in range(2, 30, 3): • else:
• print(x) • print("Finally finished!")
• Else in For Loop • Nested Loops
• The else keyword in a for loop specifies a block • A nested loop is a loop inside a loop.
of code to be executed when the loop is
finished. • The "inner loop" will be executed one
• Ex: Print all numbers from 0 to 5 and print a
time for each iteration of the "outer
message when the loop has ended.
loop“.
• for x in range(6): • Ex:
• print(x) • adj = ["red", "big", "tasty"]
• else: • fruits = ["apple", "banana", "cherry"]
• print("Finally finished!") • for x in adj:
• Note: The else block will NOT be executed if the • for y in fruits:
loop is stopped by a break statement. • print(x, y)

48
• Functions • Arguments/Parameters
• A function is a block of code which only • Information can be passed into functions as
runs when it is called. arguments.
• Arguments are specified after the function
• You can pass data, known as parameters, name, inside the parentheses.
into a function. • You can add as many arguments as you want,
• A function can return data as a result. just separate them with a comma (,).
• Ex:
• Creating a Function • def uni(uname):
• In Python a function is defined using the def • print(uname + " University")
keyword. • uni(“Catholic")
• Ex: • uni(“Salahaddin")
• def my_function(): • uni(“Koya")
• print("Hello from a function") • Lambda
• Calling a Function • A lambda function is a small unidentified
• To call a function, use the function name function.
followed by parenthesis().
• Ex:
• A lambda function can take any number of
arguments but can only have one
• def my_function(): expression.
• print("Hello from a function")
• my_function() • Syntax: lambda arguments : expression
• Ex: Add 10 to argument a, and return the
result
• x = lambda a: a + 10
• print(x(5))
49
• Lambda functions can take any number of • Create a Class
arguments. • To create a class, use the keyword class.
• Ex: • Ex: Create a class named MyClass, with a
• x = lambda a, b: a * b property named x.
• print(x(5, 6)) • class MyClass:
• x=5
• Ex: • print(MyClass)
• x = lambda a, b, c : a + b + c • Output: <class '__main__.MyClass’>
• print(x(5, 6, 2))
• Create Object
• Arrays • Now we can use the class named MyClass to
create objects.
• Python does not have built-in support for
Arrays, but Lists can be used instead. • Ex: Create an object named p1, and print the
value of x.
• Classes/Objects • class MyClass:
• Python is an object-oriented programming • x=5
language. • p1 = MyClass()
• print(p1.x)
• Almost everything in Python is an object,
with its properties and methods.
• A Class is like an object constructor, or a
"blueprint" for creating objects. 50
• The __init__() Function • Object Methods
• To understand the meaning of classes we • Objects can also contain methods.
have to understand the built-in __init__() Methods in objects are functions that
function. belong to the object.
• All classes have a function called • Ex:
__init__(), which is always executed when • class Person:
the class is being initiated. • def __init__(self, name, age):
• Use the __init__() function to assign values • self.name = name
to object properties. • self.age = age
• Ex: Create a class named Person, use the • def myfunc(self):
__init__() function to assign values for • print("Hello my name is " + self.name)
name and age .
• p1 = Person("John", 36)
• class Person:
• p1.myfunc()
• def __init__(self, name, age):
• Note: The self parameter is a reference to
• self.name = name the current instance of the class and is
• self.age = age used to access variables that belong to the
• p1 = Person("John", 36) class.
• print(p1.name)
• print(p1.age)

51
• Modify Object Properties • Delete Objects
• You can modify properties on objects. • You can delete objects by using the del keyword.
• Ex: • Ex:
• class Person: • class Person:
• def __init__(self, name, age): • def __init__(self, name, age):
• self.name = name • self.name = name
• self.age = age • self.age = age
• def myfunc(self): • def myfunc(self):
• print("Hello my name is " + self.name) • print("Hello my name is " + self.name)
• p1 = Person("John", 36) • p1 = Person("John", 36)
• p1.age = 40 • del p1
• print(p1.age) • print(p1)
• Delete Object Properties • The pass Statement
• You can delete properties on objects by using the • class definitions cannot be empty, but if you for
del keyword. some reason have a class definition with no
• Ex: content, put in the pass statement to avoid getting
• class Person:
an error.
• def __init__(self, name, age): • Ex:
• self.name = name • class Person:
• self.age = age • pass
• def myfunc(self):
• print("Hello my name is " + self.name)
• p1 = Person("John", 36)
• del p1.age
• print(p1.age)
52
• Inheritance • Create a Child Class
• Inheritance allows us to define a class that • To create a class that inherits the
inherits all the methods and properties functionality from another class, send the
parent class as a parameter when creating
from another class. the child class.
• Parent class is the class being inherited from, • Ex: Create a class named Student, which will
also called base class. inherit the properties and methods from the
• Child class is the class that inherits from Person class.
another class, also called derived class. • class Student(Person):
• Create a Parent Class • pass
• Any class can be a parent class, so the syntax • Note: Now the Student class has the same
is the same as creating any other class. properties and methods as the Person class.
• Ex: • Ex: Use the Student class to create an object,
• class Person: and then execute the printname method
• def __init__(self, fname, lname): • class Person:
• self.firstname = fname • def __init__(self, fname, lname):
• self.lastname = lname • self.firstname = fname
• def printname(self): • self.lastname = lname
• print(self.firstname, self.lastname) • def printname(self):
• #Use the Person class to create an object, • print(self.firstname, self.lastname)
and then execute the printname method: • class Student(Person):
• x = Person("John", "Doe") • pass
• x.printname() • x = Student("Mike", "Olsen")
• x.printname()

53
• Add the __init__() Function • Iterators
• So far, we have created a child class • An iterator is an object that contains a
that inherits the properties and countable number of values.
methods from its parent. • An iterator is an object that can be
• We want to add the __init__() function iterated upon, meaning that you can
to the child class traverse through all the values.
• Lists, tuples, dictionaries, and sets are
all iterable objects.
• All these objects have an iter() method
which is used to get an iterator.
• Ex: Return an iterator from a tuple and
print each value.
• mytuple = ("apple", "banana", "cherry")
• myit = iter(mytuple)
• print(next(myit))
• print(next(myit))
• print(next(myit))
54
• Even strings are iterable objects and can • Looping Through an Iterator
return an iterator. • We can also use a for loop to iterate
• Ex: Strings are also iterable objects, through an iterable object.
containing a sequence of characters. • Ex: Iterate the values of a tuple.
• mystr = "banana" • mytuple = ("apple", "banana", "cherry")
• myit = iter(mystr) • for x in mytuple:
• print(next(myit)) • print(x)
• print(next(myit)) • Output:
apple
• print(next(myit)) banana
• print(next(myit)) Cherry
• print(next(myit)) • Ex: Iterate the characters of a string.
• print(next(myit)) • mystr = "banana"
• Output: • for x in mystr:
b • print(x)
a • Output:
n b
a a
n n
a a
n
a
55
• Scope • Function Inside Function
• A variable is only available from inside • As explained in the example above, the
the region it is created. This is called variable x is not available outside the
scope. function, but it is available for any
• Local Scope function inside the function.
• A variable created inside a function • Ex: The local variable can be accessed
belongs to the local scope of that function from a function within the function.
and can only be used inside that function. • def myfunc():
• Ex: A variable created inside a function is • x = 300
available inside that function.
• def myinnerfunc():
• def myfunc():
• x = 300
• print(x)
• print(x) • myinnerfunc()
• myfunc() • myfunc()
• Ouput: 300 • Output: 300

56
• Global Scope • Naming Variables
• A variable created in the main body of • If you operate with the same variable
the Python code is a global variable name inside and outside of a function,
and belongs to the global scope. Python will treat them as two separate
• Global variables are available from variables, one available in the global
within any scope, global and local. scope (outside the function) and one
• Ex: A variable created outside of a available in the local scope (inside the
function is global and can be used by function).
anyone. • Ex: The function will print the local x,
• x = 300 and then the code will print the global
• def myfunc(): x.
• print(x) • x = 300
• myfunc() • def myfunc():
• print(x) • x = 200
• Output: • print(x)
300 • myfunc()
300 • print(x)
• Output:
200
300
57
• Global Keyword • use the global keyword if you want
• If you need to create a global variable, to make a change to a global variable
but are stuck in the local scope, you inside a function.
can use the global keyword.
• Ex:
• The global keyword makes the variable
global. • x = 300
• Ex: If you use the global keyword, the • def myfunc():
variable belongs to the global scope. • global x
• def myfunc(): • x = 200
• global x • myfunc()
• x = 300 • print(x)
• myfunc()
• Output:
• print(x)
• Output: 200
300

58
• Modules • Variables in Module
• Consider a module to be the same as a • The module can contain functions, as
code library. already described, but also variables of all
• A file containing a set of functions you types (arrays, dictionaries, objects etc).
want to include in your application. • Ex: Save this code in the file mymodule.py
• Create a Module 1. person1 = {
• To create a module just save the code you 2. "name": "John",
want in a file with the file extension .py 3. "age": 36,
• Ex: Save this code in a file named 4. "country": "Norway"
mymodule.py 5. }
1. def greeting(name):
2. print("Hello, " + name)
• Ex: Import the module named mymodule,
and access the person1 dictionary.
• Use a Module 1. import mymodule
• Now we can use the module we just 2. a = mymodule.person1["age"]
created, by using the import statement.
• When using a function from a module, use 3. print(a)
the syntax: module_name.function_name. • Re-naming a Module
• Ex: Import the module named “mymodule”
and call the greeting function. • You can create an alias when you import a
1. import mymodule module, by using the as keyword.
2. mymodule.greeting(“Mohammad") • Ex: Create an alias for mymodule called
Output: Hello, Mohammad mx.
1. Import mymodule as mx

59
• Built-in Modules • Import From Module
• There are several built-in modules in • You can choose to import only parts from a
Python, which you can import whenever module, by using the from keyword.
you like. • Ex: The module named mymodule has one
• Ex: Import and use the platform module. function and one dictionary.
1. import platform 1. def greeting(name):
2. x = platform.system() 2. print("Hello, " + name)
3. print(x) 3. person1 = {
• Output: Windows 4. "name": "John",
• Using the dir() Function 5. "age": 36,
• There is a dir() built-in function to list all the 6. "country": "Norway"
function names (or variable names) in a 7. }
module. • Ex: Import only the person1 dictionary
• Ex: List all the defined names belonging to from the module.
the platform module.
1. from mymodule import person1
1. import platform
2. print (person1["age"])
2. x = dir(platform)
3. print(x) • Note: When importing using the from
keyword, do not use the module name
when referring to elements in the module.
Example: person1["age"], not
mymodule.person1["age"]
60
• Datetime • Creating Date Objects
• Dates • To create a date, we can use the datetime()
• A date in Python is not a data type of its class (constructor) of the datetime module.
own, but we can import a module named • The datetime() class requires three
datetime to work with dates as date parameters to create a date: year, month,
objects. day.
• Ex: Import the datetime module and • Ex: Create a date object.
display the current date. 1. import datetime
1. import datetime 2. x = datetime.datetime(2020, 5, 17)
2. x = datetime.datetime.now() 3. print(x)
3. print(x) • Output: 2020-05-17 00:00:00
• Ouput: 2022-02-01 15:10:19.024787 • The datetime() class also takes parameters
• The date contains year, month, day, hour, for time and timezone (hour, minute,
minute, second, and microsecond. second, microsecond, tzone), but they are
• Ex: Return the year and name of weekday. optional, and has a default value of 0,
1. import datetime (None for timezone).
2. x = datetime.datetime.now() • The strftime() Method
3. print(x.year) • The datetime object has a method for
4. print(x.strftime("%A")) formatting date objects into readable
• Output: strings.
2022 • The method is called strftime(), and takes
Tuesday one parameter, format, to specify the
format of the returned string:
61
• Ex: Display the name of the month. • %d-Day of month 01-31
1. import datetime 1. import datetime
2. x = datetime.datetime(2018, 6, 1) 2. x = datetime.datetime.now()
3. print(x.strftime("%B")) 3. print(x.strftime("%d"))
• Output: June • Output: 03
• The legal format codes • %b-Month name, short version
1. import datetime
• %a - Weekday, short version. 2. x = datetime.datetime.now()
1. import datetime
3. print(x.strftime("%b"))
2. x = datetime.datetime.now()
3. print(x.strftime("%a"))
• Output: Feb
• Output: Thu • %B-Month name, full version
1. import datetime
• %A-Weekday, full version 2. x = datetime.datetime.now()
1. import datetime
3. print(x.strftime("%B"))
2. x = datetime.datetime.now()
3. print(x.strftime("%A"))
• Output: February
• Output: Thursday • %m-Month as a number 01-12
1. import datetime
• %w-Weekday as a number 0-6, 0 is Sunday 2. x = datetime.datetime.now()
1. import datetime
3. print(x.strftime("%m"))
2. x = datetime.datetime.now()
3. print(x.strftime("%w"))
• Output: 02
• Output: 4 • %y-Year, short version, without century
1. import datetime
2. x = datetime.datetime.now()
3. print(x.strftime("%y"))
• Output: 22
62
• %Y-Year, full version • %M-Minute 00-59
1. import datetime 1. import datetime
2. x = datetime.datetime.now() 2. x = datetime.datetime.now()
3. print(x.strftime("%Y")) 3. print(x.strftime("%M"))
• Output: 2022 • Output: 59
• %H-Hour 00-23 • %S-Second 00-59
1. import datetime 1. import datetime
2. x = datetime.datetime.now() 2. x = datetime.datetime.now()
3. print(x.strftime("%H")) 3. print(x.strftime("%S"))
• Output: 10 • Output:45
• %I-Hour 00-12 • %j-Day number of year 001-366
1. import datetime 1. import datetime
2. x = datetime.datetime.now() 2. x = datetime.datetime.now()
3. print(x.strftime("%I")) 3. print(x.strftime("%j"))
• Output: 10 • Output:34
• %p-AM/PM
1. import datetime
2. x = datetime.datetime.now()
3. print(x.strftime("%p"))
• Output: AM
63
• Math • When you have imported the math module, you can start using
• Python has a set of built-in math functions, including an methods and constants of the module.
extensive math module, that allows you to perform • The math.sqrt() method for example, returns the square root
mathematical tasks on numbers. of a number.
1. import math
• Built-in Math Functions 2. x = math.sqrt(64)
• The min() and max() functions can be used to find the lowest 3. print(x)
or highest value in an iterable.
• Output: 8
1. x = min(5, 10, 25)
2. y = max(5, 10, 25)
• The math.ceil() method rounds a number upwards to its
nearest integer.
3. print(x)
• The math.floor() method rounds a number downwards to its
4. print(y) nearest integer and returns the result.
• Output: 5, 25 1. #Import math library
• The abs() function returns the absolute (positive) value of the 2. import math
specified number. 3. #Round a number upward to its nearest integer
1. x = abs(-7.25) 4. x = math.ceil(1.4)
2. print(x) 5. #Round a number downward to its nearest integer
• Output: 7.25 6. y = math.floor(1.4)
• The pow(x, y) function returns the value of x to the power of y 7. print(x)
(xy). 8. print(y)
• Return the value of 4 to the power of 3 (same as 4 * 4 * 4) • Output: 2, 1
1. x = pow(4, 3) • The math.pi constant, returns the value of PI (3.14...)
2. print(x) 1. import math
• Output: 64 2. x = math.pi
• The Math Module 3. print(x)
• Python has also a built-in module called math, which extends • Output: 3.141592653589793
the list of mathematical functions.
• To use it , you must import the math module like “import
math”.

64
• JSON (JavaScript Object Notation) • Convert from Python to JSON
• JSON is a syntax for storing and exchanging • If you have a Python object, you can convert it
data. into a JSON string by using the json.dumps()
• JSON is text, written with JavaScript object method.
notation. • Ex: Convert from Python to JSON
• Python has a built-in package called json, which 1. import json
can be used to work with JSON data. 2. # a Python object (dict):
• Import the json module like “import json”. 3. x={
4. "name": "John",
• Parse JSON - Convert from JSON to Python 5. "age": 30,
• If you have a JSON string, you can parse it by 6. "city": "New York"
using the json.loads() method. 7. }
• After conversion, the result will be a Python 8. # convert into JSON:
dictionary. 9. y = json.dumps(x)
• Ex: Convert from JSON to Python 10. # the result is a JSON string:
1. import json 11. print(y)
2. # some JSON: • Output: {"name": "John", "age": 30, "city":
3. x = '{ "name":"John", "age":30, "city":"New "New York"}
York"}'
4. # parse x:
5. y = json.loads(x)
6. # the result is a Python dictionary:
7. print(y["age"])
• Output: 30

65
• You can convert Python objects of the following types, into JSON • Ex: Convert a Python object containing all the legal data types
strings: 1. import json
• dict 2. x={
• list 3. "name": "John",
• tuple 4. "age": 30,
5. "married": True,
• string
6. "divorced": False,
• int 7. "children": ("Ann","Billy"),
• float 8. "pets": None,
• True 9. "cars": [
• False 10. {"model": "BMW 230", "mpg": 27.5},
• None 11. {"model": "Ford Edge", "mpg": 24.1}
• Ex: Convert Python objects into JSON strings and print the values. 12. ]
1. import json 13. }
2. print(json.dumps({"name": "John", "age": 30})) 14. # convert into JSON:
3. print(json.dumps(["apple", "bananas"])) 15. y = json.dumps(x)
4. print(json.dumps(("apple", "bananas"))) 16. # the result is a JSON string:
5. print(json.dumps("hello")) 17. print(y)
6. print(json.dumps(42)) • Output:{"name": "John", "age": 30, "married": true, "divorced": false,
7. print(json.dumps(31.76)) "children": ["Ann","Billy"], "pets": null, "cars": [{"model": "BMW 230",
"mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1}]}
8. print(json.dumps(True))
9. print(json.dumps(False))
10. print(json.dumps(None))
• Output:
1. {"name": "John", "age": 30}
2. ["apple", "bananas"]
3. ["apple", "bananas"]
4. "hello"
5. 42
6. 31.76
7. true
8. false
9. null

66
• RegEx • RegEx Functions
• A RegEx, or Regular Expression, is a • The re module offers a set of functions that
sequence of characters that forms a search allows us to search a string for a match.
pattern. Function Description
• RegEx can be used to check if a string findall Returns a list containing all matches
contains the specified search pattern. search Returns a Match object if there is a match anywhere in the string
• RegEx Module split Returns a list where the string has been split at each match
• Python has a built-in package called re, which sub Replaces one or many matches with a string
can be used to work with Regular
Expressions.
• Import the re module like “import re”.
• The findall() Function
• Ex: Search the string to see if it starts with • The findall() function returns a list
"The" and ends with "Spain“. containing all matches.
1. import re • Ex: Print a list of all matches
2. #Check if the string starts with "The" and 1. import re
ends with "Spain" 2. #Return a list containing every occurrence
3. txt = "The rain in Spain" of "ai":
4. x = re.search("^The.*Spain$", txt) 3. txt = "The rain in Spain"
5. if x: 4. x = re.findall("ai", txt)
6. print("YES! We have a match!") 5. print(x)
7. else: • Output: ['ai', 'ai’]
8. print("No match")
• Output: YES! We have a match!
67
• The search() Function • The split() Function
• The search() function searches the • The split() function returns a list where
string for a match and returns a Match the string has been split at each match.
object if there is a match. • Ex: Split at each white-space character.
• If there is more than one match, only 1. import re
the first occurrence of the match will 2. #Split the string at every white-space
be returned. character:
• Ex: Search for the first white-space 3. txt = "The rain in Spain"
character in the string 4. x = re.split("\s", txt)
1. import re 5. print(x)
2. txt = "The rain in Spain" • Output: ['The', 'rain', 'in', 'Spain’]
3. x = re.search("\s", txt)
4. print("The first white-space character is
located in position:", x.start())
• Output: The first white-space character
is in position: 3

68
• The sub() Function • \ - Signals a special sequence
• The sub() function replaces the matches with 1. import re
the text of your choice. 2. txt = "That will be 59 dollars"
• Ex: Replace every white-space character with 3. #Find all digit characters:
the number 9. 4. x = re.findall("\d", txt)
1. import re 5. print(x)
2. #Replace all white-space characters with the • Output: ['5', '9’]
digit "9": • . - Any character (except newline character)
3. txt = "The rain in Spain" 1. import re
4. x = re.sub("\s", "9", txt) 2. txt = "hello planet"
5. print(x) 3. #Search for a sequence that starts with "he",
• Output: The9rain9in9Spain followed by two (any) characters, and an "o":
4. x = re.findall("he..o", txt)
• Metacharacters 5. print(x)
• Metacharacters are characters with a special • Output: ['hello’]
meaning. • ^ - starts with
• [] - A set of characters 1. import re
1. import re 2. txt = "hello planet"
2. txt = "The rain in Spain" 3. #Check if the string starts with 'hello':
3. #Find all lower-case characters alphabetically 4. x = re.findall("^hello", txt)
between "a" and “z":
4. x = re.findall("[a-z]", txt) 5. if x:
5. print(x) 6. print("Yes, the string starts with 'hello'")
• Output: ['h', 'e', 'r', 'a', 'i', 'n', 'i', 'n', 'p', 'a', 'i', 'n'] 7. else:
8. print("No match")
• Output: Yes, the string starts with 'hello'
69
• $ -Ends with • ? - Zero or one occurrences
1. import re 1. import re
2. txt = "hello planet" 2. txt = "hello planet"
3. #Check if the string ends with 'planet': 3. #Search for a sequence that starts with "he", followed by
4. x = re.findall("planet$", txt) 0 or 1 (any) character, and an "o":
5. if x: 4. x = re.findall("he.?o", txt)
6. print("Yes, the string ends with 'planet'") 5. print(x)
7. else: 6. #This time we got no match, because there were not
zero, not one, but two characters between "he" and the
8. print("No match") "o“.
• Output: Yes, the string ends with 'world’ • Output:[]
• * - Zero or more occurrences • {} - Exactly the specified number of occurrences
1. import re 1. import re
2. txt = "hello planet" 2. txt = "hello planet"
3. #Search for a sequence that starts with "he", followed by 3. #Search for a sequence that starts with "he", followed
0 or more (any) characters, and an "o": excactly 2 (any) characters, and an "o":
4. x = re.findall("he.*o", txt) 4. x = re.findall("he.{2}o", txt)
5. print(x) 5. print(x)
• Output: ['hello’] • Output: ['hello’]
• + - One or more occurrences • | - Either or
1. import re 1. import re
2. txt = "hello planet" 2. txt = "The rain in Spain falls mainly in the plain!"
3. #Search for a sequence that starts with "he", followed by 3. #Check if the string contains either "falls" or "stays":
1 or more (any) characters, and an "o": 4. x = re.findall("falls|stays", txt)
4. x = re.findall("he.+o", txt) 5. print(x)
5. print(x) 6. if x:
• Output: ['hello'] 7. print("Yes, there is at least one match!")
8. else:
9. print("No match")
• Output: ['falls’], Yes, there is at least one match!
70
• Special Sequences • \d - Returns a match where the string contains digits (numbers from 0-9)
• A special sequence is a \ followed by one of the characters in the list below and has a 1. import re
special meaning. 2. txt = "The rain in Spain"
• \A - Returns a match if the specified characters are at the beginning of the string. 3. #Check if the string contains any digits (numbers from 0-9):
1. import re 4. x = re.findall("\d", txt)
2. txt = "The rain in Spain" 5. print(x)
3. #Check if the string starts with "The": 6. if x:
4. x = re.findall("\AThe", txt) 7. print("Yes, there is at least one match!")
5. print(x) 8. else:
6. if x: 9. print("No match")
7. print("Yes, there is a match!") • Output: [], No match
8. else: • \s - Returns a match where the string contains a white space character
9. print("No match") 1. import re
• Output: ['The’],Yes, there is a match! 2. txt = "The rain in Spain"
• \b - Returns a match where the specified characters are at the beginning or at the 3. #Return a match at every white-space character:
end of a word.(the "r" in the beginning is making sure that the string is being treated 4. x = re.findall("\s", txt)
as a "raw string").
1. import re 5. print(x)
2. txt = "The rain in Spain" 6. if x:
3. #Check if "ain" is present at the beginning of a WORD: 7. print("Yes, there is at least one match!")
4. x = re.findall(r"\bain", txt) 8. else:
5. print(x) 9. print("No match")
6. if x: • Output: [' ', ' ', ' ‘], Yes, there is at least one match!
7. print("Yes, there is at least one match!") • \S - Returns a match where the string DOES NOT contain a white space character
8. else: 1. import re
9. print("No match") 2. txt = "The rain in Spain"
• Output: [],No match 3. #Return a match at every NON white-space character:
1. import re 4. x = re.findall("\S", txt)
2. txt = "The rain in Spain" 5. print(x)
3. #Check if "ain" is present at the end of a WORD: 6. if x:
4. x = re.findall(r"ain\b", txt) 7. print("Yes, there is at least one match!")
5. print(x) 8. else:
6. if x: 9. print("No match")
7. print("Yes, there is at least one match!") • Output: ['T', 'h', 'e', 'r', 'a', 'i', 'n', 'i', 'n', 'S', 'p', 'a', 'i', 'n’], Yes, there is at least one
match!
8. else:
9. print("No match")
• Output: ['ain', 'ain’], Yes, there is at least one match!

71
• \w - Returns a match where the string contains any word characters (characters from a to Z, digits from
0-9, and the underscore _ character) • Sets
1.
2.
import re
txt = "The rain in Spain" • A set is a set of characters inside a pair of square
3. #Return a match at every word character (characters from a to Z, digits from 0-9, and the underscore _
character):
brackets [] with a special meaning:
4. x = re.findall("\w", txt) • arn -Returns a match where one of the specified
5.
6.
print(x)
if x:
characters (a, r, or n) are present.
7. print("Yes, there is at least one match!") 1. import re
8. else:
9. print("No match") 2. txt = "The rain in Spain"
• Output: ['T', 'h', 'e', 'r', 'a', 'i', 'n', 'i', 'n', 'S', 'p', 'a', 'i', 'n’],Yes, there is at least one match! 3. #Check if the string has any a, r, or n characters:
• \W - Returns a match where the string DOES NOT contain any word characters (non word characters).
1. import re
4. x = re.findall("[arn]", txt)
2. txt = "The rain in Spain" 5. print(x)
3. #Return a match at every NON word character (characters NOT between a and Z. Like "!", "?" white-space etc.):
4. x = re.findall("\W", txt) 6. if x:
5. print(x) 7. print("Yes, there is at least one match!")
6. if x:
7. print("Yes, there is at least one match!") 8. else:
8.
9.
else:
print("No match")
9. print("No match")
• Output:[' ', ' ', ' ‘], Yes, there is at least one match! • Output:['r', 'a', 'n', 'n', 'a', 'n’], Yes, there is at least one
• \Z - Returns a match if the specified characters are at the end of the string match!
1.
2.
import re
txt = "The rain in Spain"
• [a-n] - Returns a match for any lower-case
3. #Check if the string ends with "Spain": character, alphabetically between a and n.
4.
5.
x = re.findall("Spain\Z", txt)
print(x)
1. import re
6. if x: 2. txt = "The rain in Spain"
7. print("Yes, there is a match!")
8. else:
3. #Check if the string has any characters between a and n:
9. print("No match") 4. x = re.findall("[a-n]", txt)
• Output: ['Spain’], Yes, there is a match!
5. print(x)
6. if x:
7. print("Yes, there is at least one match!")
8. else:
9. print("No match")
• Output: ['h', 'e', 'a', 'i', 'n', 'i', 'n', 'a', 'i', 'n’], Yes, there is at
least one match!

72
• [^arn] - Returns a match for any character EXCEPT a, r, and n. • [a-zA-Z] - Returns a match for any character alphabetically between a
1. import re and z, lower case OR upper case.
2. txt = "The rain in Spain" 1. import re
3. #Check if the string has other characters than a, r, or n: 2. txt = "8 times before 11:45 AM"
4. x = re.findall("[^arn]", txt) 3. #Check if the string has any characters from a to z lower case, and A to
Z upper case:
5. print(x)
4. x = re.findall("[a-zA-Z]", txt)
6. if x:
5. print(x)
7. print("Yes, there is at least one match!")
6. if x:
8. else:
7. print("Yes, there is at least one match!")
9. print("No match")
8. else:
• Output: ['T', 'h', 'e', ' ', 'i', ' ', 'i', ' ', 'S', 'p', 'i’],Yes, there is at least one match! 9. print("No match")
• [0123] - Returns a match where any of the specified digits (0, 1, 2, or 3) • Output:
are present.
• ['t', 'i', 'm', 'e', 's', 'b', 'e', 'f', 'o', 'r', 'e',
1. import re 'A', 'M’],Yes, there is at least one match!
2. txt = "The rain in Spain" • [+]- In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means return
3. #Check if the string has any 0, 1, 2, or 3 digits: a match for any + character in the string.
4. x = re.findall("[0123]", txt) 1. import re
5. print(x) 2. txt = "8 times before+ 11:45 AM"
6. if x: 3. #Check if the string has any + characters:
7. print("Yes, there is at least one match!") 4. x = re.findall("[+]", txt)
8. else: 5. print(x)
9. print("No match") 6. if x:
• Output: No match 7. print("Yes, there is at least one match!")
• [0-9] - Returns a match for any digit between 0 and 9. 8. else:
1. import re 9. print("No match")
2. txt = "8 times before 11:45 AM" • Output: ['+’],Yes, there is at least one match!
3. #Check if the string has any digits:
4. x = re.findall("[0-9]", txt)
5. print(x)
6. if x:
7. print("Yes, there is at least one match!")
8. else:
9. print("No match")
• Output: ['8', '1', '1', '4', '5’],Yes, there is at least one match!

73
• Python PIP (Pip Installs Packages/preferred installer • Remove a Package
program) • Use the uninstall command to remove a package:
• What is PIP? • C:\Users\Your Name\AppData\Local\Programs\Python\Python36-
32\Scripts>pip uninstall camelCase
• PIP is a package manager for Python packages, or modules if you • List Packages
like.
• What is a Package? • Use the list command to list all the packages installed on your
system:
• A package contains all the files you need for a module. • C:\Users\Your Name\AppData\Local\Programs\Python\Python36-
• Modules are Python code libraries you can include in your 32\Scripts>pip list
project.
• Check if PIP is Installed
• Try Except
• Navigate your command line to the location of Python's script • The try block lets you test a block of code for errors.
directory, and type the following: • The except block lets you handle the error.
• pip - - version • The else block lets you execute code when there is no error.
• Download a Package • The finally block lets you execute code, regardless of the result
• Downloading a package is very easy. of the try- and except blocks.
• Open the command line interface and tell PIP to download the • Exception Handling
package you want. • When an error occurs, or exception as we call it, Python will
• Navigate your command line to the location of Python's script normally stop and generate an error message.
directory, and type the following: • These exceptions can be handled using the try statement:
• Example • The try block will generate an exception, because x is not
• Download a package named "camelcase": defined:
• C:\Users\Your Name\AppData\Local\Programs\Python\Python36- • #The try block will generate an error, because x is not defined:
32\Scripts>pip install camelCase
1. try:
• Using a Package 2. print(x)
• Once the package is installed, it is ready to use. 3. except:
• Import the "camelcase" package into your project. 4. print("An exception occurred")
1. import camelcase • Output: An exception occurred
2. c = camelcase.CamelCase()
3. txt = "lorem ipsum dolor sit amet"
• Since the try block raises an error, the except block will be
4. print(c.hump(txt)) executed.
5. #This method capitalizes the first letter of each word. • Without the try block, the program will crash and raise an error:
• #This will raise an exception, because x is not defined:
• print(x)
74
• Many Exceptions • Try to open and write to a file that is not writable:
• You can define as many exception blocks as you want, e.g., if you want to • #The try block will raise an error when trying to write to a read-only file:
execute a special block of code for a special kind of error. 1. try:
• Print one message if the try block raises a NameError and another for other 2. f = open("demofile.txt")
errors:
3. try:
• #The try block will generate a NameError, because x is not defined:
4. f.write("Lorum Ipsum")
1. try:
5. except:
2. print(x)
6. print("Something went wrong when writing to the file")
3. except NameError:
7. finally:
4. print("Variable x is not defined")
8. f.close()
5. except:
9. except:
6. print("Something else went wrong")
10. print("Something went wrong when opening the file")
• Else
• You can use the else keyword to define a block of code to be executed if no • Raise an exception
errors were raised: • As a Python developer you can choose to throw an exception if a
• In this example, the try block does not generate any error: condition occurs.
• #The try block does not raise any errors, so the else block is executed: • To throw (or raise) an exception, use the raise keyword.
1. try:
• #Raise an error and stop the program if x is lower than 0:
2. print("Hello")
3. except:
1. x = -1
4. print("Something went wrong") 2. if x < 0:
5. else: 3. raise Exception("Sorry, no numbers below zero")
6. print("Nothing went wrong") • The raise keyword is used to raise an exception.
• Finally • You can define what kind of error to raise, and the text to print to the
• The finally block, if specified, will be executed regardless if the try block user.
raises an error or not.
• #The finally block gets executed no matter if the try block raises any errors or
not:
1. try:
2. print(x)
3. except:
4. print("Something went wrong")
5. finally:
6. print("The 'try except' is finished")

75
• User Input • To control such values, add placeholders
(curly brackets {}) in the text, and run the
• Python allows for user input. values through the format() method:
• That means we are able to ask the user for 1. price = 49
input. 2. txt = "The price is {} dollars"
• The method is a bit different in Python 3.6 3. print(txt.format(price))
than Python 2.7. • Output: The price is 49 dollars
• Python 3.6 uses the input() method. • You can add parameters inside the curly
• Python 2.7 uses the raw_input() method. brackets to specify how to convert the
value.
• The following example asks for the 1. price = 49
username, and when you entered the 2. txt = "The price is {:.2f} dollars"
username, it gets printed on the screen: 3. print(txt.format(price))
1. username = input("Enter username:") • Output: The price is 49.00 dollars
2. print("Username is: " + username)
• Multiple Values
• String Formatting • If you want to use more values, just add more
• To make sure a string will display as values to the format() method:
expected, we can format the result with 1. quantity = 3
the format() method. 2. itemno = 567
• format() 3. price = 49
• The format() method allows you to format 4. myorder = "I want {} pieces of item number
selected parts of a string. {} for {:.2f} dollars."
• Sometimes there are parts of a text that you 5. print(myorder.format(quantity, itemno,
do not control, maybe they come from a price))
database, or user input?
76
• Index Numbers • Named Indexes
• You can use index numbers (a number • You can also use named indexes by
inside the curly brackets {0}) to be sure entering a name inside the curly brackets
the values are placed in the correct {carname}, but then you must use names
placeholders: when you pass the parameter values
1. quantity = 3 txt.format(carname = "Ford"):
2. itemno = 567 1. myorder = "I have a {carname}, it is a
{model}."
3. price = 49
4. myorder = "I want {0} pieces of item 2. print(myorder.format(carname = "Ford",
number {1} for {2:.2f} dollars." model = "Mustang"))
5. print(myorder.format(quantity, itemno, • File Handling
price))
• File handling is an important part of any
• Also, if you want to refer to the same web application.
value more than once, use the index
number: • Python has several functions for
1. age = 36 creating, reading, updating, and
2. name = "John" deleting files.
3. txt = "His name is {1}. {1} is {0} years • The key function for working with files
old." in Python is the open() function.
4. print(txt.format(age, name)) • The open() function takes two
parameters; filename, and mode.
77
• There are four different methods • Syntax
(modes) for opening a file: • To open a file for reading it is enough to
• "r" - Read - Default value. Opens a file specify the name of the file:
for reading, error if the file does not • f = open(“test.txt")
exist. Or
• f = open(“test.txt", "rt")
• "a" - Append - Opens a file for
appending, creates the file if it does • Because "r" for read, and "t" for text are
the default values, you do not need to
not exist. specify them.
• "w" - Write - Opens a file for writing, • Note: Make sure the file exists, or else
creates the file if it does not exist. you will get an error.
• "x" - Create - Creates the specified file, • To open the file, use the built-in open()
returns an error if the file exists. function.
• "t" - Text - Default value. Text mode • The open() function returns a file
• "b" - Binary - Binary mode (e.g., object, which has a read() method for
images) reading the content of the file:
1. f = open("demofile.txt", "r")
2. print(f.read())
78
• If the file is located in a different location, • By looping through the lines of the file, you
you will have to specify the file path, like can read the whole file, line by line.
this: 1. f = open("test.txt", "r")
1. f = open("D:\\myfiles\welcome.txt", "r") 2. for x in f:
2. print(f.read()) 3. print(x)
• Read Only Parts of the File • Close Files
• By default, the read() method returns the • It is a good practice to always close the file
whole text, but you can also specify how when you are done with it.
many characters you want to return: 1. f = open("test.txt", "r")
• Ex: Return the 5 first characters of the file. 2. print(f.read())
1. f = open("test.txt", "r") 3. f.close()
2. print(f.read(5))
• Write to an Existing File
• Read Lines • To write to an existing file, you must add a
• You can return one line by using the parameter to the open() function:
readline() method. • "a" - Append - will append to the end of the
1. f = open("test.txt", "r") file.
2. print(f.readline()) • "w" - Write - will overwrite any existing
• By calling readline() two times, you can read content.
the two first lines. 1. f = open("test.txt", "a")
1. f = open("test.txt", "r") 2. f.write("Now the file has more content!")
2. print(f.readline()) 3. f.close()
3. print(f.readline()) 4. f = open("test.txt", "r")
5. print(f.read())
6. f.close()
79
• Open the file "demofile3.txt" and • Delete a File
overwrite the content. • To delete a file, you must import the OS
1. f = open("test.txt", "w") module, and run its os.remove() function.
2. f.write("overwriting the existing file") • Remove the file "demofile.txt“.
3. f.close() 1. import os
4. f = open("test.txt", "r") 2. os.remove("demofile.txt")
5. print(f.read())
• Check if File exist:
• Create a New File • To avoid getting an error, you might want to
• To create a new file in Python, use the check if the file exists before you try to delete
open() method, with one of the following it.
parameters: 1. import os
• "x" - Create - will create a file, returns an 2. if os.path.exists("demofile.txt"):
error if the file exist.
• "a" - Append - will create a file if the 3. os.remove("demofile.txt")
specified file does not exist. 4. else:
• "w" - Write - will create a file if the specified 5. print("The file does not exist")
file does not exist.
• Create a file called "myfile.txt“.
• Delete Folder
1. f = open("myfile.txt", "x") • To delete an entire folder, use the
• Result: a new empty file is created!
os.rmdir() method.
1. import os
• Create a new file if it does not exist. 2. os.rmdir("xyz")
1. f = open("myfile.txt", "w")
• Note: You can only remove empty folders.

80
• NumPy • Why is NumPy Faster Than Lists?
• NumPy is a Python library. • NumPy arrays are stored at one continuous place in
• NumPy is used for working with arrays. memory unlike lists, so processes can access and
manipulate them very efficiently.
• NumPy is short for "Numerical Python".
• This behavior is called locality of reference in computer
• What is NumPy? science.
• NumPy is a Python library used for working with arrays. • This is the main reason why NumPy is faster than lists.
• It also has functions for working in domain of linear Also, it is optimized to work with latest CPU
algebra, Fourier transform, and matrices. architectures.
• NumPy was created in 2005 by Travis Oliphant. It is an • Which Language is NumPy written in?
open-source project, and you can use it freely. • NumPy is a Python library and is written partially in
• NumPy stands for Numerical Python. Python, but most of the parts that require fast
computation are written in C or C++.
• Why Use NumPy?
• In Python we have lists that serve the purpose of arrays, • Installation of NumPy
but they are slow to process. • If you have Python and PIP already installed on a
• NumPy aims to provide an array object that is up to 50x system, then installation of NumPy is very easy.
faster than traditional Python lists. • Install it using this command:
• The array object in NumPy is called ndarray, it provides • C:\Users\Your Name>pip install numpy
a lot of supporting functions that make working with
ndarray very easy. • Import NumPy
• Arrays are very frequently used in data science, where • Once NumPy is installed, import it in your applications
speed and resources are very important. by adding the import keyword: import numpy
• Ex:
• Data Science: is a branch of computer science • import numpy
where we study how to store, use and analyze data • arr = numpy.array([1, 2, 3, 4, 5])
for deriving information from it. • Print(arr)
• print(type(arr))

81
• we can pass a list, tuple or any array-like object into the • 2-D Arrays
array() method, and it will be converted into a ndarray. • An array that has 1-D arrays as its elements is called a 2-D array.
• Use a tuple to create a NumPy array • These are often used to represent matrix or 2nd order tensors.
• import numpy as np • Ex:
• arr = np.array((1, 2, 3, 4, 5)) • import numpy as np
• arr = np.array([[1, 2, 3], [4, 5, 6]])
• print(arr)
• print(arr)
• Dimensions in Arrays • 3-D arrays
• 0-D Arrays • An array that has 2-D arrays (matrices) as its elements is called
• 0-D arrays, or Scalars, are the elements in an array. Each value 3-D array.
in an array is a 0-D array. • These are often used to represent a 3rd order tensor.
• Ex: Create a 0-D arrayimport numpy as np • Ex:
• arr = np.array(42) • import numpy as np
• print(arr) • arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
• with value 42 • print(arr)
• 1-D Arrays • Check Number of Dimensions?
• An array that has 0-D arrays as its elements is called uni- • NumPy Arrays provides the ndim attribute that returns an
dimensional or 1-D array. integer that tells us how many dimensions the array have.
• These are the most common and basic arrays. • Ex:
• Ex: • import numpy as np
• import numpy as np • a = np.array(42)
• arr = np.array([1, 2, 3, 4, 5]) • b = np.array([1, 2, 3, 4, 5])
• print(arr) • c = np.array([[1, 2, 3], [4, 5, 6]])
• d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
• print(a.ndim)
• print(b.ndim)
• print(c.ndim)
• print(d.ndim)

82
• Access Array Elements • Access 2-D Arrays
• Array indexing is the same as accessing • To access elements from 2-D arrays we
an array element. can use comma separated integers
• You can access an array element by representing the dimension and the
referring to its index number. index of the element.
• The indexes in NumPy arrays start with • Think of 2-D arrays like a table with
0, meaning that the first element has rows and columns, where the row
index 0, and the second has index 1 etc. represents the dimension, and the
• Ex: index represents the column.
• import numpy as np • Ex: Access the element on the first row,
• arr = np.array([1, 2, 3, 4]) second column.
• print(arr[0]) • import numpy as np
• arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
• Ex: Get third and fourth elements from
the following array and add them. • print('2nd element on 1st row: ', arr[0, 1])
• import numpy as np • Ex: Access the element on the 2nd row,
• arr = np.array([1, 2, 3, 4]) 5th column.
• print(arr[2] + arr[3]) • import numpy as np
• arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
• print('5th element on 2nd row: ', arr[1, 4])
83
• Access 3-D Arrays • Random Numbers in NumPy
• To access elements from 3-D arrays we can use • What is a Random Number?
comma separated integers representing the
dimensions and the index of the element. • Random number does NOT mean a different
• Ex: Access the third element of the second number every time. Random means something
array of the first array. that can not be predicted logically.
• import numpy as np • Generate Random Number
• arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, • NumPy offers the random module to work with
11, 12]]]) random numbers.
• print(arr[0, 1, 2])
• Ex: Generate a random integer from 0 to 100:
• from numpy import random
• x = random.randint(100)
• print(x)
• Generate Random Array
• In NumPy we work with arrays, and you can use
the two methods from the above examples to
make random arrays.
• Integers
• The randint() method takes a size parameter
where you can specify the shape of an array.
• Ex: Generate a 1-D array containing 5 random
integers from 0 to 100.
• from numpy import random
• x=random.randint(100, size=(5))
• print(x)
84
• Ex: Generate a 2-D array with 3 rows, • Generate Random Number From Array
each row containing 5 random integers • The choice() method allows you to
from 0 to 100. generate a random value based on an array
• from numpy import random of values.
• x = random.randint(100, size=(3, 5)) • The choice() method takes an array as a
parameter and randomly returns one of
• print(x) the values.
• Floats • Ex: Return one of the values in an array:
• The rand() method also allows you to • from numpy import random
specify the shape of the array. • x = random.choice([3, 5, 7, 9])
• Ex: Generate a 1-D array containing 5 • print(x)
random floats. • The choice() method also allows you to
• from numpy import random return an array of values.
• x = random.rand(5) • Add a size parameter to specify the shape
• print(x) of the array.
• Ex: Generate a 2-D array with 3 rows, • Ex: Generate a 2-D array that consists of
the values in the array parameter (3, 5, 7,
each row containing 5 random and 9):
numbers. • from numpy import random
• from numpy import random • x = random.choice([3, 5, 7, 9], size=(3, 5))
• x = random.rand(3, 5) • print(x)
• print(x) Output: [[9 3 5 5 7]
[7 5 3 3 9]
[7 5 9 9 7]] 85
• Random Data Distribution • Ex:
• What is Data Distribution? • Generate a 1-D array containing 100 values,
• Data Distribution is a list of all possible where each value must be 3, 5, 7 or 9.
values, and how often each value occurs. • The probability for the value to be 3 is set
• Such lists are important when working with to be 0.1.
statistics and data science. • The probability for the value to be 5 is set
• The random module offer methods that to be 0.3.
returns randomly generated data
distributions. • The probability for the value to be 7 is set
• Random Distribution to be 0.6.
• A random distribution is a set of random • The probability for the value to be 9 is set
numbers that follow a certain probability to be 0.
density function. • from numpy import random
• We can generate random numbers based on • x = random.choice([3, 5, 7, 9], p=[0.1, 0.3,
defined probabilities using the choice() 0.6, 0.0], size=(100))
method of the random module. • print(x)
• The choice() method allows us to specify the
probability for each value. • Output:
• The probability is set by a number between 0 • [7 7 7 7 7 5 7 7 5 5 7 7 7 7 7 7 7 7 5 5 5 7 7 5 7
and 1, where 0 means that the value will 5575535735557377775775757
never occur and 1 means that the value will 7777777777737773757575575
always occur. 5 7 7 7 7 5 7 7 5 7 7 7 5 5 7 7 7 7 7 7 5 7 7 5 3]
• Note: The sum of all probability numbers
should be 1. Even if you run the example
above 100 times, the value 9 will never
occur.
86
• You can return arrays of any shape and • Random Permutations
size by specifying the shape in the size • Random Permutations of Elements
parameter. • A permutation refers to an arrangement of
elements. e.g. [3, 2, 1] is a permutation of [1,
• Ex: Same example as above but return a 2, 3] and vice-versa.
2-D array with 3 rows, each containing 5 • The NumPy Random module provides two
values. methods for this: shuffle() and permutation().
• from numpy import random • Shuffling Arrays
• x = random.choice([3, 5, 7, 9], p=[0.1, 0.3, • Shuffle means changing arrangement of
elements in-place. i.e., in the array itself.
0.6, 0.0], size=(3, 5)) • The shuffle() method makes changes to the
• print(x) original array.
• Output: • Ex: Randomly shuffle elements of following
[[3 5 5 7 5] array:
• from numpy import random
[5 7 3 7 3] • import numpy as np
[7 3 7 7 7]] • arr = np.array([1, 2, 3, 4, 5])
• random.shuffle(arr)
• print(arr)
• random.shuffle(arr)
• print(arr)
• Output:
• [3 5 4 1 2]
• [4 1 3 2 5]

87
• Generating Permutation of Arrays • Seaborn
• Ex: Generate a random permutation of • Visualize Distributions With Seaborn
elements of following array: • Seaborn is a library that uses Matplotlib
• from numpy import random underneath to plot graphs.
• import numpy as np • It will be used to visualize random
• arr = np.array([1, 2, 3, 4, 5]) distributions.
• print(random.permutation(arr))
• print(random.permutation(arr))
• Output: • Install Seaborn.
• [3 4 1 2 5] • If you have Python and PIP already installed
on a system, install it using this command:
• [3 4 1 5 2] • pip install seaborn
• Note: The permutation() method returns a
re-arranged array (and leaves the original • Distplots
array un-changed). • Distplot stands for distribution plot, it takes
as input an array and plots a curve
corresponding to the distribution of points
in the array.
• Import Matplotlib
• Import the pyplot object of the Matplotlib
module in your code using the following
statement:
• import matplotlib.pyplot as plt
88
• Before going much deeper to Seaborn we will learn Matplotlib. • Pyplot
• Most of the Matplotlib utilities lies under the pyplot submodule,
and are usually imported under the plt alias:
• Matplotlib • import matplotlib.pyplot as plt

• What is Matplotlib? • Ex: Draw a line in a diagram from position (0,0) to position
• Matplotlib is a low-level graph plotting library in python that serves (6,250).
as a visualization utility. • import matplotlib.pyplot as plt
• Matplotlib was created by John D. Hunter. • import numpy as np
• Matplotlib is open source, and we can use it freely. • xpoints = np.array([0, 6])
• Matplotlib is mostly written in python, a few segments are written • ypoints = np.array([0, 250])
in C, Objective-C and JavaScript for Platform compatibility. • plt.plot(xpoints, ypoints)
• Installation of Matplotlib • plt.show()
• Install it using this command: • Plotting x and y points
• pip install matplotlib
• The plot() function is used to draw points (markers) in a diagram.
• Import Matplotlib • By default, the plot() function draws a line from point to point.
• Once Matplotlib is installed, import it in your applications by adding • The function takes parameters for specifying points in the diagram.
the import module statement.
• Parameter 1 is an array containing the points on the x-axis.
• import matplotlib
• Parameter 2 is an array containing the points on the y-axis.
• Checking Matplotlib Version
• If we need to plot a line from (1, 3) to (8, 10), we have to pass two
• The version string is stored under __version__ attribute.
arrays [1, 8] and [3, 10] to the plot function.
• Ex:
• import matplotlib
• print(matplotlib.__version__)
• Note: two underscore characters are used in __version__.

89
• Ex: Draw a line in a diagram from position (1, 3) • Multiple Points
to position (8, 10). • You can plot as many points as you like, just make
• import matplotlib.pyplot as plt sure you have the same number of points in both
• import numpy as np axis.
• xpoints = np.array([1, 8]) • Ex: Draw a line in a diagram from position (1, 3) to
(2, 8) then to (6, 1) and finally to position (8, 10).
• ypoints = np.array([3, 10]) • import matplotlib.pyplot as plt
• plt.plot(xpoints, ypoints) • import numpy as np
• plt.show() • xpoints = np.array([1, 2, 6, 8])
• Plotting Without Line • ypoints = np.array([3, 8, 1, 10])
• plt.plot(xpoints, ypoints)
• To plot only the markers, you can use shortcut • plt.show()
string notation parameter 'o', which means 'rings’.
• Ex: Draw two points in the diagram, one at • Default X-Points
position (1, 3) and one in position (8, 10). • If we do not specify the points in the x-axis, they
• import matplotlib.pyplot as plt will get the default values 0, 1, 2, 3, (etc.
• import numpy as np depending on the length of the y-points.
• xpoints = np.array([1, 8]) • So, if we take the same example as above, and
• ypoints = np.array([3, 10]) leave out the x-points, the diagram will look like
• plt.plot(xpoints, ypoints, 'o') this:
• plt.show() • Ex: Plotting without x-points.
• import matplotlib.pyplot as plt
• import numpy as np
• ypoints = np.array([3, 8, 1, 10, 5, 7])
• plt.plot(ypoints)
• plt.show()
• The x-points in the example above is [0, 1, 2, 3, 4,
5]. 90
• Markers • Format Strings fmt
• You can use the keyword argument marker to emphasize each point with • You can use also use the shortcut string notation parameter to specify
a specified marker. the marker.
• Ex: Mark each point with a circle. • This parameter is also called fmt, and is written with this syntax:
• import matplotlib.pyplot as plt • marker|line|color
• import numpy as np • Ex: Mark each point with a circle.
• ypoints = np.array([3, 8, 1, 10]) • import matplotlib.pyplot as plt
• plt.plot(ypoints, marker = 'o') • import numpy as np
• plt.show() • ypoints = np.array([3, 8, 1, 10])
• Ex: Mark each point with a star (*). • plt.plot(ypoints, 'o:r')
• plt.plot(ypoints, marker = '*') • plt.show()
• plt.plot(ypoints, marker = '|’) • The marker value can be anything from the Marker Reference above.
• plt.plot(ypoints, marker = '_’) • The line value (Line Reference) can be one of the following:
• plt.plot(ypoints, marker = '4’)(4=tri right) • plt.plot(ypoints, 'o-r’) (solid line)
• plt.plot(ypoints, marker = '3’) (3=tri left) • plt.plot(ypoints, 'o:’) (dotted line)
• plt.plot(ypoints, marker = '2’) (2=tri up) • plt.plot(ypoints, 'o--r’) (dashed line)
• plt.plot(ypoints, marker = ‘1’) (1=tri down) • plt.plot(ypoints, 'o-.’) (dashed dotted line)
• plt.plot(ypoints, marker = '>’) (Triangle right) • Note: If you leave out the line value in the fmt parameter, no line will be
• plt.plot(ypoints, marker = '<‘) (triangle left) plotted.
• plt.plot(ypoints, marker = '^’) (triangle up) • The short color value can be one of the following: r, g, b, c, m, y, k , w.
• plt.plot(ypoints, marker = 'v’) (triangle down)
• plt.plot(ypoints, marker = 'h’) (hexagon) • Marker Size
• plt.plot(ypoints, marker = 'p’) (pentagon) • You can use the keyword argument markersize or the shorter version, ms
• plt.plot(ypoints, marker = 'd’) (diamond thin) to set the size of the markers.
• plt.plot(ypoints, marker = 'D’) (diamond) • Ex: Set the size of the markers to 20.
• plt.plot(ypoints, marker = 's’) (square) • import matplotlib.pyplot as plt
• plt.plot(ypoints, marker = 'P’) (filled plus (+)) • import numpy as np
• plt.plot(ypoints, marker = '+’) (plus) • ypoints = np.array([3, 8, 1, 10])
• plt.plot(ypoints, marker = 'X’) (filled x) • plt.plot(ypoints, marker = 'o', ms = 20)
• plt.plot(ypoints, marker = 'x’) (x) • plt.show()
• plt.plot(ypoints, marker = ',’) (pixel (.))
• plt.plot(ypoints, marker = '.’) (point (.))

91
• Marker Color • Linestyle
• You can use the keyword argument • You can use the keyword argument linestyle, or
markeredgecolor or the shorter mec to set the shorter ls, to change the style of the plotted
color of the edge of the markers. line.
• Ex: Set the EDGE color to red. • Ex: Use a dotted line.
• import matplotlib.pyplot as plt • import matplotlib.pyplot as plt
• import numpy as np • import numpy as np
• ypoints = np.array([3, 8, 1, 10]) • ypoints = np.array([3, 8, 1, 10])
• plt.plot(ypoints, marker = 'o', ms = 20, mec = 'r') • plt.plot(ypoints, linestyle = 'dotted')
• plt.show() • plt.show()
• You can use the keyword argument • Ex: Use a dashed line.
markerfacecolor or the shorter mfc to set the • plt.plot(ypoints, linestyle = 'dashed’)
color inside the edge of the markers. • Shorter Syntax
• import matplotlib.pyplot as plt • The line style can be written in a shorter syntax:
• import numpy as np • linestyle can be written as ls.
• ypoints = np.array([3, 8, 1, 10]) • dotted can be written as :.
• plt.plot(ypoints, marker = 'o', ms = 20, mfc = 'r')
• dashed can be written as --.
• plt.show()
• Ex: Shorter syntax.
• Use both the mec and mfc arguments to color • plt.plot(ypoints, ls = ':’)
of the entire marker.
• plt.plot(ypoints, marker = 'o', ms = 20, mec = 'r', mfc = 'r’)
• You can also use Hexadecimal color values.
• plt.plot(ypoints, marker = 'o', ms = 20, mec = '#4CAF50', mfc =
'#4CAF50’)
• Or any of the 140 supported color names.
• plt.plot(ypoints, marker = 'o', ms = 20, mec = 'hotpink', mfc =
'hotpink')
92
• Line Color • Multiple Lines
• You can use the keyword argument color or the shorter c to set • You can plot as many lines as you like by simply adding more
the color of the line. plt.plot() functions.
• Ex: Set the line color to red. • Ex: Draw two lines by specifying a plt.plot() function for each
• import matplotlib.pyplot as plt line.
• import numpy as np • import matplotlib.pyplot as plt
• ypoints = np.array([3, 8, 1, 10]) • import numpy as np
• plt.plot(ypoints, color = 'r') • y1 = np.array([3, 8, 1, 10])
• plt.show() • y2 = np.array([6, 2, 7, 11])
• You can also use Hexadecimal color values. • plt.plot(y1)
• Ex: Plot with a green line. • plt.plot(y2)
• plt.plot(ypoints, c = '#4CAF50’) • plt.show()
• Or any of the 140 supported color names.
• Ex: • You can also plot many lines by adding the points for the x- and
• plt.plot(ypoints, c = 'hotpink’) y-axis for each line in the same plt.plot() function.
• Line Width • (In the examples above we only specified the points on the y-
axis, meaning that the points on the x-axis got the the default
• You can use the keyword argument linewidth or the shorter lw values (0, 1, 2, 3).)
to change the width of the line. • The x- and y- values come in pairs.
• The value is a floating number, in points • Ex: Draw two lines by specifiyng the x- and y-point values for
• Ex: Plot with a 20.5pt wide line. both lines.
• import matplotlib.pyplot as plt • import matplotlib.pyplot as plt
• import numpy as np • import numpy as np
• ypoints = np.array([3, 8, 1, 10]) • x1 = np.array([0, 1, 2, 3])
• plt.plot(ypoints, linewidth = '20.5') • y1 = np.array([3, 8, 1, 10])
• plt.show() • x2 = np.array([0, 1, 2, 3])
• y2 = np.array([6, 2, 7, 11])
• plt.plot(x1, y1, x2, y2)
• plt.show()

93
• Create Labels for a Plot • Set Font Properties for Title and Labels
• With Pyplot, you can use the xlabel() and • You can use the fontdict parameter in
ylabel() functions to set a label for the x- xlabel(), ylabel(), and title() to set font
and y-axis. properties for the title and labels.
• Ex: Add labels to the x- and y-axis. • Ex: Set font properties for the title and
• import numpy as np labels.
• import matplotlib.pyplot as plt • import numpy as np
• x = np.array([80, 85, 90, 95, 100, 105, 110, • import matplotlib.pyplot as plt
115, 120, 125]) • x = np.array([80, 85, 90, 95, 100, 105, 110,
• y = np.array([240, 250, 260, 270, 280, 290, 115, 120, 125])
300, 310, 320, 330]) • y = np.array([240, 250, 260, 270, 280, 290,
• plt.plot(x, y) 300, 310, 320, 330])
• plt.xlabel("Average Pulse") • font1 = {'family':'serif','color':'blue','size':20}
• plt.ylabel("Calorie Burnage") • font2 =
• plt.show() {'family':'serif','color':'darkred','size':15}
• plt.title("Sports Watch Data", fontdict =
• Create a Title for a Plot font1)
• With Pyplot, you can use the title() • plt.xlabel("Average Pulse", fontdict = font2)
function to set a title for the plot. • plt.ylabel("Calorie Burnage", fontdict = font2)
• plt.title("Sports Watch Data") • plt.plot(x, y)
• plt.xlabel("Average Pulse") • plt.show()
• plt.ylabel("Calorie Burnage")
94
• Position the Title • Specify Which Grid Lines to Display
• You can use the loc parameter in title() to • You can use the axis parameter in the grid()
position the title. function to specify which grid lines to
• Legal values are: 'left', 'right', and 'center'. display.
Default value is 'center’. • Legal values are: 'x', 'y', and 'both'. Default
• Ex: Position the title to the left. value is 'both’.
• plt.title("Sports Watch Data", loc = 'left’) • Ex: Display only grid lines for the x-axis.
• import numpy as np
• Add Grid Lines to a Plot • import matplotlib.pyplot as plt
• With Pyplot, you can use the grid() function • x = np.array([80, 85, 90, 95, 100, 105, 110,
to add grid lines to the plot. 115, 120, 125])
• Ex: Add grid lines to the plot. • y = np.array([240, 250, 260, 270, 280, 290,
• import numpy as np 300, 310, 320, 330])
• import matplotlib.pyplot as plt • plt.title("Sports Watch Data")
• x = np.array([80, 85, 90, 95, 100, 105, 110, • plt.xlabel("Average Pulse")
115, 120, 125]) • plt.ylabel("Calorie Burnage")
• y = np.array([240, 250, 260, 270, 280, 290, • plt.plot(x, y)
300, 310, 320, 330]) • plt.grid(axis = 'x’) or plt.grid(axis = 'y')
• plt.title("Sports Watch Data") • plt.show()
• plt.xlabel("Average Pulse")
• plt.ylabel("Calorie Burnage")
• plt.plot(x, y)
• plt.grid()
• plt.show()
95
• Set Line Properties for the Grid • Ex: Draw 2 plots.
• You can also set the line properties of the • import matplotlib.pyplot as plt
grid, like this: grid(color = 'color', linestyle = • import numpy as np
'linestyle', linewidth = number). • #plot 1:
• Ex: Set the line properties of the grid. • x = np.array([0, 1, 2, 3])
• plt.grid(color = 'green', linestyle = '--',
linewidth = 0.5) • y = np.array([3, 8, 1, 10])
• plt.subplot(1, 2, 1)
• Display Multiple Plots • plt.plot(x,y)
• With the subplot() function you can draw • #plot 2:
multiple plots in one figure. • x = np.array([0, 1, 2, 3])
• The subplot() Function • y = np.array([10, 20, 30, 40])
• The subplot() function takes three arguments • plt.subplot(1, 2, 2)
that describes the layout of the figure. • plt.plot(x,y)
• The layout is organized in rows and columns, • plt.show()
which are represented by the first and
second argument.
• The third argument represents the index of
the current plot.
• plt.subplot(1, 2, 1)
• #the figure has 1 row, 2 columns, and this
plot is the first plot.
• plt.subplot(1, 2, 2)
• #the figure has 1 row, 2 columns, and this
plot is the second plot.
96
• So, if we want a figure with 2 rows a 1 • Title
column (meaning that the two plots will be • You can add a title to each plot with the title()
displayed on top of each other instead of function.
side-by-side), we can write the syntax like • import matplotlib.pyplot as plt
this: • import numpy as np
• #plot 1:
• Ex: Draw 2 plots on top of each other • x = np.array([0, 1, 2, 3])
• import matplotlib.pyplot as plt • y = np.array([3, 8, 1, 10])
• import numpy as np • plt.subplot(1, 2, 1)
• #plot 1: • plt.plot(x,y)
• x = np.array([0, 1, 2, 3]) • plt.title("SALES")
• y = np.array([3, 8, 1, 10]) • #plot 2:
• x = np.array([0, 1, 2, 3])
• plt.subplot(2, 1, 1) • y = np.array([10, 20, 30, 40])
• plt.plot(x,y) • plt.subplot(1, 2, 2)
• #plot 2: • plt.plot(x,y)
• x = np.array([0, 1, 2, 3]) • plt.title("INCOME")
• y = np.array([10, 20, 30, 40]) • plt.show()
• plt.subplot(2, 1, 2)
• plt.plot(x,y)
• plt.show()
• You can draw as many plots you like on one
figure, just descibe the number of rows,
columns, and the index of the plot.
97
• Super Title • Creating Scatter Plots
• You can add a title to the entire figure with • With Pyplot, you can use the scatter()
the suptitle() function. function to draw a scatter plot.
• Ex: Add a title for the entire figure. • The scatter() function plots one dot for
• import matplotlib.pyplot as plt each observation. It needs two arrays of
• import numpy as np the same length, one for the values of the
• #plot 1: x-axis, and one for values on the y-axis.
• x = np.array([0, 1, 2, 3]) • Ex: A simple scatter plot.
• y = np.array([3, 8, 1, 10]) • import matplotlib.pyplot as plt
• plt.subplot(1, 2, 1) • import numpy as np
• plt.plot(x,y) • x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
• plt.title("SALES") • y=np.array([99,86,87,88,111,86,103,87,94,78
• #plot 2: ,77,85,86])
• x = np.array([0, 1, 2, 3]) • plt.scatter(x, y)
• y = np.array([10, 20, 30, 40]) • plt.show()
• plt.subplot(1, 2, 2)
• plt.plot(x,y)
• plt.title("INCOME")
• plt.suptitle("MY SHOP")
• plt.show()

98
• Compare Plots • Colors
• Ex: Draw two plots on the same figure: • You can set your own color for each
• import matplotlib.pyplot as plt scatter plot with the color or the c
• import numpy as np argument.
• #day one, the age and speed of 13 cars: • Ex: Set your own color of the markers:
• x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6]) • import matplotlib.pyplot as plt
• y =np.array([99,86,87,88,111,86,103,87,94,78,77,85,86]) • import numpy as np
• plt.scatter(x, y) • x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
• #day two, the age and speed of 15 cars: • y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
• x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12]) • plt.scatter(x, y, color = 'hotpink')
• y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
• x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
• plt.scatter(x, y) • y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
• plt.show() • plt.scatter(x, y, color = '#88c999')
• plt.show()

• Note: The two plots are plotted with two


different colors, by default blue and
orange,

99
• Color Each Dot • ColorMap
• You can even set a specific color for • The Matplotlib module has a number of
each dot by using an array of colors as available colormaps.
value for the c argument. • A colormap is like a list of colors, where
• Note: You cannot use the color each color has a value that ranges from
argument for this, only the c argument. 0 to 100.
• Ex: Set your own color of the markers: • Here is an example of a colormap:
• import matplotlib.pyplot as plt • This colormap is called 'viridis' and as
• import numpy as np you can see it ranges from 0, which is a
• x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6]) purple color, and up to 100, which is a
• y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86]) yellow color.
• colors = • How to Use the ColorMap
np.array(["red","green","blue","yellow","pink","black"
,"orange","purple","beige","brown","gray","cyan","m • You can specify the colormap with the
agenta"]) keyword argument cmap with the value of
• plt.scatter(x, y, c=colors) the colormap, in this case 'viridis' which is
• plt.show() one of the built-in colormaps available in
Matplotlib.
• In addition, you must create an array with
values (from 0 to 100), one value for each
of the point in the scatter plot:
100
• Ex: Create a color array, and specify a • You can include the colormap in the
colormap in the scatter plot: drawing by including the
• import matplotlib.pyplot as plt plt.colorbar() statement:
• import numpy as np • Ex:Include the actual colormap:
• x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
• y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
• import matplotlib.pyplot as plt
• colors = np.array([0, 10, 20, 30, 40, 45, • import numpy as np
• x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
50, 55, 60, 70, 80, 90, 100]) • y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
• plt.scatter(x, y, c=colors, cmap='viridis') • colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80,
90, 100])
• plt.show()
• plt.scatter(x, y, c=colors, cmap='viridis')
• plt.colorbar()
• plt.show()

101
• Size • Alpha
• You can change the size of the dots • You can adjust the transparency of the
with the s argument. dots with the alpha argument.
• Just like colors, make sure the array for • Just like colors, make sure the array for
sizes has the same length as the arrays sizes has the same length as the arrays
for the x- and y-axis: for the x- and y-axis:
• Ex: Set your own size for the markers: • Ex: Set your own size for the markers:
• import matplotlib.pyplot as plt • import matplotlib.pyplot as plt
• import numpy as np • import numpy as np
• x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6]) • x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
• y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86]) • y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
• sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75]) • sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])

• plt.scatter(x, y, s=sizes) • plt.scatter(x, y, s=sizes, alpha=0.5)


• plt.show() • plt.show()

102
• Combine Color Size and Alpha • Creating Bars
• You can combine a colormap with • With Pyplot, you can use the bar()
different sizes on the dots. This is best function to draw bar graphs:
visualized if the dots are transparent: • Ex: Draw 4 bars:
• Ex: Create random arrays with 100 • import matplotlib.pyplot as plt
values for x-points, y-points, colors and • import numpy as np
sizes: • x = np.array(["A", "B", "C", "D"])
• import matplotlib.pyplot as plt • y = np.array([3, 8, 1, 10])
• import numpy as np • plt.bar(x,y)
• x = np.random.randint(100, size=(100)) • plt.show()
• y = np.random.randint(100, size=(100))
• colors = np.random.randint(100, size=(100))
• sizes = 10 * np.random.randint(100, size=(100))
• plt.scatter(x, y, c=colors, s=sizes, alpha=0.5,
cmap='nipy_spectral')
• plt.colorbar()
• plt.show()

103
• Horizontal Bars • Bar Color
• If you want the bars to be displayed • The bar() and barh() takes the keyword
horizontally instead of vertically, use argument color to set the color of the
the barh() function: bars:
• Ex: Draw 4 horizontal bars: • Ex: Draw 4 red bars:
• import matplotlib.pyplot as plt • import matplotlib.pyplot as plt
• import numpy as np • import numpy as np
• x = np.array(["A", "B", "C", "D"]) • x = np.array(["A", "B", "C", "D"])
• y = np.array([3, 8, 1, 10]) • y = np.array([3, 8, 1, 10])
• plt.barh(x, y) • plt.bar(x, y, color = "red")
• plt.show() • plt.show()

104
• Bar Width • Histogram
• The bar() takes the keyword argument • A histogram is a graph showing frequency
width to set the width of the bars: distributions.
• Ex:Draw 4 very thin bars: • It is a graph showing the number of
• import matplotlib.pyplot as plt observations within each given interval.
• import numpy as np
• x = np.array(["A", "B", "C", "D"])
• y = np.array([3, 8, 1, 10])
• plt.bar(x, y, width = 0.1)
• Create Histogram
• plt.show() • In Matplotlib, we use the hist() function to
• Note: For horizontal bars, use height create histograms.
instead of width. • The hist() function will use an array of
numbers to create a histogram, the array is
• Bar Height sent into the function as an argument.
• The barh() takes the keyword argument • Ex: For simplicity we use NumPy to
height to set the height of the bars: randomly generate an array with 250
• import matplotlib.pyplot as plt values, where the values will concentrate
• import numpy as np around 170, and the standard deviation is
• x = np.array(["A", "B", "C", "D"]) 10.
• y = np.array([3, 8, 1, 10]) • import numpy as np
• plt.barh(x, y, height = 0.1) • x = np.random.normal(170, 10, 250)
• plt.show() • print(x) 105
• Ex: A simple histogram. • As you can see the pie chart draws one
• import matplotlib.pyplot as plt piece (called a wedge) for each value in
the array (in this case [35, 25, 25, 15]).
• import numpy as np
• By default, the plotting of the first
• x = np.random.normal(170, 10, 250) wedge starts from the x-axis and move
• plt.hist(x) counterclockwise:
• plt.show()
• Labels
• Add labels to the pie chart with the
• Creating Pie Charts label parameter.
• With Pyplot, you can use the pie() • The label parameter must be an array
function to draw pie charts. with one label for each wedge.
• Ex: A simple pie chart. • Ex:
• import matplotlib.pyplot as plt • import matplotlib.pyplot as plt
• import numpy as np • import numpy as np
• y = np.array([35, 25, 25, 15]) • y = np.array([35, 25, 25, 15])
• plt.pie(y) • mylabels = ["Apples", "Bananas",
• plt.show() "Cherries", "Dates"]
• plt.pie(y, labels = mylabels)
• plt.show()
106
• Start Angle • Explode
• As mentioned, the default start angle is • Maybe you want one of the wedges to
at the x-axis, but you can change the stand out? The explode parameter
start angle by specifying a startangle allows you to do that.
parameter. • The explode parameter, if specified,
• The startangle parameter is defined and not None, must be an array with
with an angle in degrees, default angle one value for each wedge.
is 0. • Each value represents how far from the
center each wedge is displayed.
• Ex: Start the first wedge at 90 degrees. • Ex: Pull the "Apples" wedge 0.2 from
• import matplotlib.pyplot as plt the center of the pie.
• import numpy as np • import matplotlib.pyplot as plt
• y = np.array([35, 25, 25, 15]) • import numpy as np
• mylabels = ["Apples", "Bananas", • y = np.array([35, 25, 25, 15])
"Cherries", "Dates"] • mylabels = ["Apples", "Bananas",
• plt.pie(y, labels = mylabels, startangle = 90) "Cherries", "Dates"]
• plt.show() • myexplode = [0.2, 0, 0, 0]
• plt.pie(y, labels = mylabels, explode =
myexplode)
• plt.show()
107
• Shadow • Colors
• Add a shadow to the pie chart by • You can set the color of each wedge
setting the shadows parameter to True: with the colors parameter.
• Ex: Add a shadow: • The colors parameter, if specified, must
• import matplotlib.pyplot as plt be an array with one value for each
• import numpy as np wedge.
• y = np.array([35, 25, 25, 15]) • Ex: Specify a new color for each wedge:
• mylabels = ["Apples", "Bananas", • import matplotlib.pyplot as plt
"Cherries", "Dates"] • import numpy as np
• myexplode = [0.2, 0, 0, 0] • y = np.array([35, 25, 25, 15])
• plt.pie(y, labels = mylabels, explode = • mylabels = ["Apples", "Bananas",
myexplode, shadow = True) "Cherries", "Dates"]
• plt.show() • mycolors = ["black", "hotpink", "b",
"#4CAF50"]
• plt.pie(y, labels = mylabels, colors =
mycolors)
• plt.show()

108
• Legend • Now, we are coming back to seaborn.
• To add a list of explanation for each wedge, • Import Seaborn
use the legend() function.
• Ex: Add a legend: • Import the Seaborn module in your code
using the following statement:
• import matplotlib.pyplot as plt
• import numpy as np
• import seaborn as sns
• y = np.array([35, 25, 25, 15]) • Plotting a Distplot
• mylabels = ["Apples", "Bananas", "Cherries", • Ex: plotting a distplot with histogram
"Dates"] • import matplotlib.pyplot as plt
• plt.pie(y, labels = mylabels) • import seaborn as sns
• plt.legend() • sns.distplot([0, 1, 2, 3, 4, 5])
• plt.show() • plt.show()
• Legend With Header
• To add a header to the legend, add the title • Plotting a Distplot Without the
parameter to the legend function. Histogram
• Ex: Add a legend with a header. • Ex:
• import matplotlib.pyplot as plt • import matplotlib.pyplot as plt
• import numpy as np • import seaborn as sns
• y = np.array([35, 25, 25, 15])
• sns.distplot([0, 1, 2, 3, 4, 5], hist=False)
• mylabels = ["Apples", "Bananas", "Cherries",
"Dates"] • plt.show()
• plt.pie(y, labels = mylabels)
• plt.legend(title = "Four Fruits:")
• plt.show()
109
• Python Programs • Program 2: Program 25:Check for
• Program 1: Swapping 2 No’s URL in a String (www.urlregex.com)
1. n1=10
2. n2=20
3. print("value of n1 before swap:",n1)
4. print("value of n2 before swap:",n2)
5. temp=n1
6. n1=n2
7. n2=temp
8. print("value of n1 after swap:",n1)
9. print("value of n2 after swap:",n2)
or
1. n1=input("Enter n1 value:")
2. n2=input("Enter n2 value:")
3. print("value of n1 before swap:",n1)
4. print("value of n2 before swap:",n2)
5. N1,n2=n2,n1
6. print("value of n1 after swap:",n1)
7. print("value of n2 after swap:",n2) 110
111
112
• Creating single dimensional array • Initializing numpy array with same number
• import numpy as np • n1=np.full((2,2),10)
• n1=np.array([10,20,30,40]) • n1
• n1 • Output: array([[10, 10],
• To know the type use type() function like • [10, 10]])
below: • Initializing numpy array within a range
• Type(n1) • n1=np.arange(1,11)
• Output: numpy.ndarray • N1
• Creating multidimensional array • Output: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
• n2=np.array([[10,20,30,40],[50,60,70,80]])
• N2 • Ex: 100 to 300 with increment 50
• Output: array([[10, 20, 30, 40], • n1=np.arange(100,300,50)
• [50, 60, 70, 80]]) • N1
• Output: array([100, 150, 200, 250])
• Initializing NumPy array with zeros (0’s)
• n1=np.zeros((1,2)) • Initializing numpy array with random numbers
• n1 • Ex: need 10 random numbers from 100 to 200
• Output: array([[0., 0.]]) • n1=np.random.randint(100,200,10)
• N1
• n1=np.zeros((2,2)) • Output: array([156, 187, 127, 183, 144, 154, 102,
187, 137, 139])
• N1
• Output: array([[0., 0.],
• [0., 0.]])
113
• Checking the shape of the numpy arrays • Addition of NumPy arrays
• Means it will tell you how many rows and • Sum() method is used to sum all the elements
columns available in an array. of an array.
• Ex: • Ex:
• n1=np.array([[1,2,3,4],[5,6,7,8]]) • n1=np.array([10,20])
• n1 • n2=np.array([30,40])
• Output: array([ [1, 2, 3, 4], • np.sum([n1,n2])
• [5, 6, 7, 8]]) • Output: 100 (in this case it sums all the elements
• Ex: of the both arrays)
• n1=np.array([[1,2,3,4],[5,6,7,8]]) • If you want to sum all column values of the
• n1.shape arrays, use the following way:
• Output: (2, 4)→ 2 rows and 4 columns • Ex:
• If you want the above array to be convert as 4 • n1=np.array([10,20])
rows and 2 columns, use the following • n2=np.array([30,40])
method: • np.sum([n1,n2],axis=0)
• Ex: • Output: array([40, 60])
• n1=np.array([[1,2,3,4],[5,6,7,8]]) • If you want to sum all row values of the arrays,
• n1.shape=(4,2) use the following way:
• n1 • Ex:
• Output: array([ [1, 2], • n1=np.array([10,20])
• [3, 4], • n2=np.array([30,40])
• [5, 6], • np.sum([n1,n2],axis=1)
• [7, 8]]) • Output: array([30, 70])
114
• Joining NumPy arrays • Pandas
• We have 3 types of joining’s: • It is used for data manipulations and analysis.
• Vstack() • It consists of single and multidimensional data
• Hstack() structures for manipulation.
• Column_stack() • Single dimensional are series objects.
• Ex: • Multi dimensional are data frames.
• n1=np.array([10,20,30,40]) • If you want to work with pandas, you need to
• n2=np.array([50,60,70,80]) import a package “pandas” like “import pandas
• np.vstack((n1,n2)) as pd”
• Output: array([[10, 20, 30, 40], • If pandas are not installed, go to the anaconda
• [50, 60, 70, 80]]) prompt and type “pip install pandas”.
• Ex: • Single dimensional / series object
• n1=np.array([10,20,30,40])
• n2=np.array([50,60,70,80])
• Ex:
• np.hstack((n1,n2)) • import pandas as pd
• Output: array([10, 20, 30, 40, 50, 60, 70, 80]) • s1=pd.Series([10,20,30,40,50])
• S1
• Ex: • Output:Label/Index Value
• n1=np.array([10,20,30,40]) • 0 10
• n2=np.array([50,60,70,80]) • 1 20
• np.column_stack((n1,n2)) • 2 30
• Output: array([ [10, 50], • 3 40
• [20, 60], • 4 50
• [30, 70], • dtype: int64
• [40, 80]])
115
• If you want to change the index values • Pandas' data frames
like a,b,c instead of o,1,2 • It is a 2-dimensional data structure.
• Ex: • Ex:
• import pandas as pd • df1=pd.DataFrame({"Name":["Mohammad","
• s1=pd.Series([10,20,30], index=['a','b','c']) Gouse","Galety"],"Course":["B.Sc","M.Sc","Ph.
• S1 D"]})
• Output: • df1
• a 10 • Output:
• b 20 • Name Course
• c 30 • 0 Mohammad B.Sc
• dtype: int64 • 1 Gouse M.Sc
• 2 Galety Ph.D
• Series object from dictionary • Data Frame inbuilt functions
• In this, keys will become index values.
• Ex: • Shape(), describe(), head(), tail()
• import pandas as pd • If you want to work with the above
functions, you need some data frames/.csv
• s1=pd.Series({'k1':10,'k2':20,'k3':30}) files.
• S1
• Output:
• k1 10
• k2 20
• k3 30
• dtype: int64

116
• How to load “.csv” file? • If you don’t have a file in your
• Ex: system, if it is in online, use the
• import pandas as pd following way to work:
• pd.read_csv('d:\Courses\Python\currency.c • from urllib.request Import urlretrieve
sv’)
• Output:
• import pandas as pd
• iris=‘url path’
• urlretrieve(iris)
• df=pd.read_csv(iris,sep=‘,’)
• df
• Head()
• If you want to show only top 5 records
of the data frame use head() method.
• import pandas as pd
• df=pd.read_csv('d:\Courses\Python\curren
cy.csv')
• df
• df.head()
• Output:
117
• If you want to show to 10 records • If you want to show your desired no. of
• import pandas as pd records pass that no. inside the tail()
• df=pd.read_csv('d:\Courses\Python\currenc method, like, tail(50).
y.csv') • Describe()
• df
• This method describe the entire data frame
• df.head(10) in terms of count(), mean(), std(), min()
• Output: 25%, 50%, 75%, and max().
• If you want to show your desired no. of • import pandas as pd
records pass that no. inside the head() • df=pd.read_csv('d:\Courses\Python\covid-
method, like, head(50). vaccination-vs-death_ratio.csv')
• df.describe()
• Tail() • Output:
• If you want to show only bottom 5 records
of the data frame use tail() method.
• import pandas as pd
• df=pd.read_csv('d:\Courses\Python\currenc
y.csv')
• df
• df.tail()
• Output:
118
• How to access individual row & cols • To extract only 10-20 records
from data frame and desired columns which
• To access rows and cols from the data are not in order:
frame use iloc() and loc() methods. • import pandas as pd
• import pandas as pd • df=pd.read_csv('d:\Courses\Py
• df=pd.read_csv('d:\Courses\Python\covid- thon\covid-vaccination-vs-
vaccination-vs-death_ratio.csv') death_ratio.csv')
• df.iloc[0:3,0:2] • df1=df.iloc[10:21,[0,4]]
• Output: • df1
• Output:
• For example, to extract only 99-127
records and 2 to 4th columns of the data
frame.
• import pandas as pd
• df=pd.read_csv('d:\Courses\Python\covid-
vaccination-vs-death_ratio.csv')
• df1=df.iloc[99:127,2:4]
• df1
• Output: check right slide→
119
• To extract desired rows/records and • To extract records, who’s
columns you can use loc() method “people_fully_vaccinated” < 200000.
also. • import pandas as pd
• import pandas as pd • df=pd.read_csv('d:\Courses\Python\co
• df=pd.read_csv('d:\Courses\Python\co vid-vaccination-vs-death_ratio.csv')
vid-vaccination-vs-death_ratio.csv') • df1=df[df["people_fully_vaccinated"]<
• df1=df.loc[10:15,("country","people_fu 200000]
lly_vaccinated")] • df1
• df1 • Output:
• Output:

• Note: in loc() method we are using


column names instead of index values.
• To extract records with multiple
conditions, use “&” and operator.
120
• Data Visualization • How to add x, y axis labels & titles
• Matplotlib is a python library used for • from matplotlib import pyplot as plt
data visualization. • import numpy as np
• You can create bar plots, scatter plots, • x=np.arange(1,11)
histograms. • y=2*x
• In this case, try to import pyplot library • plt.title("Line Plot")
from matplotlib like below:
• from matplotlib import pyplot as plt
• plt.xlabel("X-Axis")
• import numpy as np • plt.ylabel("Y-Axis")
• Ex: • plt.plot(x,y)
• from matplotlib import pyplot as plt • plt.show()
• import numpy as np • Output:
• x=np.arange(1,11)
• y=2*x
• print(x)
• print(y)
• plt.plot(x,y)
• plt.show()
• Output:
121

You might also like