0% found this document useful (0 votes)
89 views137 pages

Python Programming Basics Tutorial

This document provides a comprehensive tutorial on Python, covering its history, installation, basic syntax, and various programming concepts such as variables, data types, operators, control flow, and functions. It includes examples of how to use Python for web development, data science, and more, along with detailed explanations of string manipulation, collections, and the use of loops. The tutorial is designed for beginners to understand the fundamentals of Python programming.

Uploaded by

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

Python Programming Basics Tutorial

This document provides a comprehensive tutorial on Python, covering its history, installation, basic syntax, and various programming concepts such as variables, data types, operators, control flow, and functions. It includes examples of how to use Python for web development, data science, and more, along with detailed explanations of string manipulation, collections, and the use of loops. The tutorial is designed for beginners to understand the fundamentals of Python programming.

Uploaded by

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

Hands-on

Tutorial
● History
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991. It is a Interpreter language which runs line by line.

It is used for:

● web development (server-side),


● software development,
● mathematics,
● system scripting.
● Data Science

What can Python do?

● Python can be used on a server to create web applications.


● Python can be used alongside software to create workflows.
● Python can connect to database systems. It can also read and modify files.
● Python can be used to handle big data and perform complex mathematics.
● Python can be used for rapid prototyping, or for production-ready software development.
● Installation
1. winget search python

2. winget install (python 3.10 or package id)

3. successful installation

1. sudo apt update

2. sudo apt install python3

3. successful Installation

1. /bin/bash -c "$(curl -fsSL


[Link]

2. brew install python

3. python3 --version
● Basic Syntax
Printing Hello World :
Python syntax can be executed by writing directly in the Command Line.

Or by creating a python file on the server, using the .py file extension, and running it in the Command Line:
● Comments

Single line Comment

#This is a comment
print("Hello, World!")

Multi-line Comment

#This is a comment
#written in
#more than just one line
print("Hello, World!")
● Variables
Variables are containers for storing data values. Python has no command for
declaring a variable. A variable is created the moment you first assign a value
to it.

Example 1 :
x = 5
y = "John"
print(x)
print(y)

Example 2 :
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
● Casting & Types
Casting : If you want to specify the data type of a variable, this can be done with
casting.

x = str(3) # x will be '3'


y = int(3) # y will be 3
z = float(3) # z will be 3.0

Types : You can get the data type of a variable with the type() function.

x = 5
y = "John"
print(type(x))
print(type(y))
●Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).

Rules for Python variables:

● A variable name must start with a letter or the underscore character


● A variable name cannot start with a number
● A variable name can only contain alphanumeric characters and underscores (A-z, 0-9, and _ )
● Variable names are case-sensitive (age, Age and AGE are three different variables)
● A variable name cannot be any of the Python keywords.

Legal Variable Names:


●Assign Multiple
Values
Python allows you to assign values to multiple variables in one line:

List Values Assignment


●Data Types
In programming, data type is an important concept. Variables can store data of different types, and
different types can do different things. Python has the following data types built-in by default, in these
categories:

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set
Boolean Type: bool, etc.

Example:
x = input(“Enter a value:”);
print(type(x));
●Numbers
There are three numeric types in Python:

● int
● float
● complex

Example: Now, let’s take an example for assign all three variables and check the types.

x = 1 # int
y = 2.8 # float
z = 1j # complex

print(type(x))
print(type(y))
print(type(z))
Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the
same as "hello". You can display a string literal with the print() function:

print("Hello")

print('Hello')

Multiline Strings : You can assign a multiline string to a variable by using three quotes.
Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the
same as "hello". You can display a string literal with the print() function:

print("Hello")

print('Hello')

Multiline Strings : You can assign a multiline string to a variable by using three quotes.
Strings
Strings Are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode
characters. However, Python does not have a character data type, a single character is simply a string with a
length of 1. Square brackets can be used to access elements of the string.

Example : Get the character at position 1 (remember that the first character has the position 0).

Example : Loop through the letters in the word "banana".


Strings
Strings Length : To get the length of a string, use the len() function.

Example:

a = "Hello, World!"

print(len(a))

Check Stings : To check if a certain phrase or character is present in a string, we can use the keyword
in.

Example:

txt = "The best things in life are free!"

print("free" in txt)
Strings
Check If NOT : To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.

Example:

txt = "The best things in life are free!"

print("expensive" not in txt)

Slicing in Python
You can return a range of characters by using the slice syntax. Specify the start index and the end index,
separated by a colon, to return a part of the string.

Example:

b = "Hello, World!"

print(b[2:5])
Strings
String Modification: Python has a set of built-in methods that you can use on strings.
1. Uppercase: The upper() method returns the string in upper case.

a = "Hello, World!"

print([Link]())

2. Lowercase: The lower() method returns the string in lower case.

a = "Hello, World!"

print([Link]())

3. Strip: The strip() method removes any whitespace from the beginning or the end.

a = " Hello, World! "

print([Link]()) # returns "Hello, World!"


Strings
String Modification: Python has a set of built-in methods that you can use on strings.
1. Replace: The replace() method replaces a string with another string.
a = "Hello, World!"
print([Link]("H", "J"))
2. Split: The split() method returns a list where the text between the specified separator
becomes the list items.
a = "Hello, World!"
print([Link](","))
Strings
String Concatenation: To concatenate, or combine, two strings you can use the + operator.

a = "Hello"

b = "World"

c=a+b

print(c)

To add a space between them, add a " ":

a = "Hello"

b = "World"

c=a+""+b

print(c)
Strings
String Formatting: As we learned in the Python Variables chapter, we cannot combine strings and
numbers like this.

Example:
age = 36
txt = "My name is John, I am " + age
print(txt)

F-Strings: F-String was introduced in Python 3.6, and is now the preferred way of formatting [Link]
specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as
placeholders for variables and other operations.

Example:

age = 36
txt = f"My name is John, I am {age}"
print(txt)
Strings
String Methods:
capitalize(): Converts the first character to uppercase.
casefold(): Converts string into lowercase.
count(): Returns the number of times a specified value occurs in a string.
find(): Searches the string for a specified value and returns the position of where it was found.
index(): Searches the string for a specified value and returns the position of where it was found.
isalnum(): Returns True if all characters in the string are alphanumeric.
upper(): Converts a string into upper case.
lower(): Converts a string into lower case.
split(): Splits the string at the specified separator, and returns a list.
strip(): Returns a trimmed version of the string.
replace(): Returns a string where a specified value is replaced with a specified value.
join(): Joins the elements of an iterable to the end of the string.
swapcase(): Swaps cases, lower case becomes upper case and vice versa.
Booleans
In python programming you often need to know if an expression is True or False. You can
evaluate any expression in Python, and get one of two answers, True or False. The bool()
function allows you to evaluate any value, and give you True or False in return.

print(10 > 9);

print(10 == 9);

print(10 < 9);

print(bool("Hello"));

print(bool(15));

