0% found this document useful (0 votes)
115 views72 pages

Business Analysis Using Python

The document provides an overview of data analytics, its importance in decision-making, and types such as descriptive, diagnostic, predictive, and prescriptive analytics. It also introduces Python as a programming language for data analytics, covering installation, IDEs, and essential libraries like NumPy and Pandas. Additionally, it includes basic Python programming concepts such as variables, data types, functions, and object-oriented programming.

Uploaded by

Jyoti Mane
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)
115 views72 pages

Business Analysis Using Python

The document provides an overview of data analytics, its importance in decision-making, and types such as descriptive, diagnostic, predictive, and prescriptive analytics. It also introduces Python as a programming language for data analytics, covering installation, IDEs, and essential libraries like NumPy and Pandas. Additionally, it includes basic Python programming concepts such as variables, data types, functions, and object-oriented programming.

Uploaded by

Jyoti Mane
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
You are on page 1/ 72

Business

Analysis using
Python
Contents
 Overview of Data Analytics:
 Definition of Data Analytics,
 Importance in decision-making and business intelligence,
 Types of data analytics: Descriptive, Diagnostic, Predictive, and
Prescriptive.
 Python for Data Analytics:
 Python installation and setup,
 Introduction to Python Integrated Development
 Environments (IDEs),
 Basics of Python programming (variables, data types, loops, and
functions)
Overview of Data Analytics
 Definition of Data Analytics:
 Data analytics is an important field that involves the process of
collecting, processing, and interpreting data to uncover insights
and help in making decisions. Data analytics is the practice of
examining raw data to identify trends, draw conclusions, and
extract meaningful information. This involves various techniques
and tools to process and transform data into valuable insights
that can be used for decision-making.
 Steps in Data Analysis
 Define Data Requirements : This involves determining how the
data will be grouped or categorized. Data can be segmented based
on various factors such as age, demographic, income, or gender,
and can consist of numerical values or categorical data.
 Data Collection : Data is gathered from different sources,
including computers, online platforms, cameras, environmental
sensors, or through human personnel.
 Data Organization : Once collected, the data needs to be
organized in a structured format to facilitate analysis. This could
involve using spreadsheets or specialized software designed for
managing and analyzing statistical data.
 Data Cleaning : Before analysis, the data undergoes a cleaning
process to ensure accuracy and reliability. This involves identifying
and removing any duplicate or erroneous entries, as well as
addressing any missing or incomplete data. Cleaning the data helps
to mitigate potential biases and errors that could affect the analysis
results.
Importance of Data Analytics
in Decision-Making and
Business Intelligence
 In today’s digital world, data is considered one of the most valuable assets for any business.
Data analytics plays a crucial role in decision-making and business intelligence by providing
actionable insights that drive informed strategies. The importance of data analytics
includes:
 Informed Decision-Making: Data analytics helps organizations make decisions based on
facts, reducing reliance on intuition or guesswork. Leaders can use data-driven insights to
allocate resources more efficiently, optimize processes, and identify opportunities for
growth.
 Improved Business Intelligence: Business intelligence (BI) is about gathering and
analyzing data to understand market trends, consumer behavior, and internal operations.
Data analytics allows businesses to convert raw data into meaningful information, helping
organizations stay competitive and make strategic choices.
 Cost Reduction: By identifying inefficiencies or wasteful spending, companies can optimize
their operations and reduce costs. Analytics helps businesses prioritize resources and
optimize spending.
 Predicting Trends: Analytics provides a view into future trends, enabling businesses to
prepare and adapt accordingly, rather than reacting to changes after they happen.
Types of Data Analytics
 Descriptive Analytics :
 Descriptive analytics is one of the most basic level of classification of analytics used
by almost 90% of organizations. It focuses on answering "What has happened?" by
analyzing real-time and historical data. It helps organizations understand past
successes and failures and provides insights for future decision-making
 Example -
 Let's take an example of DMart, we can look at the product's history and find out
which products have been sold more or which products have large demand by
looking at the product sold trends and based on their analysis we can further make
the decision of putting a stock of that item in large quantity for the coming year.
 Diagnostic Analytics :
 Diagnostic analysis works hand in hand with Descriptive analytics. As descriptive
analytics find out what happened in the past, diagnostic analytics, on the other
hand, finds out why did that happen or what measures were taken at that time, or
how frequent it has happened.it basically gives a detailed explanation of a particular
scenario by understanding behavior patterns.
 Example -
 Let's take the example of Dmart again. Now if we want to find out why a particular
