Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Data Science Using Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 85

Data Science Using Python

Unit 1 - Introduction to data science

Unit 2 - Introduction to Python

Unit 3 - Control structures and Strings

Unit 4 - Functions and modules

Unit 5 - Classes & Objects

Unit 1 - Introduction to data science


Typically refers to a field of study that involves extracting insights and knowledge from structured
and unstructured data. It encompasses various techniques from statistics, mathematics, and
computer science to analyze and interpret complex data sets.

key aspects of an introduction to data science:


1. Definition: Data science involves collecting, processing, analyzing, visualizing, and interpreting
data to gain valuable insights, make informed decisions, and solve complex problems.

2. Key Components:

Statistics and Mathematics: Fundamental to understanding patterns and making predictions.

Programming Skills: Proficiency in languages like Python or R for data manipulation and analysis.

Data Cleaning and Preprocessing: Dealing with missing values, outliers, and ensuring data quality.

Machine Learning: Applying algorithms to create models for predictions and classifications.

Data Visualization: Creating meaningful visual representations of data to aid understanding.

Domain Knowledge: Understanding the context and specific needs of the industry or field.

3. Data Life Cycle:

Data Collection: Gathering relevant data from various sources.

Data Exploration: Understanding the structure and characteristics of the data.

Data Preprocessing: Cleaning, transforming, and organizing data for analysis.

Model Building: Applying statistical or machine learning models.

Model Evaluation: Assessing the performance and accuracy of the models.


Deployment: Implementing models in real-world scenarios.

Monitoring and Maintenance: Continuously assessing and updating models as needed.

4. Tools and Technologies:

Programming Languages: Python and R are widely used for data science.

Libraries and Frameworks: Pandas, NumPy, scikit-learn (for Python), and tidyverse (for R).

Visualization Tools: Matplotlib, Seaborn, Plotly, Tableau.

Machine Learning Libraries: TensorFlow, PyTorch, scikit-learn.

Database Technologies: SQL for relational databases, MongoDB for NoSQL.

5. Challenges in Data Science:

Data Quality: Ensuring accuracy and completeness of data.

Privacy and Ethics: Handling sensitive information responsibly.

Interpretability: Understanding and explaining complex models.

Scalability: Dealing with large datasets efficiently.

6.Applications of Data Science:

Business Analytics: Decision-making, forecasting, and market analysis.

Healthcare: Predictive modeling, patient outcomes, drug discovery.

Finance: Risk assessment, fraud detection, algorithmic trading.

Marketing: Customer segmentation, personalized recommendations.

Social Sciences: Studying human behavior, sentiment analysis.

7. Education and Resources:

Many universities and online platforms offer courses and degrees in data science.

Books, online tutorials, and open-source documentation are valuable learning resources.

Data science and its importance


Data Science is a multidisciplinary field that combines techniques from statistics, mathematics,
computer science, and domain-specific knowledge to extract meaningful insights and knowledge
from structured and unstructured data. It involves the use of various tools, algorithms, and
methodologies to analyze large volumes of data and derive actionable insights, predictions, and
solutions to complex problems. Here's a breakdown of the key aspects and importance of Data
Science:

Key Components of Data Science:

Data Collection and Storage:

Acquiring and gathering relevant data from various sources.

Storing and organizing data in structured or unstructured formats.

Data Cleaning and Preprocessing:

Handling missing values, outliers, and ensuring data quality.

Transforming and preparing data for analysis.

Exploratory Data Analysis (EDA):

Understanding the structure and characteristics of the data.

Identifying patterns, trends, and correlations.

Model Building and Machine Learning:

Applying statistical models and machine learning algorithms.

Creating predictive models for classification, regression, and clustering.

Data Visualization:

Creating visual representations of data to communicate insights effectively.

Using charts, graphs, and dashboards for clear presentation.

Interpretation and Communication:

Extracting actionable insights from analysis results.

Communicating findings to non-technical stakeholders.

Importance of Data Science:

Informed Decision-Making:

Helps organizations make data-driven decisions based on insights and evidence.

Reduces reliance on intuition and gut feeling.


Predictive Analytics:

Enables the prediction of future trends, behaviors, and outcomes.

Facilitates proactive decision-making.

Efficient Operations:

Improves efficiency and productivity by identifying optimization opportunities.

Helps in resource allocation and process improvement.

Business Innovation:

Drives innovation by uncovering new opportunities and business models.

Facilitates the development of new products and services.

Risk Management:

Identifies and assesses risks in various domains, including finance and healthcare.

Supports the development of risk mitigation strategies.

Personalization:

Facilitates personalized user experiences in areas like marketing and recommendation systems.

Enhances customer satisfaction and engagement.

Healthcare and Research:

Aids in medical research, drug discovery, and personalized medicine.

Enhances patient care through predictive analytics.

Fraud Detection and Security:

Detects anomalies and patterns indicative of fraudulent activities.

Enhances security measures in various industries.

Competitive Advantage:

Provides a competitive edge by leveraging data for strategic decision-making.

Enables organizations to adapt to changing market conditions.

Social Impact:

Contributes to social good through applications in areas like public health and disaster response.

Supports evidence-based policymaking.


In summary, Data Science plays a crucial role in today's data-driven world, empowering organizations
and individuals to extract valuable insights, make informed decisions, and drive innovation across
various domains. Its importance is expected to grow as the volume and complexity of data continue
to increase.

Advantages of Data Science


Data Science offers numerous advantages across various domains, contributing to informed decision-
making, innovation, and efficiency. Here are some key advantages of Data Science:

Informed Decision-Making:

Provides data-driven insights for making informed and evidence-based decisions.

Reduces reliance on intuition and gut feeling.

Predictive Analytics:

Enables the prediction of future trends, behaviors, and outcomes.

Supports proactive decision-making and risk management.

Operational Efficiency:

Identifies areas for optimization and efficiency improvement.

Enhances resource allocation and process streamlining.

Innovation and New Opportunities:

Drives innovation by uncovering new business opportunities and models.

Supports the development of new products and services.

Personalization:

Facilitates personalized user experiences in marketing, content recommendation, and e-commerce.

Improves customer satisfaction and engagement.

Fraud Detection and Security:

Detects anomalies and patterns indicative of fraudulent activities.

Enhances security measures in finance, e-commerce, and other industries.

Healthcare Advancements:

Aids in medical research, drug discovery, and personalized medicine.

Improves patient care through predictive analytics and disease modeling.


Competitive Advantage:

Provides a competitive edge by leveraging data for strategic decision-making.

Allows organizations to adapt quickly to changing market conditions.

Customer Understanding:

Improves understanding of customer behavior and preferences.

Facilitates targeted marketing and customer relationship management.

Optimized Marketing and Sales:

Enables targeted advertising and marketing campaigns.

Improves sales forecasting and customer acquisition strategies.

Supply Chain Optimization:

Enhances supply chain management through demand forecasting and inventory optimization.

Reduces inefficiencies and costs.

Scientific Research and Discovery:

Accelerates scientific research by analyzing large datasets.

Supports discoveries in various fields, from astronomy to environmental science.

Social Impact:

Contributes to social good through applications in public health, education, and disaster response.

Supports evidence-based policymaking.

Continuous Improvement:

Allows for continuous monitoring and improvement of processes and models.

Facilitates adaptation to changing conditions.

Data-Driven Culture:

Encourages a culture of data-driven decision-making within organizations.

Fosters collaboration between data scientists and other departments.

Cost Reduction:

Identifies areas for cost reduction and resource optimization.

Reduces the risk of unnecessary expenditures.


Risk Management:

Identifies and assesses risks in various domains, including finance and cybersecurity.

Supports the development of risk mitigation strategies.

In summary, the advantages of Data Science are diverse and impactful, offering organizations and
individuals the tools and insights needed to thrive in a data-driven world.

The Process of Data Science


The process of Data Science involves a series of steps aimed at extracting meaningful insights and
knowledge from data. While specific methodologies may vary, the following is a common framework
for the Data Science process:

Define the Problem:

Clearly articulate the problem or question that needs to be addressed.

Understand the objectives and goals of the analysis.

Data Collection:

Identify and collect relevant data from various sources.

Ensure data quality and assess the suitability of the data for analysis.

Data Cleaning and Preprocessing:

Handle missing values, outliers, and errors in the data.

Standardize and transform data to make it suitable for analysis.

Exploratory Data Analysis (EDA):

Explore and visualize the data to understand patterns, relationships, and potential insights.

Use statistical methods to summarize and describe the main characteristics of the data.

Feature Engineering:

Create new features or transform existing ones to enhance the performance of machine learning
models.

Select relevant features that contribute to the predictive power of the model.

Model Building:

Select appropriate machine learning algorithms based on the nature of the problem (classification,
regression, clustering, etc.).
Split the data into training and testing sets for model training and evaluation.

Model Training:

Train the chosen machine learning model using the training dataset.

Optimize model parameters for better performance.

Model Evaluation:

Assess the performance of the model using the testing dataset.

Use metrics such as accuracy, precision, recall, and F1 score to evaluate model effectiveness.

Model Interpretation:

Understand and interpret the results of the model.

Identify key features influencing the model's predictions.

Deployment:

Implement the model into a real-world environment for use in decision-making.

Ensure the integration of the model with existing systems.

Monitoring and Maintenance:

Continuously monitor the performance of the deployed model.

