Python Programming Basics Tutorial
Python Programming Basics Tutorial
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:
3. successful installation
3. successful Installation
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
#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.
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).
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:
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:
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:
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]())
a = "Hello, World!"
print([Link]())
3. Strip: The strip() method removes any whitespace from the beginning or the end.
a = "Hello"
b = "World"
c=a+b
print(c)
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(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)
● 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)
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.
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)
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:
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.
i=0
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)
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.
list2 = [1, 2, 3]
print(list3)
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:
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.
2. Negative Indexing: Negative indexing means start from the end. -1 refers to the last item, -2
refers to the second last item etc.
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.
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:
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.
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.
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.
for x in thisset:
print(x)
print("banana" in thisset)
Example:
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.
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:
[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!")
● 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
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)
"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:
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]())
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:
[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:
}
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:
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:
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
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.
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
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))
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.
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:
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:
a = [1, 7, 2] a = [1, 7, 2]
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).
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.
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
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.
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.
Example:
Mark each point with a circle:
import numpy as np
[Link]()
Markers List
Line Style
Linestyle
import numpy as np
[Link]()
Line Style
Linestyle
import numpy as np
[Link]()
Line Style
import numpy as np
[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 numpy as np
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:
[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.
[Link](x)
[Link]()
Pie Chart
[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 numpy as np
[Link]()
Web API in Python
What is Web API in Python?
Examples:
Explanation:
● Weather forecasting
● 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'
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
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]
🔹 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).
cursor = [Link]()
🔸 Create Cursor
🔹 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:
[Link]("INSERT INTO students (name, age) VALUES (?, ?)", ("MyName", 18))
[Link]()
🔸 SELECT Data:
rows = [Link]()
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