print((bool(15<9));
Operators
Operators are used to perform operations on variables and values. In the example below, we
use the + operator to add together two values:

print(10 + 5)

Python divides the operators in the following groups:

● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Identity operators
● Membership operators
● Bitwise operators
Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
Assignment
Assignment operators are used to assign values to variables:

Operators
Comparison
Operators
Comparison operators are used to compare two values:
Logical Operators
Logical operators are used to combine conditional statements:
Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same
object, with the same memory location:
Membership
Operators
Membership operators are used to test if a sequence is presented in an object:
Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Python If ... Else
Syntax
Shorthand If: If you have only one statement to execute,
if condition: you can put it on the same line as the if statement.
# code block if condition is True if a > b: print("a is greater than b")
elif another_condition:
# code block if this condition is True Shorthand If…Else:
else: a = 2
# code block if none of the above are True b = 330
c= 4
Example: print("A") if a > b else print("B")
x = 10
if x > 0: AND, OR, NOT keyword:
print("Positive") if a > b and c > a:
elif x == 0: print("Both conditions are True")
print("Zero") if a > b or a > c:
else: print("At least one of the conditions is True")
print("Negative") if not a > b:
print("a is NOT greater than b")
Python Match
The match statement is used to perform different Example:
actions based on different conditions. Instead of day = input(“Enter day (1-7):”);
writing many if..else statements, you can use the
match statement. match day:
case 1:
The match statement selects one of many code print("Monday")
blocks to be executed. case 2:
print("Tuesday")
Syntax:
case 3:
match expression:
print("Wednesday")
case x:
case 4:
code block
print("Thursday")
case y:
case 5:
code block
print("Friday")
case z: case 6:
code block print("Saturday")
case 7:
print("Sunday")
While loop
Python has two primitive loop commands: Break Statement Example:
i = 1
● while loops while i < 6:
● for loops print(i)
if i == 3:
With the while loop we can execute a set of break
statements as long as a condition is true.
i += 1
Example: continue Statement: With the continue statement
we can stop the current iteration, and continue with
i = 1
the next.
while i < 6:
i = 0
print(i)
while i < 6:
i += 1
i += 1
if i == 3:
Break Statement: With the break statement we
can stop the loop even if the while condition is continue
true. print(i)
For loop
A for loop is used for iterating over a sequence Example 2: Loop through the letters in the word
"banana".
(that is either a list, a tuple, a dictionary, a set, for x in "banana":
or a string).
print(x)

This is less like the for keyword in other


programming languages, and works more like Example 3: Using the range() function.
an iterator method as found in other object- for x in range(6):
oriented programming languages. print(x)

With the for loop we can execute a set of Example 4:


statements, once for each item in a list, tuple, for x in range(2, 6):
set etc. print(x)
Example 1:
fruits = ["apple", "banana", "cherry"] Example 5: Starts, Ends, Increment
for x in fruits: for x in range(2, 30, 3):
print(x) print(x)
Functions
A function is a block of code which only runs Example:
when it is called. You can pass data, known def my_function(fname, lname):
as parameters, into a function. A function print(fname + " " + lname)
can return data as a result.
my_function("Emil", "Refsnes")
In Python a function is defined using the def
keyword:
Arbitrary Arguments, *args: If you do not know
def my_function(): how many arguments that will be passed into your
print("Hello from a function") function, add a * before the parameter name in the
function definition. This way the function will receive a
my_function(); tuple of arguments, and can access the items
accordingly.
Argument: Information can be passed into def my_function(*kids):
functions as arguments. Arguments are
specified after the function name, inside the print("The youngest child is " + kids[2])
parentheses. You can add as many
arguments as you want, just separate them my_function("Emil", "Tobias", "Linus")
with a comma.
Lambda Function
A lambda function is a small anonymous
function. A lambda function can take any Why Use Lambda Functions?
number of arguments, but can only have one
expression. The power of lambda is better shown when you use them
as an anonymous function inside another function.
Syntax: lambda arguments : expression
Say you have a function definition that takes one
Example 1: Add 10 to argument a, and return the argument, and that argument will be multiplied with an
result unknown number:

x = lambda a : a + 10 def myfunc(n):


print(x(5)) return lambda a : a * n

Example 2: Multiple Arguments.


x = lambda a, b, c : a + b + c mydoubler = myfunc(2)
print(x(5, 6, 2)) print(mydoubler(11))
Python Collections
There are four collection data types in the Python programming language:
● List is a collection which is ordered and changeable. Allows duplicate
members.
● Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
● Set is a collection which is unordered, unchangeable*, and unindexed.
No duplicate members.
● Dictionary is a collection which is ordered** and changeable. No
duplicate members.
Lists
Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used
to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:

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

print(thislist)

List Items

List items are ordered, changeable, and allow duplicate values. List items are indexed, the first item has
index [0], the second item has index [1] etc.

print(thislist[0])

print(thislist[2])
Access List
Positive Indexing : List items are indexed and you can access them by referring to the index
number:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])

Negative Indexing: Negative indexing means start from the end -1 refers to the last item, -2
refers to the second last item etc.
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])

Range Indexing: You can specify a range of indexes by specifying where to start and where to
end the range. When specifying a range, the return value will be a new list with the specified items.

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:5])
Changing List Items
To change the value of a specific item, refer to the index number:

Example 1:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

Change a Range of Item Values

To change the value of items within a specific range, define a list with the new values, and refer to the range
of index numbers where you want to insert the new values.

Example 2:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
Add List Items
Append Items: To add an item to the end of the list, use the append() method.
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist)

Insert Items: To insert a list item at a specified index, use the insert() method. The insert() method inserts
an item at the specified index:
thislist = ["apple", "banana", "cherry"]
[Link](1, "orange")
print(thislist)

Extend List: To append elements from another list to the current list, use the extend() method.
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
[Link](tropical)
print(thislist)
Add List Items
Append Items: To add an item to the end of the list, use the append() method.
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist)

Insert Items: To insert a list item at a specified index, use the insert() method. The insert() method inserts
an item at the specified index:
thislist = ["apple", "banana", "cherry"]
[Link](1, "orange")
print(thislist)

Extend List: To append elements from another list to the current list, use the extend() method.
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
[Link](tropical)
print(thislist)
Remove List Items
Remove Specific Item: The remove() method removes the specified item.
thislist = ["apple", "banana", "cherry"]
[Link]("banana")
print(thislist)

Remove Specific Index: The pop() method removes the specified index. And The del keyword also
removes the specified index.
thislist = ["apple", "banana", "cherry"]
[Link](1)
print(thislist)
or
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

Remove Entire List: Using del keyword or clear() method can help to achieve this.
del thislist or [Link]()
Loop List Items
You can loop through the list items by using a for loop:

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


for x in thislist:
print(x)

Using a While Loop: You can loop through the list items by using a while loop. Use the len() function to
determine the length of the list, then start at 0 and loop your way through the list items by referring to their
indexes. Remember to increase the index by 1 after each iteration.

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

i=0

while i < len(thislist):

print(thislist[i])

i=i+1
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.

Syntax:
newlist = [expression for item in iterable if condition == True]

Example:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
List Sorting
List objects have a sort() method that will sort the list alphanumerically, ascending, by
default:
Example:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link]()
print(thislist)

Sort Descending: To sort descending, use the keyword argument reverse = True:

Example:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link](reverse = True)
print(thislist)
List Copy
1. You can use the built-in List method copy() to copy a list.
thislist = ["apple", "banana", "cherry"]
mylist = [Link]()
print(mylist)

2. Another way to make a copy is to use the built-in method list().


thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)