product has a lot of demand, is it because of their brand or is it because of quality. All
this information can easily be identified using diagnostic analytics.
 Predictive Analytics :
 Whatever information we have received from descriptive and diagnostic
analytics, we can use that information to predict future data. it basically
finds out what is likely to happen in the future. Now when I say future data
doesn't mean we have become fortune-tellers, by looking at the past
trends and behavioral patterns we are forecasting that it might happen in
the future.
 Example -
 The best example would be Amazon and Netflix recommender system. You
might have noticed that whenever you buy any product from Amazon, on
the payment side it shows you a recommendation saying the customer
who purchased this has also purchased this product that recommendation
is based on the customer purchased behavior in the past. By looking at
customer past purchase behavior analyst creates an association between
each product and that's the reason it shows recommendation when you
buy any product.
 The next example would be Netflix, when you watch any movies or web
series on Netflix you can see that Netflix provide you with a lot of
recommended movies or web series, that recommendation is based on
past data or past trends, it identifies which movie or series has gain lot of
public interest and based on that it creates a recommendation
 Prescriptive Analytics :
 This is an advanced method of Predictive analytics. Now when
you predict something or when you start thinking out of the box
you will definitely have a lot of options, and then we get confused
as to which option will actually work. Prescriptive analytics helps
to find which is the best option to make it happen or work. As
predictive analytics forecast future data, Prescriptive analytics on
the other hand helps to make it happen whatever we have
forecasted. Prescriptive analytics is the highest level of analytics
that is used for choosing the best optimal solution by looking at
descriptive, diagnostic, and predictive data.
 Example-
 The best example would be Google self-driving Car, by looking at
the past trends and forecasted data it identifies when to turn or
when to slow down, works much like a human driver.
Python Introduction
What is Python?
 Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
It is used for:
o web development (server-side),
o software development,
o mathematics,
o system scripting.
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.
Why Python?
 Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with
fewer lines than some other programming languages.
 Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can
be very quick.
 Python can be treated in a procedural way, an object-oriented
way or a functional way.
 The latest stable version of Python is 3.13.5, released in July
2025. This release includes important bug fixes and
optimizations, enhancing the language's stability and
performance
How to Install Python in
Windows?
 To download Python on your system, you can use the following steps
 Step 1: Select Version to Install Python
 Visit the official page for Python https://www.python.org//downloads/
on the Windows operating system. Locate a reliable version of
Python 3, preferably version 3.10.11, which was used in testing this
tutorial. Choose the correct link for your device from the options
provided: either Windows installer (64-bit) or Windows
installer (32-bit) and proceed to download the executable file.
After Clicking the Install Now Button the setup will start
installing Python on your Windows system. You will see a
window like this.
 Step 3: Running the Executable Installer
 After completing the setup. Python will be installed on your
Windows system. You will see a successful message.
 Step 4: Verify the Python Installation in Windows
 Close the window after successful installation of Python. You can
check if the installation of Python was successful by using either
the command line or the Integrated Development
Environment (IDLE), which you may have installed. To access
the command line, click on the Start menu and type "cmd" in the
search bar. Then click on Command Prompt.
Introduction to Python Integrated
Development
 An Integrated Development Environment (IDE) for Python is a software
application that provides a comprehensive set of tools and features to
facilitate the development of Python applications. IDEs aim to streamline
the coding process by integrating various functionalities into a single
environment, enhancing productivity and simplifying the development
workflow.
 For Python, IDEs help by combining:
 Code Editor: Where you write your Python code with features like
syntax highlighting and auto-completion.
 Interpreter/Compiler: Executes the Python code.
 Debugger: Helps find and fix errors.
 Build Automation Tools: To streamline running and packaging your
code.
 Version Control Integration: Helps manage code changes.
 Popular Python IDEs and Editors
 PyCharm: A powerful IDE specifically for Python with professional
and community editions.
 Visual Studio Code (VS Code): A lightweight but powerful editor
with Python extensions.
 Jupyter Notebook: Ideal for data science and interactive coding
with code, text, and visuals combined.
 Spyder: Popular among scientists and engineers for scientific
computing.
 IDLE: Python’s built-in simple IDE, great for beginners.
Essential Python Libraries

 NumPy:NumPy, short for Numerical Python, has long been a


cornerstone of numerical computing in Python. It provides the
data structures, algorithms, and library glue needed for most
scientific applications involving numerical data in Python.
 Pandas: pandas provides high-level data structures and