Update the model as needed to adapt to changes in data patterns or business requirements.

Communication of Results:

Clearly communicate the findings and insights to stakeholders.

Create visualizations and reports to aid in understanding.

Iterative Process:

Data Science is often an iterative process, involving revisiting and refining steps based on new
insights or changing requirements.

Feedback loops with stakeholders and domain experts are essential.

Ethical Considerations:

Consider ethical implications related to privacy, bias, and fairness in data analysis.

Ensure compliance with regulations and ethical standards.

Documentation:

Document the entire process, including data sources, methodologies, and findings.
Facilitate knowledge transfer and replication of the analysis.

It's important to note that these steps are not strictly linear and may involve going back and forth
based on the evolving understanding of the data and problem at hand. The iterative nature of Data
Science allows for continuous improvement and refinement throughout the analysis process.

Responsibilities of a Data scientist


The role of a Data Scientist involves a wide range of responsibilities, as they play a crucial role in
extracting insights and knowledge from data to support decision-making. The specific duties can vary
depending on the organization, industry, and the stage of the data science process. Here are
common responsibilities of a Data Scientist:

Problem Definition:

Collaborate with stakeholders to clearly define business problems or research questions that can be
addressed through data analysis.

Understand the goals and objectives of the analysis.

Data Collection and Integration:

Identify and collect relevant data from various sources, both internal and external.

Integrate and clean data to ensure quality and consistency.

Data Exploration and Analysis:

Conduct exploratory data analysis (EDA) to understand the structure, patterns, and characteristics of
the data.

Apply statistical methods and visualization techniques to gain insights.

Feature Engineering:

Create new features or transform existing ones to enhance the performance of machine learning
models.

Select features that contribute to the predictive power of the model.

Model Development:

Select appropriate machine learning algorithms based on the nature of the problem (classification,
regression, clustering, etc.).

Build and train predictive models using the selected algorithms.

Model Evaluation and Validation:

Assess the performance of machine learning models using appropriate metrics.


Validate models using testing datasets and iteratively refine models for better accuracy.

Model Deployment:

Implement models into production environments, ensuring seamless integration with existing
systems.

Collaborate with IT and engineering teams for deployment.

Monitoring and Maintenance:

Continuously monitor the performance of deployed models.

Update models as needed to adapt to changes in data patterns or business requirements.

Communication of Results:

Communicate findings and insights to both technical and non-technical stakeholders.

Create reports, dashboards, and visualizations to convey complex information.

Collaboration with Cross-Functional Teams:

Collaborate with domain experts, business analysts, and decision-makers to understand the context
of the analysis.

Work closely with IT, engineering, and other departments for successful project implementation.

Continuous Learning:

Stay current with advancements in data science, machine learning, and relevant technologies.

Attend conferences, participate in training, and engage in professional development.

Ethical Considerations:

Consider ethical implications related to privacy, bias, and fairness in data analysis.

Ensure compliance with regulations and ethical standards.

Documentation:

Document methodologies, assumptions, and procedures used in the analysis.

Provide documentation for reproducibility and knowledge transfer.

Educational Outreach:

Educate colleagues and stakeholders on the value of data-driven decision-making.

Conduct training sessions or workshops to share knowledge within the organization.


Project Management:

Manage timelines, resources, and deliverables for data science projects.

Prioritize tasks based on business impact and urgency.

The responsibilities of a Data Scientist often require a combination of technical skills, domain
expertise, and effective communication to ensure that data-driven insights contribute to
organizational success.

Qualifications of Data Scientist


Data scientists typically possess a combination of education, technical skills, and domain expertise.
While specific qualifications can vary based on the industry and company, here are common
qualifications and skills required for a career in data science:

Education:

Educational Background:

A bachelor's degree in a relevant field such as Computer Science, Statistics, Mathematics, Physics,
Engineering, or a related discipline.