3. You can also make a copy of a list by using the : (slice) operator.
thislist = ["apple", "banana", "cherry"]
mylist = thislist[:]
print(mylist)
List Joins
1. There are several ways to join, or concatenate, two or more lists in Python. One of the
easiest ways are by using the + operator.

list1 = ["a", "b", "c"]

list2 = [1, 2, 3]

list3 = list1 + list2

print(list3)

2. Use the extend() method to add list2 at the end of list1.

list1 = ["a", "b" , "c"]

list2 = [1, 2, 3]

[Link](list2)

print(list1)
List Methods
Tuples
Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data
types in Python used to store collections of data, the other 3 are List, Set, and Dictionary,
all with different qualities and usage. A tuple is a collection which is ordered and
unchangeable. Tuples are written with round brackets.

Example:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

1. Tuple Items: Tuple items are ordered, unchangeable, and allow duplicate [Link] items
are indexed, the first item has index [0], the second item has index [1] etc.
2. Ordered
3. Unchangeable
4. Allows Duplicates
Access Tuples
1. Positive Indexing: You can access tuple items by referring to the index number, inside square
brackets.

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])

2. Negative Indexing: Negative indexing means start from the end. -1 refers to the last item, -2
refers to the second last item etc.

thistuple = ("apple", "banana", "cherry")

print(thistuple[-1])

3. Range Of Indexing: You can specify a range of indexes by specifying where to start and where to
end the range. When specifying a range, the return value will be a new tuple with the specified
items.

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")

print(thistuple[2:5])
Update Tuples
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also
is called. But there is a way. You can convert the tuple into a list, change the list, and convert the list
back into a tuple.

Example:

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

Adding Items in Tuples:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
[Link]("orange")
thistuple = tuple(y)
Unpack Tuples
When we create a tuple, we normally assign values to it. This is called "packing" a
tuple:
fruits = ("apple", "banana", "cherry")

But, in Python, we are also allowed to extract the values back into variables. This is
called "unpacking":
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
Loop Tuples
You can loop through the tuple items by using a for loop.

thistuple = ("apple", "banana", "cherry")

for x in thistuple:

print(x)

Loop Through the Index Numbers: You can also loop through the tuple items by referring to
their index number. Use the range() and len() functions to create a suitable iterable.
thistuple = ("apple", "banana", "cherry")

for i in range(len(thistuple)):

print(thistuple[i])
Sets
Sets are used to store multiple items in a single variable. 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 with
different qualities and usage. A set is a collection which is unordered, unchangeable*,
and unindexed. Duplicates are not allowed in set.

thisset = {"apple", "banana", "cherry"}

print(thisset)

The set() Constructor: It is also possible to use the set() constructor to make a set.
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets

print(thisset)
Access Sets
You cannot access items in a set by referring to an index or a key. 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.

thisset = {"apple", "banana", "cherry"}

for x in thisset:

print(x)

Check if "banana" is present in the set:

thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

Check if "banana" is NOT present in the set:

thisset = {"apple", "banana", "cherry"}

print("banana" not in thisset)


Add Set Items
Once a set is created, you cannot change its items, but you can add new items. To add one item to a set use
the add() method.

Example:

thisset = {"apple", "banana", "cherry"}


[Link]("orange")
print(thisset)

To add items from another set into the current set, use the update() method.
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
[Link](tropical)
print(thisset)
Remove Item Set
To remove an item in a set, use the remove(), or the discard() method.
Example: remove()
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)
If the item to remove does not exist, remove() will raise an error.

Example: discard()
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)
If the item to remove does not exist, discard() will NOT raise an error.
Remove Item Set
You can also use the pop() method to remove an item, but this method will remove a random item, so you
cannot be sure what item that gets removed. The return value of the pop() method is the removed item.

Example: pop()
thisset = {"apple", "banana", "cherry"}
x = [Link]()
print(x)
print(thisset)
Note: Sets are unordered, so when using the pop() method, you do not know which item that gets removed.

The clear() method empties the set:


[Link]()

The del keyword will delete the set completely:


del thisset
Loop Set
You can loop through the set items by using a for loop.
Example:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)

Join Set
There are several ways to join two or more sets in Python. The union() and update() methods joins all items
from both sets.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = [Link](set2)#[Link](set2)
print(set3)
Dictionary in Python
Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*,
changeable and do not allow duplicates. As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

print(thisdict)

print(thisdict["brand"])

Note: Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created. Dictionaries cannot have two items with the same key.
Change Dictionary
You can change the value of a specific item by referring to its key name:

Items
thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict["year"] = 2018;

[Link]({"year": 2020})

Note: The update() method will update the dictionary with the items from the given argument. The
argument must be a dictionary, or an iterable object with key:value pairs.
Add Dictionary Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict["color"] = "red";

[Link]({"color": "red"})

print(thisdict);

Note: The update() method will update the dictionary with the items from the given argument. The
argument must be a dictionary, or an iterable object with key:value pairs.
Dictionary Methods
OOPs in Python
OOP stands for Object-Oriented Programming. What are Classes and Objects?
Python is an object-oriented language, allowing you Classes and objects are the two core concepts in
to structure your code using classes and objects for object-oriented programming.
better organization and reusability.
A class defines what an object should look like, and
Advantages of OOP an object is created based on that class. For
example:
● Provides a clear structure to programs
● Makes code easier to maintain, reuse, and
debug
● Helps keep your code DRY (Don't Repeat
Yourself)
● Allows you to build reusable applications with
less code
Objects & Class
Python is an object oriented programming The __init__() Function: All classes have a
function called __init__(), which is always executed
language. Almost everything in Python is an when the class is being initiated.
object, with its properties and methods.
Use the __init__() function to assign values to
object properties, or other operations that are
A Class is like an object constructor, or a necessary to do when the object is being created:
"blueprint" for creating objects.
Example:
Example: Creating class & objects. class Person:
def __init__(self, name, age):
class MyClass:
[Link] = name
x = 5 [Link] = age

p1 = MyClass()
p1 = Person("John", 36)
print(p1.x) print([Link])
print([Link])
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another
class.

Parent class is the class being inherited from, also called base class. Child class is the class that
inherits from another class, also called derived class.

Example:
class Person:

def __init__(self, fname, lname):

[Link] = fname

[Link] = lname

def printname(self):

print([Link], [Link])

x = Person("John", "Doe")

[Link]()
Python Polymorphism
The word "polymorphism" means "many forms", and in programming it refers to methods / functions /
operators with the same name that can be executed on many objects or classes.

Polymorphism is often used in Class methods, where we can have multiple classes with the same method
name. For example, say we have three classes: Car, Boat, and Plane, and they all have a method called
move():
class Car: class Plane:
def __init__(self, brand, model): def __init__(self, brand, model):
[Link] = brand [Link] = brand
[Link] = model [Link] = model
def move(self): def move(self):
print("Drive!") print("Fly!")

class Boat: car1 = Car("Ford", "Mustang")


def __init__(self, brand, model): #Create a Car object
[Link] = brand boat1 = Boat("Ibiza", "Touring 20")
[Link] = model #Create a Boat object
def move(self): plane1 = Plane("Boeing", "747")
print("Sail!") #Create a Plane object

for x in (car1, boat1, plane1):


[Link]()
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an error
message. These exceptions can be handled using:

● The try block lets you test a block of code for errors.
● The except block lets you handle the error.
● The else block lets you execute code when there is no error.
● The finally block lets you execute code, regardless of the result of the try- and except blocks.

Syntax: try:
num = int(input("Enter a number: "))
try: result = 10 / num
# code that may raise an exception print("Result:", result)
except ZeroDivisionError:
except SomeError:
print("Cannot divide by zero!")
# code that runs if exception occurs except ValueError:
else: print("Invalid input! Please enter a number.")
# runs if no exception occurs else:
finally: print("Division successful.")
# always runs (optional) finally:
print("Execution complete.")
Exception Description Exception Description

ArithmeticError Raised when an error occurs IndexError Raised when an index of a


in numeric calculations sequence does not exist

AssertionError Raised when an assert KeyError Raised when a key does not
statement fails exist in a dictionary

AttributeError Raised when attribute KeyboardInterrupt Raised when the user presses
reference or assignment fails Ctrl+c, Ctrl+z or Delete

Exception Base class for all exceptions IndexError Raised when an index of a
sequence does not exist
EOFError Raised when the input() KeyError Raised when a key does not
method hits an "end of file" exist in a dictionary
condition (EOF)

FloatingPointError Raised when a floating point OverflowError Raised when the result of a
calculation fails numeric calculation is too large
GeneratorExit Raised when a generator is ReferenceError Raised when a weak reference
closed (with the close() object does not exist
method)

ImportError Raised when an imported RuntimeError Raised when an error occurs


module does not exist that do not belong to any
specific exceptions
IndentationError Raised when indentation is
not correct ZeroDivisionError Raised when the second
operator in a division is zero
File Handling
File handling is an important part of any web "w" - Write - Opens a file for writing, creates the file if
application. Python has several functions for it does not exist.
creating, reading, updating, and deleting files.
"x" - Create - Creates the specified file, returns an
The key function for working with files in Python error if the file exists.
is the open() [Link] open() function takes
two parameters; filename, and mode. In addition you can specify if the file should be
handled as binary or text mode.
There are four different methods (modes) for
opening a file: "t" - Text - Default value. Text mode

"r" - Read - Default value. Opens a file for "b" - Binary - Binary mode (e.g. images)
reading, error if the file does not exist.
Example Syntax:
"a" - Append - f = open("[Link]", "rt")
Append means to add information to the end of
an existing file or create a new file if it does not Because "r" for read, and "t" for text are the default
exist. values, you do not need to specify them.
File Handling
Reading Files If the file is located in a different location, you will have
to specify the file path, like this:
Assume we have the following file, located in the same
folder as Python: f = open("D:\\myfiles\[Link]")

[Link] print([Link]())

Hello! Welcome to [Link], This file is for testing, Using the with statement: Then you do not
purposes. Good Luck! have to worry about closing your files, the with
statement takes care of that.
To open the file, use the built-in open() function. The
open() function returns a file object, which has a read() with open("[Link]") as f:
method for reading the content of the file:
print([Link]())
f = open("[Link]") It reads the first line of the file:

print([Link]()) with open("[Link]") as f:


print([Link]())
[Link]()
File Handling
Write Files Overwrite Existing Content
To write to an existing file, you must add a To overwrite the existing content to the file, use the w
parameter to the open() function:
parameter:
"a" - Append - will append to the end of the file
with open("[Link]", "w") as f:
"w" - Write - will overwrite any existing content [Link]("Woops! I have deleted the content!")

Example:
#open and read the file after the overwriting:
with open("[Link]", "a") as f:
with open("[Link]") as f:
[Link]("Now the file has more content!") print([Link]())

#open and read the file after the appending:

with open("[Link]") as f:

print([Link]())
File Handling
Delete Files

To delete a file, you must import the OS module, and run its [Link]() function:

Example:

import os

[Link]("[Link]")

Check If Exists:

import os

if [Link]("[Link]"):

[Link]("[Link]")

else:

print("The file does not exist")


Python Modules
Consider a module to be the same as a code library. Now we can use the module we just created, by
A file containing a set of functions you want to using the import statement. Import the module
include in your [Link] create a module just named mymodule, and call the greeting function:
save the code you want in a file with the file
extension .py: import mymodule

[Link]("Jonathan")
Save this code in a file named [Link]
a = mymodule.person1["age"]
def greeting(name):
print(a) #Import the module named mymodule,
print("Hello, " + name)
and access the person1 dictionary
person1 = {
Import only the person1 dictionary from the
"name": "John", module:

"age": 36, from mymodule import person1

"country": "Norway" print (person1["age"])

}
Python Numpy
NumPy is a Python library. NumPy is used for working with arrays. NumPy is short for "Numerical Python".

Installation: Example:
$pip install numpy
import numpy as np
Debugging: arr = [Link]([1, 2, 3, 4, 5])
$python -m pip install --upgrade pip print(arr)
or print(type(arr))
$py -m pip install --upgrade pip
Numpy-Dimensions
In NumPy, the term "dimension" refers to the Create a 1-D array containing the values 1,2,3,4,5:
number of axes along which the data is organized
in an array. It's essentially the number of indices import numpy as np
needed to access a specific element within the
arr = [Link]([1, 2, 3, 4, 5], ndmin=1)
array. Dimensions are also referred to as axes in
NumPy. When the array is created, you can define print([Link])
the number of dimensions by using the ndmin
argument. 2D Arrays:

0-D Arrays: 0-D arrays, or Scalars, are the import numpy as np


elements in an array. Each value in an array is a 0-D
array. arr = [Link]([[1, 2, 3], [4, 5, 6]])

import numpy as np print(arr)


arr = [Link](42)
3D Arrays:
print(arr)
import numpy as np
1D Arrays: An array that has 0-D arrays as its arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[1,
elements is called uni-dimensional or 1-D array. These 2, 3], [4, 5, 6]]])
are the most common and basic arrays.
print(arr)
Numpy-Access Items
Access Array Elements Access 2D Arrays
import numpy as np
Array indexing is the same as accessing an array
element. You can access an array element by arr = [Link]([[1,2,3,4,5], [6,7,8,9,10]])
referring to its index number. print('5th element on 2nd row: ', arr[1, 4])

The indexes in NumPy arrays start with 0, meaning


that the first element has index 0, and the second
has index 1 etc. Access 3D Arrays: To access elements from 3-D
arrays we can use comma separated integers
Access 1D Arrays representing the dimensions and the index of the
element.
import numpy as np
import numpy as np
arr = [Link]([1, 2, 3, 4])
arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[7,
print(arr[0]) 8, 9], [10, 11, 12]]])

print(arr[2]) print(arr[0, 1, 2])