functions designed to make working with structured or tabular
data fast, easy, and expressive.
 Matplotlib: matplotlib is the most popular Python library for
producing plots and other two-dimensional data visualizations.
Import Convention
 When you write Python code that uses external modules or libraries, you bring
those modules into your code using the import statement. Following import
conventions helps keep your code clean, readable, and consistent.
 Basic Import Syntax:
import module_name
Import with Alias
You can give a module or an item a shorter alias using as, which can
make your code cleaner:
import module_name as alias

 The Python community has adopted a number of naming conventions


for
commonly used modules:
 import numpy as np
 import matplotlib.pyplot as plt
 import pandas as pd
 import seaborn as sns
 import statsmodels as sm
 Example
import numpy as np
np.arange(10)

 it means you’re calling the arange function from the


NumPy library, but with the short alias np.
The Python Interpreter
 Python is an interpreted language. The Python interpreter runs a program
by executing one statement at a time. The standard interactive Python
interpreter can be invoked on the command line with the python
command:
 $ python
 Python 3.8.6 | packaged by conda-forge | (default, Jan 25 2021,
 23:22:12)
 [Clang 11.0.1 ] on darwin
 Type "help", "copyright", "credits" or "license" for more
 information.
 >>> a = 5
 >>> print(a)
 5
 The >>> you see is the prompt where you’ll type code expressions. To
exit the Python interpreter, you can either type exit() or press Ctrl-D
Python Language Basics
 1. Comments
 Comments are notes you write in code to explain what it
does.Python ignores comments when running the program.
 Use # for one-line comments:
 Example:
# This is a single-line comment
print("Hello") # This comment is after a line of code
Use triple quotes for multi-line comments or documentation strings
Example:
"""
This is a multi-line comment.
It can span several lines.
"""
Variables and Data Types

 A variable is a name that refers to a value stored in your computer’s


memory.
 Example