Many data scientists hold advanced degrees (master's or Ph.D.) in data science, machine learning,
statistics, or a related field.

Specialized Courses and Certifications:

Completion of specialized courses or certifications in data science, machine learning, and statistical
analysis can enhance qualifications.

Certifications from recognized organizations, such as Coursera, edX, or professional associations like
the Data Science Council of America (DASCA), are valuable.

Technical Skills:

Programming Languages:

Proficiency in programming languages such as Python and/or R is crucial for data manipulation,
analysis, and modeling.

Familiarity with SQL for database queries.

Statistical Analysis and Mathematics:

Strong foundation in statistics and mathematics for data analysis, hypothesis testing, and predictive
modeling.
Machine Learning:

Knowledge of machine learning algorithms and frameworks (e.g., scikit-learn, TensorFlow, PyTorch).

Experience in applying supervised and unsupervised learning techniques.

Data Wrangling and Cleaning:

Skills in data cleaning, preprocessing, and manipulation using tools like Pandas in Python.

Data Visualization:

Proficiency in data visualization tools (e.g., Matplotlib, Seaborn, Plotly) to present findings in a clear
and concise manner.

Big Data Technologies:

Familiarity with big data technologies, such as Hadoop and Spark, for handling large-scale datasets.

Soft Skills:

Analytical Thinking:

Strong analytical and critical-thinking skills to approach complex problems.

Communication Skills:

Effective communication skills to convey technical findings to non-technical stakeholders.

Collaboration:

Ability to collaborate with cross-functional teams, including domain experts, engineers, and business
leaders.

Domain Expertise:

Industry Knowledge:

Understanding of the specific industry or domain in which the data scientist works, allowing for more
relevant and impactful analyses.

Additional Qualifications:

Coding Practices:

Adherence to best coding practices, version control, and familiarity with software development
methodologies.

Problem-Solving:

Strong problem-solving skills and the ability to think creatively about data-related challenges.
Continuous Learning:

Commitment to staying updated with the latest developments in data science and related
technologies.

Ethical Considerations:

Awareness of ethical considerations related to data privacy, bias, and responsible use of data.

Project Management:

Basic project management skills to effectively plan and execute data science projects.

It's important to note that the field of data science is dynamic, and individuals may continue to build
on their qualifications throughout their careers. Real-world experience through internships, personal
projects, or contributions to open-source projects can also be valuable in showcasing practical skills.
Employers may prioritize a combination of education, technical proficiency, and relevant experience
when hiring data scientists.

why to use python for data science

Python is a widely adopted and popular programming language in the field of data science for
several compelling reasons:

Ease of Learning and Readability:

Python has a simple and readable syntax, making it accessible for beginners and easy to understand
for experienced programmers.

Its readability helps in writing clean and concise code, facilitating collaboration among data science
teams.

Extensive Libraries and Frameworks:

Python has a rich ecosystem of libraries and frameworks specifically designed for data science and
machine learning, including:

NumPy and Pandas: For data manipulation and analysis.

Matplotlib, Seaborn, and Plotly: For data visualization.

scikit-learn: For machine learning algorithms.

TensorFlow and PyTorch: For deep learning.


Community and Support:

Python has a large and active community of developers and data scientists.

The community contributes to a wealth of resources, tutorials, and forums, making it easy to find
help and share knowledge.

Versatility:

Python is a versatile language that can be used for a wide range of tasks beyond data science,
including web development, automation, scripting, and more.

This versatility allows data scientists to integrate their work into larger applications seamlessly.

Open Source:

Python is an open-source language with a permissive license, fostering collaboration and sharing of
tools and libraries within the community.

This open nature facilitates innovation and the development of a diverse set of tools.

Integration Capabilities:

Python can easily integrate with other languages and technologies, allowing data scientists to use
specialized libraries or tools when needed.

Integration with databases, APIs, and other data sources is seamless.

Data Visualization:

Python offers multiple powerful libraries for data visualization, such as Matplotlib, Seaborn, and
Plotly, allowing data scientists to create compelling and informative visualizations.

Community-Driven Packages:

The Python Package Index (PyPI) hosts a vast collection of community-driven packages and modules.

Data scientists can leverage these packages to extend Python's functionality and address specific
data science challenges.

Large Corporations Adopting Python:

Many large corporations and tech companies have embraced Python for data science and machine
learning, contributing to its widespread adoption.

This industry acceptance has led to increased support and resources for Python in the data science
ecosystem.

Job Market Demand:

Python is one of the most sought-after skills in the job market, especially in the field of data science.

Many data science job postings specifically mention Python as a required or preferred skill.
In summary, Python's simplicity, extensive libraries, community support, and versatility make it a
preferred choice for data scientists. Its popularity continues to grow as it remains at the forefront of
data science and machine learning developments.
Unit 2 - Introduction to Python

What is Python
Python is a high-level, general-purpose programming language known for its readability, simplicity,
and versatility. It was created by Guido van Rossum and first released in 1991. Python is designed to
be easy to understand and write, with a clean and straightforward syntax that emphasizes code
readability.

Key features and characteristics of Python include:

Readable and Simple Syntax:

Python uses a clear and readable syntax, making it easy for beginners to learn and write code.

The language emphasizes the use of indentation for code blocks, enhancing code readability.

Interpreted and High-Level:

Python is an interpreted language, meaning that it is executed line by line by an interpreter, rather
than being compiled into machine code.

It is considered a high-level language because of its abstraction from machine-level details.

Versatility and General-Purpose:

Python is a general-purpose programming language, suitable for a wide range of applications,


including web development, data science, machine learning, artificial intelligence, automation,
scripting, and more.

Large Standard Library:

Python comes with a comprehensive standard library that includes modules and packages for various
tasks, simplifying development by providing pre-built functionality.

Dynamically Typed:

Python is dynamically typed, meaning that variable types are determined at runtime. This allows for
flexibility but requires careful attention to variable types in code.

Object-Oriented Programming (OOP):

Python supports object-oriented programming principles, allowing developers to create and use
classes and objects.
Extensive Ecosystem:

The Python ecosystem includes a vast collection of third-party libraries and frameworks that extend
its functionality, such as Django for web development, NumPy for scientific computing, and
TensorFlow for machine learning.

Community and Documentation:

Python has a large and active community of developers who contribute to its growth and
development.

Extensive documentation and tutorials are available, making it easy for developers to find resources
and support.

Cross-Platform Compatibility:

Python is platform-independent, meaning that Python code can run on various operating systems
without modification.

Open Source:

Python is open source, and its source code is freely available. This encourages collaboration and the
development of a wide range of applications and tools.

Python's popularity has grown significantly over the years, and it is widely used in industry,
academia, and the open-source community. Its versatility, ease of use, and strong community
support make it a popular choice for developers worldwide.

Features of Python
Python is a versatile and powerful programming language that offers a wide range of features. Here
are some key features of Python:

Readability and Simplicity:

Python's syntax is designed to be clear and readable, emphasizing code readability and reducing the
cost of program maintenance.

The use of indentation for code blocks enforces a clean and consistent coding style.

Interpreted Language:

Python is an interpreted language, allowing for easy and quick development. Code is executed line by
line by the Python interpreter.

Versatility and General-Purpose:

Python is a general-purpose language suitable for various applications, including web development,
data science, machine learning, automation, scripting, and more.
High-Level Language:

Python abstracts many low-level details, making it easier for developers to focus on solving problems
without dealing with complex memory management.

Dynamically Typed:

Python is dynamically typed, meaning that variable types are determined at runtime. This offers
flexibility but requires careful attention to variable types.

Object-Oriented Programming (OOP):

Python supports object-oriented programming principles, allowing developers to use classes,


objects, and inheritance.

Large Standard Library:

Python comes with a comprehensive standard library that includes modules and packages for various
tasks, reducing the need for external dependencies.

Community and Documentation:

Python has a large and active community of developers who contribute to its growth and
development.

Extensive documentation and online resources make it easy for developers to find support and learn
Python.

Cross-Platform Compatibility:

Python code is platform-independent, meaning it can run on various operating systems without
modification.

Extensive Ecosystem:

The Python ecosystem includes a rich collection of third-party libraries and frameworks, such as
Django for web development, NumPy for scientific computing, and TensorFlow for machine learning.

Integration Capabilities:

Python can easily integrate with other languages and technologies, making it suitable for
interoperability with existing systems and tools.

Open Source:

Python is open source, and its source code is freely available. This fosters collaboration, community
contributions, and the development of a wide range of applications and tools.

Rapid Prototyping:

Python's simplicity and readability make it an excellent choice for rapid prototyping and
development.
Support for Modular Programming:

Python supports modular programming, allowing developers to break down large programs into
smaller, manageable modules.

High-Level Data Structures:

Python provides built-in high-level data structures like lists, dictionaries, and sets, simplifying
complex data manipulations.

Dynamic Memory Management:

Python employs automatic memory management, handling memory allocation and deallocation,
reducing the risk of memory leaks.

These features collectively contribute to Python's popularity and make it a favored choice for a wide
range of applications and industries. The language continues to evolve, with the Python community
actively contributing to its growth and improvement.

History of python
Python, a high-level programming language, has a rich history that dates back to the late 1980s. Here
is a timeline highlighting key events in the history of Python:

Late 1980s: Origin of Python:

Python was conceived by Guido van Rossum, a Dutch programmer, in the late 1980s. The
development started as a Christmas project over the holidays in December 1989.

February 1991: Python 0.9.0 Released:

The first official release, Python 0.9.0, was released on February 20, 1991. This version included
many fundamental features of the language.

1994: Python 1.0 Released:

Python 1.0 was released on January 26, 1994. It included new features such as lambda, map, filter,
and reduce.

2000: Python 2.0 Released:

Python 2.0, released on October 16, 2000, introduced list comprehensions and garbage collection.

2008: Python 3.0 (Python 3000 or "Py3k") Released:

Python 3.0, a significant and backward-incompatible release, was released on December 3, 2008. It
aimed to clean up and simplify the language, addressing various design issues.
2010s: Coexistence of Python 2 and Python 3:

The transition from Python 2 to Python 3 was gradual. Both versions coexisted for several years, with
Python 2 reaching its end of life on January 1, 2020.

2018: Python Software Foundation (PSF) Adopts Governance Model:

In 2018, the Python Software Foundation adopted a new governance model called PEP 8000, which
aimed to provide a more inclusive and transparent decision-making process.

2020: Python 2 End of Life:

Python 2 officially reached its end of life on January 1, 2020. This marked the end of official support
and updates for Python 2, encouraging the community to transition to Python 3.

2020: Python 3.9 Released:

Python 3.9, released on October 5, 2020, included new features and optimizations, continuing the
evolution of the language.

2021: Continued Development and Community Growth:

Python continues to be actively developed, with regular releases introducing new features,
improvements, and optimizations.

The Python community remains vibrant, with a large number of contributors, extensive
documentation, and a wealth of third-party libraries and frameworks.

Python's success can be attributed to its simplicity, readability, versatility, and a strong and active
community that contributes to its ongoing development and growth. The language is widely used in
various domains, including web development, data science, machine learning, scientific computing,
and more.

Writing and Executing the python program


Writing and executing a Python program involves the following steps:

Writing a Python Program:

Choose a Text Editor or Integrated Development Environment (IDE):

You can write Python code using a simple text editor like Notepad (on Windows) or TextEdit (on
macOS) or use a more feature-rich integrated development environment (IDE) like VSCode, PyCharm,
or Jupyter Notebook.

Write Your Python Code:

Open your chosen editor or IDE and write your Python code. A simple "Hello, World!" program is a
common starting point:

print("Hello, World!")
Save Your Python File:

Save your Python code with a .py extension. For example, you might save it as hello.py.

Executing a Python Program:

Using the Command Line or Terminal:

Open a Command Prompt (Windows) or Terminal (macOS/Linux):

Navigate to the directory where your Python file is saved.

Run the Python Interpreter:

Type python or python3 (depending on your system) followed by the name of your Python file and
press Enter:

bash

python hello.py

note: If you are using Python 3, replace python with python3.

Using an Integrated Development Environment (IDE):

Open Your IDE:

Open your chosen IDE and load your Python file.

Run the Program:

Look for a "Run" or "Execute" button in the IDE, often represented by a play icon.

Click the button to run your Python program.

Using Jupyter Notebook:

Open Jupyter Notebook:

If you are using Jupyter Notebook, open your notebook file (with a .ipynb extension).

Run Cells:

Use the "Run" button or press Shift+Enter to run the cells containing your Python code.

Output:

Regardless of the method used to execute your Python program, you should see the output in the
command line, terminal, or IDE console. In the case of the "Hello, World!" program, the output
would be:

Output:

Hello, World!
Basic syntax
The basic syntax of Python is designed to be simple and readable. Here are some fundamental
elements of Python syntax:

1. Indentation:

Python uses indentation to define blocks of code. Indentation is crucial for determining the scope of
functions, loops, and conditional statements.

Typically, four spaces are used for each level of indentation.

if x > 0:

print("Positive number")

else:

print("Non-positive number")

2. Variables:

Variables are used to store data. You can assign values to variables using the = operator.

x = 10

name = "John"

3. Data Types:

Python has several built-in data types, including integers, floats, strings, booleans, lists, tuples, and
dictionaries.

num = 42 # integer

pi = 3.14 # float

message = "Hello" # string

is_true = True # boolean

my_list = [1, 2, 3] # list

4. Print Statement:

The print() function is used to output data to the console.

print("Hello, World!")
5. Comments:

Comments start with the # symbol and are used for adding explanations within the code.

# This is a comment

6. Conditional Statements:

if, elif (else if), and else are used for conditional execution.

if x > 0:

print("Positive number")

elif x == 0:

print("Zero")

else:

print("Negative number")

7. Loops:

for and while loops are used for iteration.

for i in range(5):

print(i)

while x > 0:

print(x)

x -= 1

8. Functions:

Functions are defined using the def keyword.

def greet(name):

print("Hello, " + name + "!")

greet("Alice")
9. Lists:

Lists are ordered, mutable sequences.

my_list = [1, 2, 3]

10. Dictionaries:

Dictionaries are unordered collections of key-value pairs.

my_dict = {'name': 'John', 'age': 25}

11. Tuples:

Tuples are ordered, immutable sequences.

my_tuple = (1, 2, 3)

These are some of the basic elements of Python syntax. As you progress, you'll encounter more
advanced concepts and features that make Python a powerful and versatile programming language.

variables
In Python, variables are used to store and manage data. Here are some key points about variables in
Python:

Variable Assignment:

Variables are created using the assignment operator =. You assign a value to a variable like this:

x = 10

name = "John"

pi = 3.14

is_true = True

Variable Naming Rules:

Variable names can contain letters (a-z, A-Z), numbers (0-9), and underscores (_).

Variable names cannot start with a number.

Python is case-sensitive, so name and Name would be different variables.

Choose meaningful and descriptive variable names for better code readability.
Data Types:

Python is dynamically typed, meaning you don't need to explicitly declare the data type of a variable.
The interpreter infers the type based on the assigned value:

x = 10 # Integer

name = "John" # String

pi = 3.14 # Float

is_true = True # Boolean

Reassigning Variables:

You can change the value of a variable by assigning a new value to it:

x=5

print(x) # Output: 5

x = "Hello"

print(x) # Output: Hello

Multiple Assignment:

You can assign values to multiple variables in a single line:

a, b, c = 1, 2, 3

Variable Naming Conventions:

Use descriptive and meaningful names (e.g., total_amount instead of t).

Follow the snake_case convention for variable names (e.g., my_variable).

Constants:

While Python doesn't have true constants, naming conventions in uppercase are often used to
indicate that a variable is intended to be a constant:

PI = 3.14

GRAVITY = 9.8

Deleting Variables:

You can use the del statement to delete a variable:

x = 10

del x
# Trying to access x now would result in an error

Understanding and using variables effectively is fundamental to programming in Python. They serve
as containers for storing and manipulating data throughout your code.

Keywords
In Python, keywords are reserved words that have special meanings and cannot be used as
identifiers (names for variables, functions, etc.). These keywords define the syntax and structure of
the language. Here is a list of Python keywords:

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise

These keywords are case-sensitive, meaning that True and true are different and have distinct
meanings in Python. It's important to avoid using these words as variable names or identifiers in your
code to prevent conflicts and unexpected behavior.

Datatypes in python
Python supports several built-in data types that allow you to represent and work with different kinds
of data. Here are some of the fundamental data types in Python:

Numeric Types:

int: Integer type represents whole numbers.

x=5

float: Float type represents floating-point numbers (decimal numbers).

pi = 3.14
complex: Complex type represents complex numbers.

complex_num = 2 + 3j

Text Type:

str: String type represents textual data. Strings can be enclosed in single or double quotes.

name = "John"

Boolean Type:

bool: Boolean type represents truth values, either True or False.

is_true = True

Sequence Types:

list: List type represents ordered, mutable sequences.

my_list = [1, 2, 3]

tuple: Tuple type represents ordered, immutable sequences.

my_tuple = (1, 2, 3)

range: Range type represents an immutable sequence of numbers.

my_range = range(5)

Set Types:

set: Set type represents an unordered collection of unique elements.

my_set = {1, 2, 3}

frozenset: Frozenset type represents an immutable set.

frozen_set = frozenset({1, 2, 3})

Mapping Type:

dict: Dictionary type represents key-value pairs, where keys are unique.

my_dict = {'name': 'John', 'age': 25}

None Type:

NoneType: The None type represents the absence of a value or a null value.

empty_variable = None
Binary Types:

bytes: Bytes type represents a sequence of bytes.

binary_data = b'hello'

bytearray: Bytearray type represents a mutable sequence of bytes.

mutable_binary_data = bytearray(b'hello')

memoryview: Memoryview type provides a view of the memory of an object.

memory_view = memoryview(b'hello')

These are some of the basic built-in data types in Python.

Operators
Operators in Python are special symbols or keywords that perform operations on operands. They are
used to manipulate data and perform various computations. Here are some common types of
operators in Python:

1. Arithmetic Operators:

Used for basic arithmetic operations.

+ # Addition

- # Subtraction

* # Multiplication

/ # Division

% # Modulus (remainder)

// # Floor Division

** # Exponentiation

2. Comparison Operators:

Used to compare values.

== # Equal to

!= # Not equal to

< # Less than

> # Greater than

<= # Less than or equal to


>= # Greater than or equal to

3. Logical Operators:

Used to perform logical operations.

and # Logical AND

or # Logical OR

not # Logical NOT

4. Assignment Operators:

Used to assign values to variables.

= # Assignment

+= # Increment and assign

-= # Decrement and assign

*= # Multiply and assign

/= # Divide and assign

%= # Modulus and assign

//= # Floor division and assign

**= # Exponentiation and assign

5. Identity Operators:

Used to compare the memory location of two objects.

is # True if the operands are identical objects

is not # True if the operands are not identical objects

6. Membership Operators:

Used to test whether a value is a member of a sequence.

in # True if a value is found in the sequence

not in # True if a value is not found in the sequence


7. Bitwise Operators:

Used for bitwise operations on integers.

& # Bitwise AND

| # Bitwise OR

^ # Bitwise XOR

~ # Bitwise NOT

<< # Left shift

>> # Right shift

8. Unary Operators:

Operate on a single operand.

+ # Unary plus (positive)

- # Unary minus (negation)

~ # Bitwise NOT

These operators play a crucial role in performing various operations in Python.

Indentation
In Python, indentation is a fundamental aspect of the language syntax. Unlike many programming
languages that use braces or keywords to denote code blocks, Python uses indentation to indicate
the grouping of statements. Here are the key points regarding indentation in Python:

Whitespace Matters:

Python uses spaces or tabs at the beginning of a line to define the level of indentation.

Consistent indentation is crucial for grouping statements together in blocks.

Indentation Levels:

Statements with the same level of indentation are considered part of the same block.

Subsequent levels of indentation represent nested blocks.

Colon (:) Indicates Indentation:

A colon : at the end of a control statement (like if, else, for, while, etc.) signals the start of an
indented code block.
if condition:

# Code block with indentation

statement1

statement2

Mixing Tabs and Spaces:

It is recommended to use spaces for indentation consistently. Mixing tabs and spaces can lead to
indentation errors.

Recommended Indentation:

The Python community conventionally uses four spaces for each level of indentation. This is
recommended in the official PEP 8 style guide.

def example_function():

if x > 0:

print("Positive number")

else:

print("Non-positive number")

End of Indentation:

Dedentation (reducing indentation) indicates the end of a code block.

if condition:

# Indented block

statement1

statement2

# Dedentation indicates the end of the block

next_statement

Indentation in Loops and Functions:

Indentation is used consistently in loops, function definitions, and other control flow structures.

for item in iterable:

# Indented block

statement1
statement2

def my_function():

# Indented block

statement1

statement2

Blank Lines and Whitespace:

Blank lines are allowed and do not affect indentation. However, the level of indentation must remain
consistent within a block.

if condition:

statement1

# Blank lines are allowed

statement2

Conditional statements
Conditional statements in Python are used to control the flow of the program based on specified
conditions. The key conditional statements in Python are:

1. if Statement:

The if statement is used to execute a block of code only if a specified condition is true.

if condition:

# Code to be executed if the condition is true

statement1

statement2

2. if-else Statement:

The if-else statement allows the program to execute one block of code if a condition is true and
another block if the condition is false.

if condition:

# Code to be executed if the condition is true


statement1

statement2

else:

# Code to be executed if the condition is false

statement3

statement4

3. if-elif-else Statement:

The if-elif-else statement is an extension of the if-else statement. It allows you to check multiple
conditions sequentially.

if condition1:

# Code to be executed if condition1 is true

statement1

statement2

elif condition2:

# Code to be executed if condition2 is true

statement3

statement4

else:

# Code to be executed if none of the conditions are true

statement5

statement6

Example:

x = 10

if x > 0:

print("Positive number")

elif x == 0:

print("Zero")

else:
print("Negative number")

4. Nested if Statements:

You can nest if statements within each other to create more complex conditional structures.

if condition1:

if condition2:

# Code to be executed if both condition1 and condition2 are true

statement1

else:

# Code to be executed if condition1 is true but condition2 is false

statement2

else:

# Code to be executed if condition1 is false

statement3

These conditional statements allow you to create flexible and dynamic programs by making decisions
based on the evaluation of conditions. The indentation in Python plays a crucial role in defining the
scope of each block of code within these statements.

Looping Statements
Looping statements in Python allow you to execute a block of code repeatedly. The primary looping
statements are:

1. for Loop:

The for loop is used for iterating over a sequence (that is either a list, tuple, dictionary, string, or
range).

for variable in sequence:

# Code to be executed in each iteration

statement1

statement2

Example:

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


for fruit in fruits:

print(fruit)

2. while Loop:

The while loop is used to repeatedly execute a block of code as long as a specified condition is true.

while condition:

# Code to be executed in each iteration

statement1

statement2

Example:

count = 0

while count < 5:

print(count)

count += 1

3. break Statement:

The break statement is used to exit the loop prematurely based on a certain condition.

for variable in sequence:

if condition:

# Code to be executed

break

Example:

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

for fruit in fruits:

if fruit == "banana":

break

print(fruit)

4. continue Statement:

The continue statement is used to skip the rest of the code inside a loop for the current iteration and
move to the next iteration.
for variable in sequence:

if condition:

# Code to be skipped

continue

# Code to be executed for other cases

statement1

statement2

Example:

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

for fruit in fruits:

if fruit == "banana":

continue

print(fruit)

In this example, when the loop encounters the "banana" element, the continue statement skips the
print(fruit) statement for that iteration and moves to the next iteration.

5. else Clause with Loops:

Both for and while loops can have an optional else clause, which is executed when the loop condition
becomes false.

for variable in sequence:

# Code to be executed in each iteration

statement1

statement2

else:

# Code to be executed when the loop condition becomes false

statement_after_loop

while condition:

# Code to be executed in each iteration

statement1
statement2

else:

# Code to be executed when the loop condition becomes false

statement_after_loop

Example:

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

for fruit in fruits:

print(fruit)

else:

print("No more fruits")

In this example, after iterating through all the fruits, the else block is executed because there are no
more items in the sequence.

These looping statements provide flexibility for iterating over sequences and performing repetitive
tasks in Python. Understanding how to use loops effectively is essential for writing efficient and
readable code.

Pass
In Python, pass is a null statement or a no-operation statement. It serves as a placeholder where
syntactically some code is required, but no action is desired or necessary. It is often used in situations
where the syntax demands a statement, but you don't want to execute any code. For example:

if x < 0:

print("Negative number")

else:

pass # No action needed for non-negative numbers

Here, the pass statement is used as a placeholder in the else block. Without it, there would be a
syntax error, as Python expects an indented block of code following the else keyword. The pass
statement allows the program to run without any actual code execution in that block.

Similarly, you might use pass when defining a function, class, or loop that needs to have a body, but
you're not ready to implement it yet:
def my_function():

pass # Placeholder for the function body

It's important to note that pass does not do anything at runtime. It's simply a way to satisfy the
Python syntax requirements when a statement is expected but no action is necessary.
Unit 3 - Control structures and Strings

Strings
In Python, strings are used to represent sequences of characters. Strings are one of the fundamental
data types, and they are immutable, meaning that once a string is created, it cannot be changed.
Here are some key features and operations related to strings in Python:

Creating Strings:

Strings can be created using single quotes (') or double quotes ("). Triple quotes (''' or """) are used
for multiline strings.

single_quoted_string = 'Hello, World!'

double_quoted_string = "Python is fun!"

multiline_string = '''This is a

multiline

string.'''

Accessing Characters:

Individual characters in a string can be accessed using indexing. Python uses 0-based indexing, so the
first character is at index 0.

my_string = "Python"

first_character = my_string[0] # 'P'

second_character = my_string[1] # 'y'

String Slicing:

You can extract a substring from a string using slicing.

my_string = "Python"

substring = my_string[1:4] # 'yth'

String Concatenation:

Strings can be concatenated using the + operator.

string1 = "Hello"

string2 = "World"
result = string1 + ", " + string2 # 'Hello, World'

String Repetition:

You can repeat a string using the * operator.

original_string = "abc"

repeated_string = original_string * 3 # 'abcabcabc'

String Methods:

Strings have numerous built-in methods for various operations, such as converting case, finding
substrings, splitting, joining, and more.

my_string = "Python is fun!"

uppercase_string = my_string.upper()

substring_index = my_string.find("is")

split_string = my_string.split(" ")

String Formatting:

String formatting allows you to create formatted strings by inserting values into placeholders.

name = "Alice"

age = 30

formatted_string = f"My name is {name} and I am {age} years old."

Escape Characters:

Escape characters are used to represent special characters within a string.

escaped_string = "This is a newline character.\nAnd this is a tab character:\tSee?"

Raw Strings:

Raw strings are specified by prefixing the string literal with an 'r' or 'R', and they treat backslashes as
literal characters.

raw_string = r"This is a raw string with \n newlines and \t tabs."

These are some of the basic operations and features related to strings in Python. Strings are versatile
and play a crucial role in various programming tasks.
Basic string operations

Strings in Python support various operations that allow you to manipulate and work with them. Here
are some basic operations and functions related to strings in Python:

1. Concatenation:

You can concatenate two or more strings using the + operator.

str1 = "Hello"

str2 = "World"

result = str1 + " " + str2 # "Hello World"

2. Repetition:

You can repeat a string using the * operator.

original_str = "abc"

repeated_str = original_str * 3 # "abcabcabc"

3. Indexing:

Access individual characters in a string using indexing. Python uses 0-based indexing.

my_str = "Python"

first_char = my_str[0] # 'P'

second_char = my_str[1] # 'y'

4. Slicing:

Extract a substring using slicing.

my_str = "Python"

substring = my_str[1:4] # "yth"

5. Length:

Find the length of a string using the len() function.

my_str = "Python"

length = len(my_str) # 6

6. Conversion:

Convert the case of a string.


my_str = "Python"

uppercase_str = my_str.upper() # "PYTHON"

lowercase_str = my_str.lower() # "python"

7. Find and Replace:

Find the index of a substring and replace occurrences.

my_str = "Python is fun!"

index = my_str.find("is") # 7

new_str = my_str.replace("fun", "awesome") # "Python is awesome!"

8. Strip:

Remove leading and trailing whitespace.

my_str = " Python "

stripped_str = my_str.strip() # "Python"

9. Split and Join:

Split a string into a list of substrings and join a list of strings into one.

my_str = "apple,orange,banana"

split_list = my_str.split(",") # ['apple', 'orange', 'banana']

joined_str = "-".join(split_list) # "apple-orange-banana"

10. Formatting:

Use string formatting for more complex string construction.

name = "Alice"

age = 30

formatted_str = f"My name is {name} and I am {age} years old."

11. Comparison:

Compare strings using comparison operators.

str1 = "apple"

str2 = "orange"

result = str1 == str2 # False


These are some of the basic operations you can perform on strings in Python. Strings are versatile,
and there are many more advanced operations and methods available for manipulating and working
with strings.

Lists
In Python, a list is a versatile and mutable data structure that allows you to store a collection of
items. Lists are defined by enclosing elements in square brackets [ ] and separating them with
commas. Here are some key features and operations related to lists in Python:

Creating Lists:

# Creating an empty list

empty_list = []

# Creating a list with elements

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

# Lists can contain elements of different types

mixed_list = [1, "two", 3.0, [4, 5]]

Accessing Elements:

# Accessing elements using indexing (0-based)

first_fruit = fruits[0] # "apple"

second_fruit = fruits[1] # "banana"

Slicing:

# Slicing to get a sublist

subset = fruits[1:3] # ["banana", "cherry"]

Modifying Lists:

# Modifying an element

fruits[0] = "orange" # ["orange", "banana", "cherry"]

# Appending an element to the end

fruits.append("grape") # ["orange", "banana", "cherry", "grape"]

# Extending the list with another list

fruits.extend(["kiwi", "mango"]) # ["orange", "banana", "cherry", "grape", "kiwi", "mango"]


# Inserting an element at a specific position

fruits.insert(2, "pear") # ["orange", "banana", "pear", "cherry", "grape", "kiwi", "mango"]

# Removing an element by value

fruits.remove("banana") # ["orange", "pear", "cherry", "grape", "kiwi", "mango"]

# Removing an element by index

popped_fruit = fruits.pop(2) # "pear", fruits: ["orange", "cherry", "grape", "kiwi", "mango"]

List Operations:

# Concatenating lists

more_fruits = ["pineapple", "watermelon"]

all_fruits = fruits + more_fruits # ["orange", "cherry", "grape", "kiwi", "mango", "pineapple",


"watermelon"]

# Replicating lists

repeated_fruits = fruits * 2 # ["orange", "cherry", "grape", "kiwi", "mango", "orange", "cherry",


"grape", "kiwi", "mango"]

Other List Functions:

# Finding the index of an element

index = fruits.index("kiwi") # 3

# Counting occurrences of an element

count = fruits.count("cherry") # 1

# Reversing the list in-place

fruits.reverse() # ["mango", "kiwi", "grape", "cherry", "orange"]

Sorting Lists:

# Sorting the list in-place

fruits.sort() # ["cherry", "grape", "kiwi", "mango", "orange"]

List Comprehension:

List comprehensions provide a concise way to create lists.

squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]

Lists are widely used in Python due to their flexibility and ease of use. They can store different data
types, and their dynamic nature makes them suitable for a variety of tasks.
Tuples
In Python, a tuple is an ordered, immutable sequence of elements. Tuples are similar to lists, but the
key difference is that once a tuple is created, its elements cannot be modified or changed. Tuples are
defined by enclosing elements in parentheses () and separating them with commas. Here are some
key features and operations related to tuples in Python:

Creating Tuples:

# Creating an empty tuple

empty_tuple = ()

# Creating a tuple with elements

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

# Tuples can contain elements of different types

mixed_tuple = (1, "two", 3.0, (4, 5))

Accessing Elements:

# Accessing elements using indexing (0-based)

first_fruit = fruits[0] # "apple"

second_fruit = fruits[1] # "banana"

Slicing:

# Slicing to get a subtuple

subset = fruits[1:3] # ("banana", "cherry")

Immutability:

# Attempting to modify a tuple will result in an error

fruits[0] = "orange" # TypeError: 'tuple' object does not support item assignment

Tuple Operations:

# Concatenating tuples

more_fruits = ("pineapple", "watermelon")

all_fruits = fruits + more_fruits # ("apple", "banana", "cherry", "pineapple", "watermelon")


# Replicating tuples

repeated_fruits = fruits * 2 # ("apple", "banana", "cherry", "apple", "banana", "cherry")

Other Tuple Functions:

# Finding the index of an element

index = fruits.index("banana") # 1

# Counting occurrences of an element

count = fruits.count("cherry") # 1

Tuple Unpacking:

# Unpacking a tuple into variables

a, b, c = fruits

# a = "apple", b = "banana", c = "cherry"

Benefits of Tuples:

Immutability: Once a tuple is created, its elements cannot be modified, making it suitable for
situations where data should remain constant.

Performance: Tuples are generally faster than lists, especially for read-only operations.

Hashability: Tuples are hashable and can be used as keys in dictionaries, unlike lists.

Tuples are often used when the data should remain constant throughout the program, such as
representing coordinates, RGB color values, or records from a database.

Dictionaries
In Python, a dictionary is a mutable, unordered collection of key-value pairs. Each key in a dictionary
must be unique, and the associated value can be of any data type. Dictionaries are defined by
enclosing key-value pairs in curly braces {} and separating them with commas. Here are key features
and operations related to dictionaries in Python:

Creating Dictionaries:

# Creating an empty dictionary

empty_dict = {}

# Creating a dictionary with key-value pairs

fruits_dict = {"apple": 2, "banana": 3, "cherry": 5}


# Dictionaries can contain keys of different types

mixed_dict = {1: "one", "two": 2, (3, 4): "three-four"}

Accessing and Modifying Values:

# Accessing a value using a key

banana_count = fruits_dict["banana"] # 3

# Modifying a value

fruits_dict["cherry"] = 7

Adding and Removing Items:

# Adding a new key-value pair

fruits_dict["orange"] = 4

# Removing a key-value pair

removed_value = fruits_dict.pop("banana")

Dictionary Operations:

# Checking if a key is in the dictionary

is_apple_present = "apple" in fruits_dict # True

# Getting the list of keys and values

keys_list = list(fruits_dict.keys())

values_list = list(fruits_dict.values())

Dictionary Comprehension:

Dictionary comprehensions provide a concise way to create dictionaries.

squares_dict = {x: x**2 for x in range(5)}

# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Nested Dictionaries:

Dictionaries can contain other dictionaries as values, creating nested structures.

nested_dict = {"person": {"name": "Alice", "age": 30, "city": "Wonderland"}}

Benefits of Dictionaries:

Key-Value Structure: Dictionaries provide an intuitive key-value structure, making it easy to represent
relationships between entities.
Dynamic Size: Dictionaries can dynamically grow or shrink as items are added or removed.

Fast Access: Accessing a value by key in a dictionary is efficient, even for large datasets.

Versatility: Dictionaries are versatile and can represent a wide range of data structures, including
sets, graphs, and more.

Dictionaries are commonly used for tasks involving mappings, configurations, and data organization
where key-based access is crucial.
Unit 4 - Functions and modules

Functions

In Python, a function is a reusable block of code that performs a specific task or set of tasks.
Functions help modularize code, making it more readable, maintainable, and reusable. Here are key
features and concepts related to functions in Python:

Defining a Function:

You define a function using the def keyword, followed by the function name, parameters in
parentheses, and a colon. The function body is indented.

def greet(name):

print(f"Hello, {name}!")

Calling a Function:

To execute the code inside a function, you call the function by using its name followed by
parentheses and passing any required arguments.

greet("Alice")

Function Parameters:

Functions can take parameters, which are values passed to the function when it is called. Parameters
are specified in the function definition.

def add(a, b):

return a + b

Return Statement:

Functions can return a value using the return statement. If no return statement is present, the
function returns None by default.

def add(a, b):

return a + b

Default Parameters:

You can provide default values for function parameters. If a value is not passed for a parameter, the
default value is used.

def greet(name, greeting="Hello"):


print(f"{greeting}, {name}!")

Keyword Arguments:

When calling a function, you can use keyword arguments to specify the values for parameters by
name.

greet(name="Bob", greeting="Hi")

Variable-Length Argument Lists:

Functions can accept a variable number of arguments using *args for positional arguments and
**kwargs for keyword arguments.

def print_args(*args, **kwargs):

print("Positional arguments:", args)

print("Keyword arguments:", kwargs)

Anonymous Functions (Lambda Functions):

Lambda functions are small, anonymous functions defined using the lambda keyword.

multiply = lambda x, y: x * y

Scope of Variables:

Variables defined inside a function have local scope, while variables defined outside functions have
global scope.

global_var = 10

def my_function():

local_var = 5

print(global_var) # Access global variable

print(local_var) # Access local variable

my_function()

Docstrings:

Docstrings are used to provide documentation for functions. They are placed in triple-quotes
immediately following the function definition.

def my_function(parameter):

"""

This is a docstring explaining the function.


Parameters:

- parameter: Description of the parameter.

"""

# Function code here

Recursion:

A function can call itself, a concept known as recursion.

def factorial(n):

if n == 0 or n == 1:

return 1

else:

return n * factorial(n - 1)

Functions are a fundamental concept in Python programming, allowing developers to create reusable
and organized code. They play a crucial role in building modular and maintainable software.

Different variable scopes


In Python, variables can have different scopes, and the scope determines where a variable can be
accessed or modified. The two main types of variable scopes are:

Local Variables:

 Defined inside a function.


 Accessible only within that function.
 Not visible or accessible outside the function.

def my_function():

local_var = 10

print(local_var)

my_function() # Prints 10

# print(local_var) # This would result in an error because local_var is not defined in this scope.
Global Variables:

 Defined outside any function.


 Accessible throughout the entire program, including inside functions.
 Can be modified inside functions using the global keyword.

global_var = 20

def another_function():

print(global_var)

another_function() # Prints 20

def modify_global():

global global_var

global_var = 30

modify_global()

print(global_var) # Prints 30

When a variable is referenced within a function, Python searches for that variable in the following
order:

Local Scope: Inside the function.

Enclosing Scope: In the local scopes of any enclosing functions (for nested functions).

Global Scope: Outside any function, at the top level of the module.

Built-in Scope: Python's built-in names.

If a variable is not found in the local scope, Python looks in the enclosing and global scopes.
However, if a variable is modified (assigned a new value) inside a function without using the global
keyword, Python assumes it's a local variable.

Here's an example illustrating the difference between local and global variables:

global_var = 50

def my_function():

local_var = 25

print("Inside function - Local Variable:", local_var)

print("Inside function - Global Variable:", global_var)

my_function()
print("Outside function - Global Variable:", global_var)

# print("Outside function - Local Variable:", local_var) # This would result in an error

In the example above, local_var is a local variable and is accessible only inside the my_function
function. global_var is a global variable and is accessible both inside and outside the function.

Modules - math and random


In Python, the math and random modules provide various mathematical and random number-related
functions. Here's an overview of each module:

math Module:

The math module provides mathematical functions for basic arithmetic operations, advanced
mathematical operations, and constants.

import math

# Basic arithmetic operations

print(math.sqrt(25)) # Square root: 5.0

print(math.pow(2, 3)) # Power: 8.0

print(math.exp(2)) # Exponential: e^2

print(math.log(10, 2)) # Logarithm base 2: 3.3219280948873626

print(math.sin(math.pi/2)) # Sine: 1.0

# Constants

print(math.pi) # Pi: 3.141592653589793

print(math.e) # Euler's number: 2.718281828459045

random Module:

The random module provides functions for generating pseudo-random numbers and performing
random selections.

import random

# Generating random numbers

print(random.random()) # Random float in the range [0.0, 1.0)

print(random.randint(1, 10)) # Random integer in the range [1, 10]


print(random.uniform(1.0, 5.0)) # Random float in the range [1.0, 5.0)

# Random selections

my_list = [1, 2, 3, 4, 5]

print(random.choice(my_list)) # Randomly choose an element from the list

print(random.shuffle(my_list)) # Shuffle the list in-place

print(random.sample(my_list, 2)) # Randomly select 2 unique elements from the list

These are just a few examples of the functions provided by the math and random modules. Both
modules offer a variety of functions to perform different mathematical and statistical operations, and
they are commonly used in various applications, including scientific computing, simulations, and
games.
Unit 5 - Classes & Objects
classes and objects
In Python, a class is a blueprint for creating objects, and an object is an instance of a class. Classes
provide a way to structure and model data, and they encapsulate data and behavior into a single
unit. Here's an overview of classes and objects in Python:

Defining a Class:

You define a class using the class keyword, followed by the class name and a colon. The class body
contains attributes (variables) and methods (functions).

class Dog:

# Class attribute

species = "Canis familiaris"

# Constructor method

def __init__(self, name, age):

# Instance attributes

self.name = name

self.age = age

# Instance method

def bark(self):

print(f"{self.name} says Woof!")

Creating Objects (Instances):

To create an object (instance) of a class, you call the class as if it were a function, passing any
required arguments to the constructor (__init__ method).

# Creating instances of the Dog class

dog1 = Dog("Buddy", 3)

dog2 = Dog("Max", 5)

# Accessing attributes

print(dog1.name) # Buddy

print(dog2.age) #5
# Calling methods

dog1.bark() # Buddy says Woof!

dog2.bark() # Max says Woof!

Class and Instance Attributes:

Class Attributes: Shared by all instances of a class.

Instance Attributes: Specific to each instance of a class.

# Accessing class attribute

print(Dog.species) # Canis familiaris

# Modifying instance attribute

dog1.age = 4

print(dog1.age) #4

Methods:

Instance Methods: Operate on an instance of the class and can access and modify instance
attributes.

Class Methods: Operate on the class itself and can access and modify class attributes.

Static Methods: Don't depend on instance or class attributes and are defined with the
@staticmethod decorator.

class Circle:

pi = 3.14

def __init__(self, radius):

self.radius = radius

def area(self):

return self.pi * self.radius**2

@classmethod

def set_pi(cls, new_pi):

cls.pi = new_pi

@staticmethod
def circumference(radius):

return 2 * Circle.pi * radius

# Using methods

circle1 = Circle(5)

print(circle1.area()) # 78.5

circle1.set_pi(3.14159)

print(circle1.circumference(5)) # 31.4159

Inheritance:

Inheritance allows a class to inherit attributes and methods from another class. The new class is
called the derived class or subclass, and the class it inherits from is the base class or superclass.

class Car:

def __init__(self, make, model):

self.make = make

self.model = model

def display_info(self):

print(f"{self.make} {self.model}")

class ElectricCar(Car):

def __init__(self, make, model, battery_capacity):

super().__init__(make, model)

self.battery_capacity = battery_capacity

def display_info(self):

super().display_info()

print(f"Battery Capacity: {self.battery_capacity} kWh")


# Using inheritance

car1 = Car("Toyota", "Camry")

car2 = ElectricCar("Tesla", "Model 3", 75)

car1.display_info() # Toyota Camry

car2.display_info() # Tesla Model 3, Battery Capacity: 75 kWh

Classes and objects are fundamental concepts in object-oriented programming (OOP), and they
provide a way to structure and organize code in a modular and reusable manner.

Class method and self-argument

In Python, methods are functions that are associated with an object. When defining methods within
a class, there are two common types of methods: instance methods and class methods. Additionally,
the self argument is a special parameter used in instance methods to reference the instance of the
class. Let's explore class methods and the self argument:

Class Methods:

A class method is a method that is bound to the class and not the instance of the class. It is defined
using the @classmethod decorator, and it takes the class itself as its first parameter, commonly
named cls (though you can use any valid variable name).

class MyClass:

class_variable = "I am a class variable"

def __init__(self, instance_variable):

self.instance_variable = instance_variable

@classmethod

def class_method(cls):

print(cls.class_variable)

# Accessing a class method

MyClass.class_method() # Output: I am a class variable


In the example above, class_method can access and modify class-level attributes but cannot access
instance-level attributes because it does not have access to the instance itself.

The self Argument:

In Python, the self argument is a convention used in instance methods to represent the instance of
the class. It is the first parameter in every instance method, though you can use any valid variable
name (e.g., this), but it is highly recommended to use self for clarity.

class MyClass:

def __init__(self, instance_variable):

self.instance_variable = instance_variable

def instance_method(self):

print(f"Instance variable: {self.instance_variable}")

# Creating an instance of MyClass

obj = MyClass("I am an instance")

# Accessing an instance method

obj.instance_method() # Output: Instance variable: I am an instance

In the example above, instance_method can access and modify both class-level and instance-level
attributes because it has access to the instance through the self parameter.

It's important to note that when calling an instance method, you don't explicitly pass the self
argument; Python handles it implicitly. For example, obj.instance_method() is equivalent to
MyClass.instance_method(obj).

Understanding the distinction between class methods and instance methods, as well as the use of
the self argument, is crucial for working effectively with object-oriented programming in Python.

class variables and object variables


In Python, methods are functions that are associated with an object. When defining methods within
a class, there are two common types of methods: instance methods and class methods. Additionally,
the self argument is a special parameter used in instance methods to reference the instance of the
class. Let's explore class methods and the self argument:

Class Methods:

A class method is a method that is bound to the class and not the instance of the class. It is defined
using the @classmethod decorator, and it takes the class itself as its first parameter, commonly
named cls (though you can use any valid variable name).

class MyClass:

class_variable = "I am a class variable"

def __init__(self, instance_variable):

self.instance_variable = instance_variable

@classmethod

def class_method(cls):

print(cls.class_variable)

# Accessing a class method

MyClass.class_method() # Output: I am a class variable

In the example above, class_method can access and modify class-level attributes but cannot access
instance-level attributes because it does not have access to the instance itself.

The self Argument:

In Python, the self argument is a convention used in instance methods to represent the instance of
the class. It is the first parameter in every instance method, though you can use any valid variable
name (e.g., this), but it is highly recommended to use self for clarity.

class MyClass:

def __init__(self, instance_variable):

self.instance_variable = instance_variable

def instance_method(self):
print(f"Instance variable: {self.instance_variable}")

# Creating an instance of MyClass

obj = MyClass("I am an instance")

# Accessing an instance method

obj.instance_method() # Output: Instance variable: I am an instance

In the example above, instance_method can access and modify both class-level and instance-level
attributes because it has access to the instance through the self parameter.

It's important to note that when calling an instance method, you don't explicitly pass the self
argument; Python handles it implicitly. For example, obj.instance_method() is equivalent to
MyClass.instance_method(obj).

class variables and object variables


In Python, class variables and instance variables are two types of variables associated with classes.
Let's explore the differences between them:

Class Variables:

Shared by all instances of a class: Class variables are defined within a class but outside any instance
method.

Same value for all instances: They have the same value for every instance of the class.

Defined outside methods using the class name or within class methods using cls:

class MyClass:

class_variable = "I am a class variable"

def __init__(self, instance_variable):

self.instance_variable = instance_variable

# Accessing a class variable

print(MyClass.class_variable) # Output: I am a class variable


# Class variable can be modified using the class name

MyClass.class_variable = "Modified class variable"

print(MyClass.class_variable) # Output: Modified class variable

# Instances share the same class variable

obj1 = MyClass("Instance 1")

obj2 = MyClass("Instance 2")

print(obj1.class_variable) # Output: Modified class variable

print(obj2.class_variable) # Output: Modified class variable

Instance Variables:

Unique to each instance: Instance variables are defined within the __init__ method and are specific
to each instance of the class.

Different values for different instances: Each instance can have a different value for an instance
variable.

class MyClass:

def __init__(self, instance_variable):

self.instance_variable = instance_variable

# Creating instances with different values for instance variables

obj1 = MyClass("Value for Instance 1")

obj2 = MyClass("Value for Instance 2")

# Accessing instance variables

print(obj1.instance_variable) # Output: Value for Instance 1

print(obj2.instance_variable) # Output: Value for Instance 2

When to Use Each:

Class Variables: Use class variables when you want a value to be shared among all instances of a
class. For example, a constant value that is the same for all instances.

Instance Variables: Use instance variables when each instance needs to have its own unique data.
It's essential to understand the distinction between class variables and instance variables to
effectively use classes in Python. Class variables are shared among all instances, while instance
variables are specific to each instance.

public and private data members


In Python, data members (variables) of a class can be classified into two main categories: public and
private. These classifications are based on the visibility and accessibility of the variables. Here's an
overview:

Public Data Members:

Accessible from outside the class: Public data members can be accessed and modified from outside
the class.

No special syntax required: They are accessed using the dot notation.

class MyClass:

# Public data member

public_variable = "I am a public variable"

# Creating an instance of MyClass

obj = MyClass()

# Accessing and modifying a public variable

print(obj.public_variable) # Output: I am a public variable

obj.public_variable = "Modified public variable"

print(obj.public_variable) # Output: Modified public variable

Private Data Members:

Not accessible from outside the class: Private data members are intended to be used only within the
class itself.

Prefix with double underscores (__): To make a variable private, prefix its name with double
underscores.

class MyClass:

# Private data member


__private_variable = "I am a private variable"

def get_private_variable(self):

return self.__private_variable

def set_private_variable(self, new_value):

self.__private_variable = new_value

# Creating an instance of MyClass

obj = MyClass()

# Attempting to access a private variable directly will result in an AttributeError

# print(obj.__private_variable) # Uncommenting this line will result in an error

# Accessing and modifying a private variable using getter and setter methods

print(obj.get_private_variable()) # Output: I am a private variable

obj.set_private_variable("Modified private variable")

print(obj.get_private_variable()) # Output: Modified private variable

Note:

While Python does not enforce strict access control, the use of the double underscore prefix is a
convention indicating that a variable is intended to be private.

Private variables can still be accessed with a different name, as the double underscore is mainly a
form of name mangling to make it more difficult but not impossible to access the variable.

In summary, public data members are accessible from outside the class, while private data members
are intended for internal use within the class. The use of private variables is based on convention and
serves as a way to communicate that a variable is not intended for external manipulation.
private methods
In Python, just like data members, methods of a class can also be classified into public and private
based on their visibility and accessibility. Private methods are intended to be used only within the
class and are not accessible from outside the class. To make a method private, you can prefix its
name with double underscores (__). Here's an example:

class MyClass:

def __init__(self, value):

self.__private_variable = value

def __private_method(self):

print("This is a private method")

def public_method(self):

print("This is a public method")

# Accessing a private method within the class

self.__private_method()

# Creating an instance of MyClass

obj = MyClass("Initial value")

# Accessing and modifying a private variable using a public method

obj.public_method() # Output: This is a public method \n This is a private method

In the example above:

__private_method is a private method that can only be accessed within the class.

public_method is a public method that can be accessed from outside the class. Inside this method,
the private method __private_method is called.

Keep in mind the following:

Python doesn't provide strict access control, and the double underscore is a form of name mangling,
making it more difficult but not impossible to access private methods.
The use of private methods is more about convention and communicating that a method is intended
for internal use.

It's important to carefully consider the design and purpose of your class when deciding which
methods should be public or private to ensure encapsulation and maintainability.

built-in class attributes


In Python, each class has several built-in attributes that provide information about the class itself.
These attributes are accessible using the class name and the dot notation. Here are some commonly
used built-in class attributes:

__doc__:

Provides the docstring associated with the class.

The docstring is a string literal that occurs as the first statement in a module, function, class, or
method definition.

class MyClass:

"""This is a docstring for MyClass."""

pass

print(MyClass.__doc__) # Output: This is a docstring for MyClass.

__name__:

Represents the name of the class.

For a module-level class, it's the name of the module.

class MyClass:

pass

print(MyClass.__name__) # Output: MyClass

__module__:

Provides the name of the module in which the class is defined.

For a class defined in the main module, it will be __main__.


class MyClass:

pass

print(MyClass.__module__) # Output: __main__

__bases__:

Returns a tuple containing the base classes, in the order they are declared.

python

Copy code

class Parent:

pass

class Child(Parent):

pass

print(Child.__bases__) # Output: (<class '__main__.Parent'>,)

__dict__:

A dictionary containing the class's namespace.

python

Copy code

class MyClass:

class_variable = "I am a class variable"

print(MyClass.__dict__) # Output: {'__module__': '__main__', 'class_variable': 'I am a class variable',


...}

These built-in class attributes can be useful for introspection and understanding the structure of
classes at runtime. They provide information about the class, its attributes, and its relationships with
other classes.
static methods
In Python, a static method is a method that belongs to a class rather than an instance of the class.
Unlike instance methods, static methods don't have access to the instance or its attributes. They are
defined using the @staticmethod decorator and take neither self (for instance) nor cls (for class) as
their first parameter. Instead, they behave like regular functions, and you can call them on the class
itself or an instance.

Here's an example of defining and using a static method:

python

Copy code

class MathOperations:

@staticmethod

def add(x, y):

return x + y

@staticmethod

def multiply(x, y):

return x * y

# Using static methods

result_add = MathOperations.add(3, 5)

result_multiply = MathOperations.multiply(4, 6)

print(result_add) # Output: 8

print(result_multiply) # Output: 24

In this example:
add and multiply are static methods of the MathOperations class.

They are called on the class itself, not on an instance of the class.

Static methods are useful when a method doesn't depend on the state of an instance or the class.
They provide a way to organize utility functions related to the class but don't rely on instance-specific
or class-specific attributes.

While static methods don't have direct access to instance or class attributes, they can still be called
on instances, and you can use them for operations that are logically related to the class but don't
involve modifying the instance or class state.
LAB

1. Python Program to Find the Square Root

import math

def find_square_root(number):

# Check if the number is non-negative

if number >= 0:

square_root = math.sqrt(number)

return square_root

else:

return "Cannot find the square root of a negative number."

# Get input from the user

user_input = float(input("Enter a number to find its square root: "))

# Call the function to find the square root

result = find_square_root(user_input)

# Display the result

print(f"The square root of {user_input} is: {result}")

output
2. Python Program to Swap Two Variable

# Function to swap two variables

def swap_variables(var1, var2):

temp = var1

var1 = var2

var2 = temp

return var1, var2

# Get input from the user

variable1 = input("Enter the value of the first variable: ")

variable2 = input("Enter the value of the second variable: ")

# Display the original values

print(f"Original values: Variable1 = {variable1}, Variable2 = {variable2}")

# Call the function to swap the variables

variable1, variable2 = swap_variables(variable1, variable2)

# Display the swapped values

print(f"Swapped values: Variable1 = {variable1}, Variable2 = {variable2}")


3. Python Program to Generate a Random Number

import random

# Get input from the user for the range

start_range = int(input("Enter the start of the range: "))

end_range = int(input("Enter the end of the range: "))

# Generate a random number between the specified range

random_result = random.randint(start_range, end_range)

# Display the random number

print(f"Random number between {start_range} and {end_range}: {random_result}")

Output
4. Python Program to Check if a Number is Odd or Even

def check_odd_or_even(number):

if number % 2 == 0:

return "Even"

else:

return "Odd"

# Get input from the user

user_input = int(input("Enter a number: "))

# Call the function to check if the number is odd or even

result = check_odd_or_even(user_input)

# Display the result

print(f"The number {user_input} is {result}.")

Output
5. Python Program to Find the Largest Among Three Numbers

def find_largest_number(num1, num2, num3):

# Using the max function to find the maximum among the three numbers

largest_number = max(num1, num2, num3)

return largest_number

# Get input from the user

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

num3 = float(input("Enter the third number: "))

# Call the function to find the largest number

result = find_largest_number(num1, num2, num3)

# Display the result

print(f"The largest number among {num1}, {num2}, and {num3} is: {result}")

output
6. Python Program to Check Prime Number

def is_prime_number(number):

if number <= 1:

return False

elif number == 2:

return True

elif number % 2 == 0:

return False

else:

# Check for factors from 3 to the square root of the number

for i in range(3, int(number**0.5) + 1, 2):

if number % i == 0:

return False

return True

# Get input from the user

user_input = int(input("Enter a number to check if it's prime: "))

# Call the function to check if the number is prime

result = is_prime_number(user_input)

# Display the result

if result:

print(f"{user_input} is a prime number.")

else:

print(f"{user_input} is not a prime number.")


Output
7. Python Program to Display the multiplication Table

def display_multiplication_table(number, table_size):

print(f"Multiplication Table for {number} up to {table_size}:")

for i in range(1, table_size + 1):

result = number * i

print(f"{number} x {i} = {result}")

# Get input from the user

user_input = int(input("Enter the number for the multiplication table: "))

table_size = int(input("Enter the size of the table: "))

# Call the function to display the multiplication table

display_multiplication_table(user_input, table_size)

Output
8. Python Program to Print the Fibonacci sequence

def generate_fibonacci_sequence(terms):

fibonacci_sequence = [0, 1]

while len(fibonacci_sequence) < terms:

next_term = fibonacci_sequence[-1] + fibonacci_sequence[-2]

fibonacci_sequence.append(next_term)

return fibonacci_sequence

# Get input from the user

num_terms = int(input("Enter the number of terms for the Fibonacci sequence: "))

# Call the function to generate the Fibonacci sequence

fibonacci_result = generate_fibonacci_sequence(num_terms)

# Display the result

print(f"Fibonacci sequence up to {num_terms} terms: {fibonacci_result}")

Output
9. Python Program to Find the Sum of Natural Numbers

def sum_of_natural_numbers(n):

if n < 0:

return "Please enter a non-negative number."

else:

sum_result = (n * (n + 1)) // 2

return sum_result

# Get input from the user

user_input = int(input("Enter a non-negative number: "))

# Call the function to find the sum of natural numbers

result = sum_of_natural_numbers(user_input)

# Display the result

if isinstance(result, int):

print(f"The sum of natural numbers up to {user_input} is: {result}")

else:

print(result)

Output
10. Python Program to Find Factorial of Number Using Recursion

def factorial_recursive(n):

if n == 0 or n == 1:

return 1

else:

return n * factorial_recursive(n - 1)

# Get input from the user

user_input = int(input("Enter a non-negative integer to find its factorial: "))

# Check if the input is non-negative

if user_input < 0:

print("Please enter a non-negative integer.")

else:

# Call the function to find the factorial using recursion

result = factorial_recursive(user_input)

# Display the result

print(f"The factorial of {user_input} is: {result}")

Output
11. Python Program to work with string methods

# Sample string

input_string = "Hello, World! Welcome to Python Programming."

# 1. Length of the string

length = len(input_string)

print(f"1. Length of the string: {length}")

# 2. Convert the string to uppercase

uppercase_string = input_string.upper()

print(f"2. Uppercase string: {uppercase_string}")

# 3. Convert the string to lowercase

lowercase_string = input_string.lower()

print(f"3. Lowercase string: {lowercase_string}")

# 4. Count the occurrences of a substring

substring_count = input_string.count("o")

print(f"4. Number of occurrences of 'o': {substring_count}")

# 5. Find the index of a substring

substring_index = input_string.find("World")

print(f"5. Index of 'World': {substring_index}")

# 6. Replace a substring
new_string = input_string.replace("Hello", "Hi")

print(f"6. String after replacement: {new_string}")

# 7. Check if the string starts with a specific prefix

starts_with_hello = input_string.startswith("Hello")

print(f"7. Does the string start with 'Hello'? {starts_with_hello}")

# 8. Check if the string ends with a specific suffix

ends_with_programming = input_string.endswith("Programming.")

print(f"8. Does the string end with 'Programming.'? {ends_with_programming}")

Output
12. Python Program to create a dictionary and print its content

# Create a dictionary

student_info = {

'name': 'John Doe',

'age': 20,

'grade': 'A',

'subjects': ['Math', 'Science', 'English']

# Print the entire dictionary

print("Dictionary Content:")

print(student_info)

# Print each key-value pair separately

print("\nIndividual Key-Value Pairs:")

for key, value in student_info.items():

print(f"{key}: {value}")

Output
13. Python Program to create class and objects

# Define a class named 'Person'

class Person:

# Constructor to initialize instance variables

def __init__(self, name, age):

self.name = name

self.age = age

# Method to display information about the person

def display_info(self):

print(f"Name: {self.name}, Age: {self.age}")

# Create objects of the 'Person' class

person1 = Person("John", 25)

person2 = Person("Alice", 30)

# Display information about the persons

print("Information about Person 1:")

person1.display_info()

print("\nInformation about Person 2:")

person2.display_info()
Output

You might also like