Numpy-Data Types
NumPy has some extra data types, and refer to data Creating Arrays With a Defined Data
types with one character, like i for integers, u for Type:
unsigned integers etc. The NumPy array object has a
We use the array() function to create arrays, this
property called dtype that returns the data type of the function can take an optional argument: dtype that
array. Below is a list of all data types in NumPy and allows us to define the expected data type of the
the characters used to represent them. array elements:
import numpy as np
● i - integer
● b - boolean arr = [Link]([1, 2, 3, 4], dtype='S')
● u - unsigned integer print(arr)
● f - float print([Link])
● c - complex float
● m - timedelta Create an array with data type 4 bytes integer:
● M - datetime
import numpy as np
● O - object
● S - string arr = [Link]([1, 2, 3, 4], dtype='i4')
● U - unicode string
print(arr)
● V - fixed chunk of memory for other type ( void )
print([Link])
Numpy-Array Reshape
NumPy arrays have an attribute called shape that returns Convert the following 1-D array with 12 elements into
a tuple with each index having the number of a 2-D array. The outermost dimension will have 4
arrays, each with 3 elements:
corresponding elements.
import numpy as np
Print the shape of a 2-D array:
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12])
import numpy as np
newarr = [Link](4, 3)
arr = [Link]([[1, 2, 3, 4], [5, 6, 7, 8]])
print(newarr)
print([Link])
Convert the following 1D array with 12 elements into
a 3D [Link] outermost dimension will have 2
Reshaping arrays: Reshaping means changing the
arrays that contains 3 arrays, each with 2 elements.
shape of an array.
import numpy as np
The shape of an array is the number of elements in each
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9,
dimension. By reshaping we can add or remove 10, 11, 12])
dimensions or change number of elements in each
newarr = [Link](2, 3, 2)
dimension.
print(newarr)
Numpy-Array Join
Joining NumPy Arrays Join two 2-D arrays along rows (axis=1):
import numpy as np
Joining means putting contents of two or more arrays in a
single array. Whereas in NumPy we join arrays by axes. arr1 = [Link]([[1, 2], [3, 4]])
arr2 = [Link]([[5, 6], [7, 8]])
We pass a sequence of arrays that we want to join to the arr = [Link]((arr1, arr2), axis=1)
concatenate() function, along with the axis. If axis is not
print(arr)
explicitly passed, it is taken as 0.
In numpy there are more types of functions to join
Numpy arrays.
Example:
stack(): Stacking is same as concatenation, the only
import numpy as np difference is that stacking is done along a new
[Link] can concatenate two 1-D arrays along the
second axis which would result in putting them one
arr1 = [Link]([1, 2, 3]) over the other, ie. stacking.

arr2 = [Link]([4, 5, 6]) hstack(): NumPy provides a helper function:


hstack() to stack along rows.
arr = [Link]((arr1, arr2)) vstack(): to stack along columns.
dstack(): to stack along height, which is the same
print(arr) as depth.
Numpy-Array Split
Splitting is reverse operation of Joining. Joining merges The example above returns three 2-D arrays. In
multiple arrays into one and Splitting breaks one array into addition, you can specify which axis you want to do
multiple. We use array_split() for splitting arrays, we pass it the split around.
the array we want to split and the number of splits.
The example below also returns three 2-D arrays,
Split the array in 3 parts: but they are split along the column (axis=1).

import numpy as np Split the 2-D array into three 2-D arrays along
columns.
arr = [Link]([1, 2, 3, 4, 5, 6])
import numpy as np
newarr = np.array_split(arr, 3)
arr = [Link]([[1, 2, 3], [4, 5, 6], [7,
print(newarr)
8, 9], [10, 11, 12], [13, 14, 15], [16,
Note: We also have the method split() available but it will 17, 18]])
not adjust the elements when elements are less in source
newarr = np.array_split(arr, 3, axis=1)
array for splitting like in example above, array_split()
worked properly but split() would fail. print(newarr)
Numpy-Array Search
You can search an array for a certain value, and return the The searchsorted() method is assumed to be used
indexes that get a match. To search an array, use the on sorted arrays.
where() method.
Example
Find the indexes where the value is 4:
Find the indexes where the value 7 should be
import numpy as np inserted:

arr = [Link]([1, 2, 3, 4, 5, 4, 4]) import numpy as np

x = [Link](arr == 4) arr = [Link]([6, 7, 8, 9])

print(x) x = [Link](arr, 7, side='right')

Search Sorted print(x)

There is a method called searchsorted() which performs a Note: By default the leftmost index is returned, but
binary search in the array, and returns the index where the we can give side='right' to return the rightmost index
specified value would be inserted to maintain the search instead.
order.
Numpy-Array Sorting
Sorting means putting elements in an ordered You can also sort arrays of strings, or any other data
type:
sequence. Ordered sequence is any sequence that
has an order corresponding to elements, like numeric
Example
or alphabetical, ascending or descending.
Sort the array alphabetically:
The NumPy ndarray object has a function called
sort(), that will sort a specified array. import numpy as np