x = 10
name = "Alice"
 Python Data Types
 1. Integer (int)
 Represents whole numbers (positive or negative.
 2.Floating Point Number (float)Represents numbers with
decimals (fractional part)
 3.String (str)Represents text, enclosed in quotes (single ',
double ", or triple quotes).
Simple python programs

 Example 1: print hello


 print("Hello")
 Example 2: add two numbers
a=5
b=3
sum = a + b
print("Sum:", sum)
 # Take input from the user and convert it to integer
 num1 = int(input("Enter first number: "))
 num2 = int(input("Enter second number: "))

 # Add the two numbers


 sum = num1 + num2

 # Print the result


 print("Sum:", sum)

 input() gets input as a string.


 int() converts the input string to an integer so we can do math.
Conditional statements

 if condition:
 # code block if condition is True
 else:
 # code block if condition is False
Example:
num = int(input("Enter a number: "))

if num > 0:
print("Positive number")
else:
print("Negative number or zero")
Function and object method calls

 What is a function?
 A function is a block of reusable code that performs a specific
task.
 It’s defined independently using the def keyword.
 It can accept input parameters and optionally return a result.
 Syntax:
def function_name(parameters):
# function body
return value # optional
 Syntax to call a function:
function_name(arguments)
Example:

def add(x, y):


return x + y

result = add(3, 4) # Function call with arguments 3 and 4


print(result) # Output: 7
 What is a class?
 A class in Python is a blueprint for creating objects (instances). It defines a
set of attributes (data) and methods (functions) that the created objects will
have.
 Syntax
 class ClassName:
# Class attribute (shared by all instances)
class_attribute = value

def __init__(self, param1, param2):


# Instance attributes
self.param1 = param1
self.param2 = param2

def method_name(self):
# Method that can use self to access instance attributes
pass
 class Employee:
 def __init__(self, name, salary):
 self.name = name # Employee's name
 self.salary = salary # Employee's salary

 def display(self):
 print(f"Employee: {self.name}, Salary: ${self.salary}")

 # Create employee objects


 emp1 = Employee("John", 50000)
 emp2 = Employee("Jane", 60000)

 # Call method to display details


 emp1.display() # Output: Employee: John, Salary: $50000
 emp2.display() # Output: Employee: Jane, Salary: $60000
Python For Loops

 Python For Loops are used for


iterating over a sequence like lists,
tuples, strings, and ranges.
 For loop allows you to apply the same
operation to every item within loop.
 Using For Loop avoid the need of
manually managing the index.
 For loop can iterate over any iterable
object, such as dictionary, list or any
custom iterators.
 Python For Loop Syntax
for var in iterable:
# statements
pass

Example:
 Python For Loop with String
 This code uses a for loop to iterate over a string and print each
character on a new line. The loop assigns each character to the
variable i and continues until all characters in the string have
been processed.
s = "Geeks"
for i in s:
print(i)
 Using range() with For Loop
 The range() function is commonly used with for loops to generate a
sequence of numbers. It can take one, two, or three arguments:

 range(stop): Generates numbers from 0 to stop-1.


 range(start, stop): Generates numbers from start to stop-1.
 range(start, stop, step): Generates numbers from start to stop-1,
incrementing by step.

for i in range(0, 10, 2):


print(i)
 Control Statements with For Loop
 Loop control statements change execution from their normal
sequence. When execution leaves a scope, all automatic objects
that were created in that scope are destroyed. Python supports the
following control statements.

 Continue with For Loop


 Python continue Statement returns the control to the beginning of
the loop.

# Prints all letters except 'e' and 's'


​for i in 'geeksforgeeks':
if i == 'e' or i == 's':
continue
print(i)
 Break with For Loop
 Python break statement brings control out of the loop.
 for i in 'geeksforgeeks':
 ​
 # break the loop as soon it sees 'e'
 # or 's'
 if i == 'e' or i == 's':
 break
 ​
 print(i)
Unit 2

Working with
Python Libraries
Contents
Introduction to key Libraries

 Numpy
 What is NumPy?
 NumPy is a Python library used for working with arrays.
 It also has functions for working in domain of linear algebra, fourier transform,
and matrices.
 NumPy was created in 2005 by Travis Oliphant. It is an open source project and
you can use it freely.
 NumPy stands for Numerical Python.
 NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.
 The array object in NumPy is called ndarray, it provides a lot of supporting
functions that make working with ndarray very easy.
 Arrays are very frequently used in data science, where speed and resources are
very important
 Installation of NumPy
 If you have Python and PIP already installed on a system, then
installation of NumPy is very easy.
 Install it using this command:
 C:\Users\Your Name>pip install numpy

 Import NumPy
 Once NumPy is installed, import it in your applications by adding the
import keyword:
 import numpy

 Example
 import numpy

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

print(arr)
 NumPy as np
 NumPy is usually imported under the np alias.

 alias: In Python alias are an alternate name for referring to the same thing.

 Create an alias with the as keyword while importing:

 import numpy as np
 Now the NumPy package can be referred to as np instead of numpy.

 Example
 import numpy as np

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

 print(arr)
 Data Types in NumPy
 NumPy has some extra data types, and refer to data types with one
character, like i for integers, u for unsigned integers etc.

 Below is a list of all data types in NumPy and the characters used to
represent them.
 i - integer
 b - boolean
 u - unsigned integer
 f - float
 c - complex float
 m - timedelta
 M - datetime
 O - object
 S - string
 U - unicode string
 V - fixed chunk of memory for other type ( void )
 Checking the Data Type of an Array
 The NumPy array object has a property called dtype that returns
the data type of the array:

 ExampleGet your own Python Server


 Get the data type of an array object:

 import numpy as np

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

 print(arr.dtype)
 Output: int64
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.
 Installation of Pandas
 If you have Python and PIP already installed on a system, then
installation of Pandas is very easy.
 Install it using this command:
 C:\Users\Your Name>pip install pandas
 Import Pandas
 Once Pandas is installed, import it in your applications by adding
the import keyword:

 import pandas
 import pandas

mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}

myvar = pandas.DataFrame(mydataset)

print(myvar)
 Output:
 cars passings
 0 BMW 3
 1 Volvo 7
 2 Ford 2
 What is a Series?
 A Pandas Series is like a column in a table.
 It is a one-dimensional array holding data of any type.
 Example
 Create a simple Pandas Series from a list:
 import pandas as pd

a = [1, 7, 2]

myvar = pd.Series(a)

print(myvar)

 Output

 0 1
 1 7
 2 2
 dtype: int64
 Create Labels
 With the index argument, you can name your own labels.
 Example
 Create your own labels:

 import pandas as pd
 a = [1, 7, 2]
 myvar = pd.Series(a, index = ["x", "y", "z"])
 print(myvar)
 Output
 x 1
 y 7
 z 2
 dtype: int64
Pandas DataFrames
 A Pandas DataFrame is a 2 dimensional data structure, like a 2
dimensional array, or a table with rows and columns.

 import pandas as pd

 data = {
 "calories": [420, 380, 390],
 "duration": [50, 40, 45]
 }

 #load data into a DataFrame object:


 df = pd.DataFrame(data)

 print(df)
 Locate Row:Pandas use the loc attribute to return one or more
specified row(s)
 import pandas as pd
 data = {
 "calories": [420, 380, 390],
 "duration": [50, 40, 45]
 }
 #load data into a DataFrame object:
 df = pd.DataFrame(data)
 print(df.loc[0])
 Output:
 calories 420
 duration 50
 Name: 0, dtype: int64
 Load Files Into a DataFrame:If your data sets are stored in a
file, Pandas can load them into a DataFrame.

 import pandas as pd
 df = pd.read_csv('data.csv')
 print(df)

 Pandas - Analyzing DataFrames

 The head() method returns the headers and a specified number


of rows, starting from the top.
Matplotlib
 Matplotlib is a low level graph plotting library in python that
serves as a visualization utility.
 Matplotlib was created by John D. Hunter.
 Matplotlib is open source and we can use it freely.
 Matplotlib Pyplot:

 Most of the Matplotlib utilities lies under the pyplot submodule,


and are usually imported under the plt alias:
 import matplotlib.pyplot as plt
 Example
 Draw a line in a diagram from position (0,0) to position (250):
 import matplotlib.pyplot as plt
import numpy as np

xpoints = np.array([0, 6])


ypoints = np.array([0, 250])

plt.plot(xpoints, ypoints)
plt.show()
Seaborn
 Seaborn is a Python library for creating statistical graphics. It is built on top of
Matplotlib and integrates closely with pandas data structures. Seaborn aims to make
data visualization a central part of exploring and understanding datasets by providing
a high-level interface for drawing informative and attractive statistical plots.
 It offers a wide range of specialized plots for different types of data and analysis,
including:
 Relational plots: Scatter plots, line plots (e.g., scatterplot, lineplot).
 Distributional plots: Histograms, kernel density estimates, box plots, violin plots (e.g.,
histplot, kdeplot, boxplot, violinplot).
 Categorical plots: Bar plots, count plots, point plots (e.g., barplot, countplot,
pointplot).
 Multi-variate plots: Joint plots, pair plots for exploring relationships between multiple
variables (e.g., jointplot, pairplot).
 Importing:
 It is conventionally imported with the alias sns:
 import seaborn as sns
 import matplotlib.pyplot as plt
Scikit

 Scikit-learn, often referred to as sklearn, is an open-source Python library widely


used for machine learning and data mining tasks. It provides a comprehensive
set of tools for various machine learning algorithms and statistical modeling
techniques.
 Key features and capabilities of Scikit-learn:
 Algorithms:
 It includes a vast collection of algorithms for:
 Classification: Such as Support Vector Machines (SVMs), K-Nearest Neighbors
(KNN), Decision Trees, Random Forests, and Naive Bayes.
 Regression: Including Linear Regression, Ridge Regression, Lasso Regression,
and Support Vector Regression.
 Clustering: Like K-Means, DBSCAN, and Hierarchical Clustering.
 Dimensionality Reduction: Such as Principal Component Analysis (PCA) and
Linear Discriminant Analysis (LDA).
Data Structures In python

 Data Structures in Python refer to the ways of organizing and


storing data so that it can be accessed and worked with
efficiently. Python provides several built-in data structures, each
designed to handle different kinds of data and operations.
 Lists
 Tuples
 Sets
 Dictionaries
 Array
Lists
 A list is a built-in data structure in Python, used to store multiple elements.
 Creating Lists
 Lists are created using square brackets []:

 # Empty list
 x = []

 # List with initial values


 y = [1, 2, 3, 4, 5]

 # List with mixed types


 z = [1, "hello", 3.14, True]

 print(x)
 print(y)
 print(z)
 The list data type has some more methods. Here are all of the
methods of list objects:
 1. append()Adds a single element to the end of a list.
 Syntax:
 list.append(element)
 Example
 x = [1, 2, 3]
 x.append(4)
 print(x)
 # Output: [1, 2, 3, 4]
 2. sort():
 Sorts the list in-place (modifies the original list) in ascending
order by default.
 Syntax: list.sort()
 Example:
 x = [3, 1, 4, 2]
 x.sort()
 print(x)
 # Output: [1, 2, 3, 4]
3. Extend vs Append
 append(element) adds a single element to the end of the list.
 extend(iterable) adds all elements from another iterable (like
another list) to the end.
 Example:
 lst = [1, 2, 3]

 lst.append([4, 5])
 print(lst)
 # Output: [1, 2, 3, [4, 5]] ← Adds the whole list as one element

 lst = [1, 2, 3]
 lst.extend([4, 5])
 print(lst)
 # Output: [1, 2, 3, 4, 5] ← Adds elements individually
4. Insert
 insert(i, x) puts x at index i, pushing the rest to the right.
 Example:
 lst = [1, 3, 4]
 lst.insert(1, 2)
 print(lst)
 # Output: [1, 2, 3, 4]
Tuples

 A tuple is an ordered collection of items.


 It is immutable, meaning once created, you cannot change its
elements (no adding, removing, or modifying).
 Tuples can contain heterogeneous data types (different types in
one tuple).
 Tuples are written using parentheses ( ).
 Example:
 thistuple = ("apple", "banana", "cherry")
 print(thistuple)
Python Sets

 Sets are used to store multiple items in a single variable.

 Set Items
 Set items are unordered, unchangeable, and do not allow duplicate values.

 Unordered
 Unordered means that the items in a set do not have a defined order.
 Set items can appear in a different order every time you use them, and
cannot be referred to by index or key.
 Unchangeable
 Set items are unchangeable, meaning that we cannot change the items
after the set has been created.
 Duplicates Not Allowed
 Sets cannot have two items with the same value.
 Example:
 thisset = {"apple", "banana", "cherry", "apple"}
 print(thisset)
 Get the Length of a Set
 To determine how many items a set has, use the len() function.
 Example:
 thisset = {"apple", "banana", "cherry"}
 print(len(thisset))
 Output :3

 Set items can be of any data type


 Access Items
 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.
 Example 1
 Thisset = {“apple”, “banana”, “cherry”}
 For x in thisset:
 print(x)
 Example 2
 Check if "banana" is present in the set:
 thisset = {"apple", "banana", "cherry"}

 print("banana" in thisset)
 Add Items
 To add one item to a set use the add() method.

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

 thisset.add("orange")

 print(thisset)
Python Dictionaries

 Python dictionary is a data structure that stores the value


in key: value pairs. Values in a dictionary can be of any data
type and can be duplicated, whereas keys can't be repeated and
must be immutable.
 Example: Here, The data is stored in key:value pairs in
dictionaries, which makes it easier to find values.
 d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 print(d)
 Output
 {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 d1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 print(d1)

 # create dictionary using dict() constructor


 d2 = dict(a = "Geeks", b = "for", c = "Geeks")
 print(d2)
 Output
 {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 {'a': 'Geeks', 'b': 'for', 'c': 'Geeks'}
 Dictionary keys are case sensitive: the same name but different cases of
Key will be treated distinctly.
 Keys must be immutable: This means keys can be strings, numbers or
tuples but not lists.
 Keys must be unique: Duplicate keys are not allowed and any duplicate key
will overwrite the previous value.
 Dictionary internally uses Hashing. Hence, operations like search, insert,
delete can be performed in Constant Time.
 Accessing Dictionary Items
 We can access a value from a dictionary by using the key within
square brackets or get() method.
 Example
 d = { "name": "Prajjwal", 1: "Python", (1, 2): [1,2,4] }
 # Access using key
 print(d["name"])
 # Access using get()
 print(d.get("name"))

 Output
 Prajjwal
 Prajjwal
 Adding and Updating Dictionary Items
 We can add new key-value pairs or update existing keys by using
assignment.
 Example
 d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 # Adding a new key-value pair
 d["age"] = 22
 # Updating an existing value
 d[1] = "Python dict"
 print(d)

 Output
 {1: 'Python dict', 2: 'For', 3: 'Geeks', 'age': 22}
Removing Dictionary Items
 We can remove items from dictionary using the following methods:
 del: Removes an item by key.
 pop(): Removes an item by key and returns its value.
 clear(): Empties the dictionary.
 popitem(): Removes and returns the last key-value pair.
 d = {1: 'Geeks', 2: 'For', 3: 'Geeks', 'age':22}
 # Using del to remove an item
 del d["age"]
 print(d)
 # Using pop() to remove an item and return the value
 val = d.pop(1)
 print(val)
 # Using popitem to removes and returns
 # the last key-value pair.
 key, val = d.popitem()
 print(f"Key: {key}, Value: {val}")
 # Clear all items from the dictionary
 d.clear()
 print(d)
 Output
 {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 Geeks
 Key: 3, Value: Geeks

You might also like