Sort the array: arr = [Link](['banana', 'cherry',


'apple'])
import numpy as np
print([Link](arr)
arr = [Link]([3, 2, 0, 1])
Sort a boolean array:
print([Link](arr)) import numpy as np

Note: This method returns a copy of the array, leaving arr = [Link]([True, False, True])
the original array unchanged. print([Link](arr))
Numpy-Array Filter
Getting some elements out of an existing array and creating a new array out of them is called
filtering. In NumPy, you filter an array using a boolean index list.

A boolean index list is a list of booleans corresponding to indexes in the array.

If the value at an index is True that element is contained in the filtered array, if the value at
that index is False that element is excluded from the filtered array.

import numpy as np

arr = [Link]([41, 42, 43, 44])

x = [True, False, True, False]

newarr = arr[x]

print(newarr)
Numpy-Random
What is a Random Number? Generate Random Array: In NumPy we
work with arrays, and you can use the two
Random number does NOT mean a different number
methods from the above examples to make
every time. Random means something that cannot
random arrays.
be predicted logically. In simple terms which is
uncertain. Integers: The randint() method takes a size
parameter where you can specify the shape of
Generate Random Number: NumPy offers the
an array.
random module to work with random numbers.
Generate a 2D array with 3 rows, each row
from numpy import random
containing 5 random integers from 0 to 100:
x = [Link](100)
from numpy import random
print(x)
x = [Link](100, size=(3, 5))

Generate Random Float: The random module print(x)


rand() method returns a random float between 0 and
1.
Normal (Gaussian) Distribution
Normal Distribution Example 1: Generate a random normal
distribution of size 2x3.
The Normal Distribution is one of the most important
from numpy import random
distributions. It is also called the Gaussian
Distribution after the German mathematician Carl x = [Link](size=(2, 3))
Friedrich Gauss.
print(x)
It fits the probability distribution of many events, eg.
IQ Scores, Heartbeat etc. Use the [Link]()
method to get a Normal Data Distribution. Example 2: Generate a random normal distribution of
size 2x3 with mean at 1 and standard deviation of 2.
It has three parameters:
from numpy import random
loc - (Mean) where the peak of the bell exists. x = [Link](loc=1, scale=2, size=(2, 3))

scale - (Standard Deviation) how flat the graph print(x)


distribution should be.

size - The shape of the returned array.


Binomial Distribution
Binomial Distribution is a Discrete Example 1: Given 10 trials for coin toss generate
Distribution. It describes the outcome of binary 1000 data points.
scenarios, e.g. toss of a coin, it will either be
from numpy import random
head or tails.
x = [Link](n=10, p=0.5, size=1000)
It has three parameters:
print(x)
n - number of trials.

p - probability of occurrence of each trial (e.g. for


toss of a coin 0.5 each).

size - The shape of the returned array.

Discrete Distribution: The distribution is


defined at separate set of events, e.g. a coin toss
result is discrete as it can be only head or tails
whereas height of people is continuous as it can
be 170, 170.1, 170.11 and so on.
Pandas
What is Pandas?

Pandas is a Python library used for working with data sets. It has functions for analyzing, cleaning, exploring,
and manipulating data. The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis"
and was created by Wes McKinney in 2008.

Why Use Pandas?

Pandas allows us to analyze big data and make conclusions based on statistical theories. Pandas can clean
messy data sets, and make them readable and relevant. Relevant data is very important in data science.
Pandas-Installation
Installation of Pandas Once Pandas is installed, import it in your
applications by adding the import keyword:
If you have Python and PIP already installed on a
system, then installation of Pandas is very easy. Example for pandas:

Install it using this command: import pandas

$pip install pandas mydataset = {

'cars': ["BMW", "Volvo", "Ford"],

Debugging for pip: 'passings': [3, 7, 2]

$python -m pip install --upgrade pip }


or
$py -m pip install --upgrade pip myvar = [Link](mydataset)

print(myvar)
Pandas-Series
What is a Series? Create Labels

A Pandas Series is like a column in a table. It is a one- With the index argument, you can name your own labels.
dimensional array holding data of any type.
Example
Create a simple Pandas Series from a list: Create your own labels:

import pandas as pd import pandas as pd

a = [1, 7, 2] a = [1, 7, 2]

myvar = [Link](a) myvar = [Link](a, index = ["x", "y", "z"])

print(myvar) print(myvar)

Return the first value of the Series: When you have created labels, you can access an item
by referring to the label.
print(myvar[0])
print(myvar["y"])
Pandas DataFrames
What is a Data Frame? Locate Row
A Pandas DataFrame is a 2 dimensional data structure,
like a 2 dimensional array, or a table with rows and As you can see from the result above, the Data Frame is
columns. like a table with rows and columns. Pandas use the loc
Create a simple Pandas DataFrame: attribute to return one or more specified row(s).

import pandas as pd Example

data = { Return row 0:


"calories": [420, 380, 390],
#refer to the row index:
"duration": [50, 40, 45]
print([Link][0])
}
Return row 0 and 1:
#load data into a DataFrame object:
#use a list of indexes:
df = [Link](data)

print(df) print([Link][[0, 1]])


Read CSV & Excel
A simple way to store big data sets is to use To read an Excel file using Pandas in Python, you
CSV files (comma separated files). CSV files use the read_excel() function.
contains plain text and is a well know format
import pandas as pd
that can be read by everyone including
Pandas. # Reading the Excel file

Example: df = pd.read_excel("students_data.xlsx") #
Displaying first few rows
Load the CSV into a DataFrame:
print([Link]())
import pandas as pd or
df = pd.read_csv('[Link]') print(df)

print(df)
Read JSON
Big data sets are often stored, or extracted as JSON. JSON is plain text, but has the
format of an object, and is well known in the world of programming, including Pandas.

Load the JSON file into a DataFrame:

import pandas as pd

df = pd.read_json('[Link]')

print(df)
Analyzing DataFrames
Viewing the Data There is also a tail() method for viewing the
last rows of the DataFrame. The tail() method
One of the most used method for getting a quick returns the headers and a specified number of
overview of the DataFrame, is the head() rows, starting from the bottom.
method. Example
The head() method returns the headers and a Print the last 5 rows of the DataFrame:
specified number of rows, starting from the top.
print([Link]())
Example:
Info About the Data
Get a quick overview by printing the first 10 rows The DataFrames object has a method called
of the DataFrame: info(), that gives you more information about
the data set.
import pandas as pd
Print information about the data:
df = pd.read_csv('[Link]')
print([Link]())
print([Link](10))
Data Cleaning
Data Cleaning: Data cleaning means Note: Now, the dropna(inplace = True) will NOT
fixing bad data in your data set. return a new DataFrame, but it will remove all
Bad data could be: rows containing NULL values from the original
DataFrame.
● Empty cells
● Data in wrong format Replace Empty Values: Another way of
dealing with empty cells is to insert a new value
● Wrong data instead. This way you do not have to delete
● Duplicates entire rows just because of some empty cells.

Empty cells can potentially give you a The fillna() method allows us to replace empty
wrong result when you analyze data. cells with a value:
Remove all rows with NULL values:
Replace NULL values with the number 130:
import pandas as pd
df = pd.read_csv('[Link]') import pandas as pd

[Link](inplace = True) df = pd.read_csv('[Link]')


print(df.to_string()) [Link](130, inplace = True)
Data Cleaning
Original:
Removing Rows Duration Date Pulse Max-pulse Calories
0 60 2020-12-01 110 130 409.1
The result from the converting in the example above 1 60 2020-12-02 117 145 479.0
gave us a NaT value, which can be handled as a 2 60 2020-12-03 103 135 340.0
NULL value, and we can remove the row by using 3 45 109 175
282.4
the dropna() method. 4 45 2020-12-05 117 148 406.0
5 60 2020-12-06 102 127 300.0
import pandas as pd
After:
df = pd.read_csv('[Link]') Duration Date Pulse Max-pulse Calories
0 60 2020-12-01 110 130 409.1
df['Date'] = pd.to_datetime(df['Date']) 1 60 2020-12-02 117 145 479.0
2 60 2020-12-03 103 135 340.0
[Link](subset=['Date'], inplace = True) 4 45 2020-12-05 117 148 406.0
5 60 2020-12-06 102 127 300.0
print(df.to_string())
Data Cleaning
Cleaning Wrong Data Example
"Wrong data" does not have to be "empty cells" or Set "Duration" = 45 in row 7:
"wrong format", it can just be wrong, like if someone
registered "199" instead of "1.99".
[Link][7, 'Duration'] = 45
Sometimes you can spot wrong data by looking at
the data set, because you have an expectation of For small data sets you might be able to replace the
what it should be. wrong data one by one, but not for big data [Link]
replace wrong data for larger data sets you can
Replacing Values create some rules, e.g. set some boundaries for legal
One way to fix wrong values is to replace them with
values, and replace any values that are outside of the
something else. boundaries.
for x in [Link]:
In our example, it is most likely a typo, and the
value should be "45" instead of "450", and we could
if [Link][x, "Duration"] > 120:
just insert "45" in row 7: [Link][x, "Duration"] = 120
Data Cleaning
Duplicate Data Removing Duplicates
Duplicate rows are rows that have been registered To remove duplicates, use the drop_duplicates() method.
more than one time. By taking a look at our test
data set, we can assume that row 11 and 12 are Example:
duplicates.
import pandas as pd
To discover duplicates, we can use the duplicated()
method. df = pd.read_csv('[Link]')

Example: df.drop_duplicates(inplace = True)

import pandas as pd print(df)

df = pd.read_csv('[Link]')
Remember: The (inplace = True) will make sure that the
method does NOT return a new DataFrame, but it will
print([Link]().sum())
remove all duplicates from the original DataFrame.
Data Correlations
Finding Relationships Perfect Correlation:
A great aspect of the Pandas module is the corr() We can see that "Duration" and "Duration" got the number
1.000000, which makes sense, each column always has a
method. perfect relationship with itself.

The corr() method calculates the relationship between Good Correlation:


each column in your data set.
"Duration" and "Calories" got a 0.922721 correlation, which
Example: is a very good correlation, and we can predict that the
longer you work out, the more calories you burn, and the
other way around: if you burned a lot of calories, you
import pandas as pd probably had a long work out.

df = pd.read_csv('[Link]')
Bad Correlation:
print([Link]())
"Duration" and "Maxpulse" got a 0.009403 correlation,
which is a very bad correlation, meaning that we can not
predict the max pulse by just looking at the duration of the
work out, and vice versa.
Python Matplotlib
What is Matplotlib?
Matplotlib is a low level graph plotting library in python that serves as a visualization
utility. It was created by John D. Hunter.

Matplotlib is open source and we can use it freely. Matplotlib is mostly written in python, a
few segments are written in C, Objective-C and Javascript for Platform compatibility.
Matplotlib Installation

Installation of Matplotlib
If you have Python and PIP already installed on a system, then installation of Matplotlib is very easy.

Install it using this command:

$pip install matplotlib

Debugging for pip:

$python -m pip install --upgrade pip


or
$py -m pip install --upgrade pip
Matplotlib Pyplot
Pyplot: Most of the Matplotlib utilities lies under
the pyplot submodule, and are usually imported
under the plt alias.

Example: Draw a line in a diagram from position


(5, 5) to position (0, 250):

import [Link] as plt


import numpy as np
xpoints = [Link]([5, 0])
ypoints = [Link]([5, 250])
[Link](xpoints, ypoints)
[Link]()
Matplotlib Plotting
Plotting x and y points
The plot() function is used to draw points (markers)
in a diagram. By default, the plot() function draws a
line from point to point. The function takes
parameters for specifying points in the diagram.
Parameter 1 is an array containing the points on the
x-axis. Parameter 2 is an array containing the points
on the y-axis.
Draw a line in a diagram from position (1, 3) to
(2, 8) then to (6, 1) and finally to position (8,
10):
import [Link] as plt
import numpy as np
xpoints = [Link]([1, 2, 6, 8])
ypoints = [Link]([3, 8, 1, 10])
[Link](xpoints, ypoints)
[Link]()
Matplotlib Markers
Markers

You can use the keyword argument marker to


emphasize each point with a specified marker.

Example:
Mark each point with a circle:

import [Link] as plt

import numpy as np

ypoints = [Link]([3, 8, 1, 10])

[Link](ypoints, marker = 'o')

[Link]()
Markers List
Line Style

Linestyle

You can use the keyword argument linestyle, or


shorter ls, to change the style of the plotted line.

Use a dotted line:

import [Link] as plt

import numpy as np

ypoints = [Link]([3, 8, 1, 10])

[Link](ypoints, linestyle = 'dotted')

[Link]()
Line Style

Linestyle

You can use the keyword argument linestyle, or


shorter ls, to change the style of the plotted line.

Use a dotted line:

import [Link] as plt

import numpy as np

ypoints = [Link]([3, 8, 1, 10])

[Link](ypoints, linestyle = 'dotted')

[Link]()
Line Style

Line Color: You can use the keyword argument


color or the shorter c to set the color of the line.
import [Link] as plt
import numpy as np
ypoints = [Link]([3, 8, 1, 10])
[Link](ypoints, color = 'red')
[Link]()
Matplotlib Labels and Title
Create Labels for a Plot

With Pyplot, you can use the xlabel() and ylabel()


functions to set a label for the x- and y-axis.

import numpy as np

import [Link] as plt

x = [Link]([80, 85, 90, 95, 100, 105,


110, 115, 120, 125])

y = [Link]([240, 250, 260, 270, 280,


290, 300, 310, 320, 330])

[Link](x, y)

[Link]("Average Pulse")

[Link]("Calorie Burnage")

[Link]()
Matplotlib Labels and Title
Create Labels for a Plot
With Pyplot, you can use the xlabel() and ylabel()
functions to set a label for the x- and y-axis.
import numpy as np
import [Link] as plt
x = [Link]([80, 85, 90, 95, 100, 105,
110, 115, 120, 125])
y = [Link]([240, 250, 260, 270, 280,
290, 300, 310, 320, 330])
[Link]("Sports Watch Data", loc =
'left')
[Link]("Average Pulse")
[Link]("Calorie Burnage")
[Link](x, y)
[Link]()
Grid Lines
Add Grid Lines to a Plot
With Pyplot, you can use the grid() function to add
grid lines to the plot.
import numpy as np
import [Link] as plt
x = [Link]([80, 85, 90, 95, 100, 105,
110, 115, 120, 125])
y = [Link]([240, 250, 260, 270, 280,
290, 300, 310, 320, 330])
[Link]("Sports Watch Data")
[Link]("Average Pulse")
[Link]("Calorie Burnage")
[Link](x, y)
[Link]()
[Link]()
Subplot
The subplot() Function
The subplot() function takes three arguments that describes the layout of the figure. The layout is organized in
rows and columns, which are represented by the first and second argument. The third argument represents
the index of the current plot.

[Link](1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is the first plot.

[Link](1, 2, 2)

#the figure has 1 row, 2 columns, and this plot is the second plot.
Subplot
Example:
import [Link] as plt
import numpy as np
#plot 1:
x = [Link]([0, 1, 2, 3])
y = [Link]([3, 8, 1, 10])
[Link](2, 1, 1)
[Link](x,y)

#plot 2:
x = [Link]([0, 1, 2, 3])
y = [Link]([10, 20, 30, 40])
[Link](2, 1, 2)
[Link](x,y)
[Link]()
Scatter Plot
Creating Scatter Plots
With Pyplot, you can use the scatter() function to draw a
scatter plot. The scatter() function plots one dot for
each observation. It needs two arrays of the same length,
one for the values of the x-axis, and one for values on the
y-axis.
Example:
import [Link] as plt
import numpy as np
x = [Link]([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = [Link]([99, 86 , 87 , 88, 111, 86, 103, 87,
94, 78, 77, 85, 86])
[Link](x, y)
[Link]()
Bar Plot
Creating Bars
With Pyplot, you can use the bar() function to draw bar
graphs. The bar() function takes arguments that describes
the layout of the bars. The categories and their values
represented by the first and second argument as arrays.

import [Link] as plt

import numpy as np

x = [Link](["A", "B", "C", "D"])

y = [Link]([3, 8, 1, 10])

[Link](x,y)

[Link]()
Bar Plot
Horizontal Bars
If you want the bars to be displayed horizontally instead of
vertically, use the barh() function.

Example:

import [Link] as plt


import numpy as np

x = [Link](["A", "B", "C", "D"])


y = [Link]([3, 8, 1, 10])

[Link](x, y)
[Link]()
Histogram
A histogram is a graph showing frequency distributions. It
is a graph showing the number of observations within each
given interval.

Example: Say you ask for the height of 250 people,


you might end up with a histogram like this.

import [Link] as plt


import numpy as np

x = [Link](170, 10, 250)

[Link](x)
[Link]()
Pie Chart

Creating Pie Charts


With Pyplot, you can use the pie() function to draw pie
charts.

Example: A simple pie chart.


import [Link] as plt
import numpy as np

y = [Link]([35, 25, 25, 15])

[Link](y)
[Link]()
Pie Chart

Labels
Add labels to the pie chart with the labels parameter. The
labels parameter must be an array with one label for
each wedge.

import [Link] as plt

import numpy as np

y = [Link]([35, 25, 25, 15])

mylabels = ["A", "B", "C", "D"]

[Link](y, labels = mylabels)

[Link]()
Web API in Python
What is Web API in Python?

API: Application Programming Interface.

Web API: A web service that allows applications to


communicate and share data over the internet
using HTTP.

Examples:

● Weather API: Get current temperature of a


city.

● Currency Exchange API: Get latest conversion


rates.
Web API in Python
Why Use Web APIs?

Explanation:

● Automate data retrieval

● Access real-time information

● Use external services (like Google Maps, Weather, Twitter)

Example Use Cases:

● Stock price updates

● Weather forecasting

● Social media integration


Web API-JSON
JSON is a syntax for storing and exchanging data. Convert from Python to JSON
JSON is text, written with JavaScript object
notation. Python has a built-in package called json, If you have a Python object, you can convert it
which can be used to work with JSON data. into a JSON string by using the [Link]()
method.
Convert from JSON to Python: If you have
a JSON string, you can parse it by using the import json
[Link]() method.
x = {
import json "name": "John",
"age": 30,
x = '{ "name":"John", "age":30, "city":"New
York"}' "city": "New York"
}
y = [Link](x)
y = [Link](x)
print(y["age"])
print(y)
Web API-JSON
You can convert Python objects of the following Convert a Python object containing all the legal data
types:
types, into JSON strings:
import json

● dict x = {
● list "name": "John",
● tuple "age": 30,
● string "married": True,
● int "divorced": False,
● float "children": ("Ann","Billy"),
● True "pets": None,
● False "cars": [
● None {"model": "BMW 230", "mpg":
27.5},
{"model": "Ford Edge", "mpg":
24.1}
]
}
print([Link](x))
Web API-JSON
Convert a Python object containing all the legal data Accessing the Json format:
types:
import json Task Python Code Output
x = {
"name": "John",
Get name data["name"] 'John'

"age": 30, Get first child data["children"][0] 'Ann'


"married": True,
"divorced": False, Get second car data["cars"][1] 'Ford
"children": ("Ann","Billy"), model ["model"] Edge'
"pets": None,
Get MPG of BMW data["cars"][0]["mpg"] 27.5
"cars": [
{"model": "BMW 230", "mpg":
27.5}, Check if married data["married"] True
{"model": "Ford Edge", "mpg":
24.1}
] Check if pets data["pets"] is None True
exist
}
print([Link](x))
Web API Python
Python Requests
Make a request to a web page, and print the response text. The requests module allows you to send HTTP
requests using Python.

The HTTP request returns a Response Object with all the response data (content, encoding, status, etc).

Installation:
$pip install requests

Useage:

import requests
x = [Link]('[Link]
print([Link])
Web API Python
Python Requests Methods
Web API Python
Weather Details Fetching Using Web API

Step 01: Visit [Link]

Step 02: Register Yourself using valid credentials.

Step 03: Login into dashboard

Step 04: Click on My Apps

Step 05: Click on add a new app

Step 06: Click on the app and copy the key


Web API Python
Weather Details Fetching Using Web API
Step 01: Get The location Key using API Call

import requests

api_key = "API_Key"
city = input("Enter a City Name:")
url = f"[Link]

def fetchLocationKey():
location_url = url
response = [Link](location_url)
data = [Link]()
if response.status_code == 200 and data:
location_key = data[0]['Key']
return location_key
else:
print("Error fetching location key")

location_Key = fetchLocationKey()
Web API Python
Weather Details Fetching Using Web API
Step 02: Fetch Weather Details by location key

weather_url = f"[Link]

# Make the request


response = [Link](weather_url)

# Parse the response


if response.status_code == 200:
weather_data = [Link]()
if weather_data:
temperature = weather_data[0]['Temperature']['Metric']['Value']
unit = weather_data[0]['Temperature']['Metric']['Unit']
description = weather_data[0]['WeatherText']

print(f"Current weather in {city}: {description}, {temperature}°{unit}")


else:
print("No weather data found")
else:
print(f"Failed to fetch weather. Status: {response.status_code}")
Database Connectivity
Introduction to Database Connectivity
🔹 What is Database Connectivity?
It refers to how a program communicates with a database to store, retrieve, update, or delete data. Python supports
many databases; here we use SQLite, which is built-in and file-based.

🔹 Introduction to SQLite3
SQLite is a lightweight, embedded, relational database engine that is built into Python via the sqlite3 module.
Unlike other database systems like MySQL or PostgreSQL, SQLite doesn't require a server—it stores the entire
database as a single file on disk (.db).

🔹 Why Use SQLite3?


● Self-contained: Stores the whole database in one file.

● ⚙️Serverless: No need to install or manage a database server.

● 🔧 Built-in with Python: No external libraries needed.

● 📚 Great for learning, small apps, prototyping.


Database Connectivity
Connecting to SQLite using sqlite3
Import & Connect
import sqlite3

conn = [Link]('[Link]') # creates file if not exists

cursor = [Link]()

🔸 Create Cursor

cursor is used to execute SQL commands

🔹 Close Connection
[Link]()
Database Connectivity
Creating Tables
🔸 Create Table Query:
[Link]("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
""")
[Link]()

🔹 Notes:

● IF NOT EXISTS: avoids duplicate table error

● commit(): saves changes


Database Connectivity
CRUD Operations (Insert & Read)
🔸 INSERT Data:

[Link]("INSERT INTO students (name, age) VALUES (?, ?)", ("MyName", 18))

[Link]()

🔸 SELECT Data:

[Link]("SELECT * FROM students")

rows = [Link]()

for row in rows:

print(row)
Database Connectivity
CRUD Operations (Update & Delete)
🔸 UPDATE Data:
[Link]("UPDATE students SET age = ? WHERE name = ?", (23, "Arun"))
[Link]()

🔸 DELETE Data:
[Link]("DELETE FROM students WHERE name = ?", ("Arun",))
[Link]()

🔚 Final Tip:

Always use commit() after INSERT, UPDATE, or DELETE because commit() is used to save the
changes (like INSERT, UPDATE, DELETE) permanently into the database file. Without calling
commit(), those changes are only temporary (in memory) and will be lost when the program
ends.
What We Learned
📚 What You’ve Learned:
● ✅ Basics of Python: Syntax, Variables, Control Flow

● ✅ Functions & Modules for reusable code

● ✅ Data Structures: List, Tuple, Set, Dictionary

● ✅ String Handling & File Operations

● ✅ Exception Handling & Debugging techniques

● ✅ Object-Oriented Programming (OOP)

● ✅ Working with Libraries: NumPy, pandas

● ✅ Data Visualization using matplotlib

● ✅ Web APIs & JSON for real-time data

● ✅ SQLite Database Connectivity & CRUD operations


What Next?
🚀 What’s Next?
● 🔸 Build Real Projects:
➤ Weather App, Expense Tracker, Data Dashboard

● 🔸 Learn Advanced Concepts:


➤ Web Development (Flask, Django)
➤ Automation, Web Scraping, Data Science

● 🔸 Explore Career Paths:


➤ Python Developer, Data Analyst, ML Engineer

● 🔸 Keep Practicing & Share Your Work on GitHub!

You might also like