TESDA License NC II PC Operations TESDA, Office ProductivityMELJUN CORTES
Ad
Exploring Data Science Using Python Tools
1. PYTHON PROGRAMMING LANGUAGE
PYTHON WORKSHOP
Mohan Kamal Hassan
Resource Person
JNTUH ID: 212541-25005
Faculty Registration ID: 5803-250326-100018
Assitant Professor(AI&DS)-Bhaskar Engineering College
B.Tech(I.T), M.Tech(CSE), MS(CSE-USA)
2. INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE
PYTHON ROADMAP
FEATURES OF PYTHON
FUNDAMENTAL CONCEPTS OF PYTHON
PYTHON SYNTAX AND SEMANTICS PROTOCOLS
DATA STRUCTURES IN PYTHON
PYTHON PACKAGES(Numpy,Pandas,Matplotlib)
REAL TIME EXAMPLE
RESOURCES AND MATERIALS
INDEX
3. INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE
Python is a popular high-level programming language used in various applications
○ Python is an programming language easy to learn, to code because of its simple syntax.
○ Python can be used for both simple tasks and complex tasks like machine learning.
○ Python is efficient in computing large amount of dataset.
4. ● Interpreter VS Compiler
● Two kinds of applications process high-level languages into low-level languages:
interpreters and compilers.
● An interpreter reads a high-level program and executes it, meaning that it does what the
program says. It processes the program a little at a time, alternately reading lines and
performing computations.
● ----------------------------------------------------------------------------------------------------------------------------
● A compiler reads the program and translates it into a low-level program, which can then
be run.
● In this case, the high-level program is called the source code, and the translated
program is called the object code or the executable. Once a program is compiled, you
can execute it repeatedly without further translation.
5. ● Many modern languages use both processes. They are first compiled into a lower
● level language, called byte code, and then interpreted by a program called a virtual machine.
Python uses both processes, but because of the way programmers interact with it, it is usually
considered an interpreted language
● There are two ways to use the Python interpreter: shell mode and script mode.
● In shell mode, you type Python statements into the Python shell and the interpreter
immediately prints the result.
6. ● What is Debugging ?
● Programming is a complex process, and because it is done by human beings, programs often contain errors.
For whimsical reasons, programming errors are called bugs and the process of tracking them down and
correcting them is called debugging.
● Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is useful
to distinguish between them in order to track them down more quickly
● Syntax errors
● Python can only execute a program if the program is syntactically correct; otherwise, the process fails and
returns an error message. Syntax refers to the structure of a program and the rules about that structure. For
example, in English, a sentence must begin with a capital letter and end with a period. this sentence
contains a syntax error.
● So does this one For most readers, a few syntax errors are not a significant problem, which is why we can
read the poetry of e. e. cummings without spewing error messages. Python is not so forgiving. If there is a
single syntax error anywhere in your program, Python will print an error message and quit, and you will
not be able to run your program.
● During the first few weeks of your programming career, you will probably spend a lot of time tracking
down syntax errors. As you gain experience, though, you will make fewer syntax errors and find them
faster.
7. ● Runtime errors
● The second type of error is a runtime error, so called because the error does not appear until you run the
program. These errors are also called exceptions because they usually indicate that something exceptional
(and bad) has happened. Runtime errors are rare in the simple programs you will see in the first few
chapters, so it might be a while before you encounter one.
● Semantic errors
● The third type of error is the semantic error. If there is a semantic error in your program, it will run
successfully, in the sense that the computer will not generate any error messages, but it will not do the right
thing. It will do something else.
● Specifically, it will do what you told it to do.
● The problem is that the program you wrote is not the program you wanted to write. The meaning of the
program (its semantics) is wrong. Identifying semantic errors can be tricky because it requires you to work
backward by looking at the output of the program and trying to figure out what it is doing.
8. The Difference Between Brackets, Braces, and Parentheses:
● Braces are used for different purposes. If you just want a list to contain some elements and organize them by index
numbers (starting from 0), just use the [] and add elements as necessary. {} are special in that you can give custom
id's to values like a = {"John": 14}. Now, instead of making a list with ages and remembering whose age is where,
you can just access John's age by a["John"].
● The [] is called a list and {} is called a dictionary (in Python).
● Dictionaries are basically a convenient form of list which allow you to access data in a much easier way.
● However, there is a catch to dictionaries. Many times, the data that you put in the dictionary doesn't stay in the
same order as before. Hence, when you go through each value one by one, it won't be in the order you expect.
There is a special dictionary to get around this, but you have to add this line from collections import OrderedDict
and replace {} with OrderedDict(). But, I don't think you will need to worry about that for now.
10. Features of python:
Python's features include-
• Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows a student to
pick up the language quickly.
• Easy-to-read: Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain: Python's source code is fairly easy-to-maintain.
• A broad standard library: Python's bulk of the library is very portable and cross platform compatible on UNIX,
Windows, and Macintosh.
• Interactive Mode: Python has support for an interactive mode, which allows interactive testing and debugging
of snippets of code.
FEATURES OF PYTHON
11. FUNDAMENTAL CONCEPTS OF PYTHON
Fundamental concept of python cosmists of
1) VARIABLES
2) OBJECT
3) CLASSES
1.Variables:
•Definition: A variable is a named location in memory where you can store data.
•Purpose: Variables are used to represent data that can be changed during the program's execution.
•Types: Variables have different data types (e.g., integer, string, boolean) that determine the kind of data
they can store.
•Example: age = 30 stores the integer value 30 in a variable named age
12. 2. Objects:
•Definition:
An object is a specific instance of a class. It's a concrete entity created based on the class's blueprint.
•Purpose:
Objects represent real-world entities or concepts within the program, allowing you to interact with them.
•Example:
my_dog = Dog("Buddy", "Golden Retriever") creates an object named my_dog based on the Dog class,
giving it the name "Buddy" and breed "Golden Retriever".
3. Classes:
•Definition:
A class is a blueprint or template for creating objects. It defines the structure (data) and behavior
(methods) of objects that will be based on it.
•Purpose:
Classes help organize code by grouping related data and methods together, promoting code reuse and
maintainability.
•Example:
A Dog class might have attributes like name and breed, and methods like bark() and play().
13. Variables, Objects, and Classes (cont.)
● A class is a collection of objects who share
the same set of variables/methods.
○ The definition of the class provides a
blueprint for all the objects within it
(instances).
○ Instances may share the same
variables (color, size, shape, etc.), but
they do NOT share the same values
for each variable (blue/red/pink,
small/large, square/circular etc.)
Instance #1
Color: Pink
Name: Polo
Instance #2
Color: Red
Name: Mini
Instance #3
Color: Blue
Name: Beetle
14. PYTHON SYNTAX AND SEMANTICS PROTOCOLS
Python 9 Syntax Protocols
Python syntax focuses on readability and simplicity. It utilizes indentation for code blocks, avoids special characters in
variable names, and uses keywords for specific functions.
1. Indentation
2. Variable Names
3. Comments
4. Data Types
5. Basic Syntax Elements
6. Control Flow
7. Operators
8. Functions
9. Modules and Imports
15. 1. Indentation
•Python uses indentation (spaces or tabs, but not mixed) to define code blocks, unlike other languages
that use braces { }.
•Indentation is crucial and affects how the interpreter reads the code.
•Consistent indentation within a block is essential.
2. Variable Names
•Variable names must start with a letter or underscore (_) and can't start with a
number.
•They can contain alphanumeric characters and underscores.
•Variable names are case-sensitive (e.g., age, Age, and AGE are different).
•Reserved keywords (like print, if, for) cannot be used as variable names.
16. 3. Comments
•Comments are used to explain code. They start with a # symbol.
•Multiline comments can be created by enclosing the text within triple quotes ( """ or ```).
4. Data Types
•Python supports various data types, including integers, floats, strings, lists, dictionaries, and more.
•Variable types are inferred when a value is assigned, without needing explicit type declarations.
5. Basic Syntax Elements
•Parentheses (): Used for function calls and grouping expressions.
•Square brackets []: Used for lists and array indexing.
•Curly braces {}: Used for dictionaries.
•Semicolons ;: While not required in Python, they can be used to separate statements on a single line.
•Backslashes ``: Used to continue a statement onto the next line.
17. 6. Control Flow
•if, elif, else: Used for conditional statements.
•for and while: Used for loops.
•try, except, finally: Used for exception handling.
7. Operators:
•Python uses various operators like arithmetic (+, -, *, /),
• comparison (==, !=, <, >, <=, >=), logical (and, or, not),
•and assignment (=).
8. Functions
•Functions are defined using the def keyword.
•They can have parameters and return values.
9. Modules and Imports
•Python uses modules to organize code.
•The import keyword is used to import modules and their contents.
18. PYTHON SYNTAX AND SEMANTICS PROTOCOLS
Python 9 Semantics Protocols
In Python, semantics are the rules that determine how code is interpreted and executed, focusing on the meaning and intended
behavior of the code, This includes how expressions are evaluated, variables and objects are handled, control flow is managed, and
how functions and classes are used.
1. Variable Scope
2. Function Calls
3. Object References:
4. Data Type Behavior
5. Control Flow
6. Error Handling
7. Operator Overloading
8. Dynamic Typing
9. Strong Typing
19. 1.Variable Scope
Variables are accessed and modified within different parts of the code (e.g., local vs. global variables).
2.Function Calls
Functions are called, arguments are passed, and return values are handled.
3.Object References
objects are stored and referenced in memory, and how changes to objects affect other parts of the code.
4.Data Type Behavior
How different data types (e.g., integers, strings, lists, dictionaries) behave in operations and comparisons.
5.Control Flow
How conditional statements (if, else, elif), loops (for, while), and other control structures dictate the execution
path of the program.
20. 6.Error Handling
How exceptions are raised, caught, and handled.
7.Operator Overloading
The ability to define custom behavior for operators on user-defined classes.
8.Dynamic Typing
Variables are not explicitly typed; their type is determined at runtime.
9.Strong Typing
Python is strongly typed, meaning that type conversions are not performed implicitly.
21. DATA STRUCTURES IN PYTHON
Data Structures in Python
Lists
Tuples
Sets
Dictionaries
22. 1. List
List an ordered collection of items. You can add, remove, or change elements.
Lists allow duplicate values.
•Lists are written using square brackets [].
•You can access items using an index (starting from 0).
Example
•fruits = ["apple", "banana", "cherry"]
•print(fruits[1]) # Outputs: banana
2.Tuple
A tuple is like a list, but it is immutable, meaning you cannot change its contents after it is created.
•Tuples are written using parentheses ().
•Good for storing fixed data that shouldn’t be changed.
Example:
python
colors = ("red", "green", "blue") print(colors[0]) # Outputs: red
23. 3. Set
A set is an unordered collection of unique items. Sets do not allow duplicates and the items cannot be
accessed by index.
•Sets are written using curly braces {}.
•Useful when you want only unique values.
Example
numbers = {1, 2, 3, 2}
print(numbers) # Outputs: {1, 2, 3}
4. Dictionary
A dictionary is a collection of key-value pairs. Each key is unique and is used to access its
corresponding value.
•Dictionaries are written using curly braces {}, with key-value pairs separated by a colon :.
•Great for storing data that relates to something, like a person's profile.
Example
person = {"name": "Alice", "age": 25}
print(person["name"]) # Outputs: Alice
24. PYTHON PACKAGES(NUMPY,PANDAS,MATPLOTLIB)
Python 3 important Packages used in ML/AI:
1. Numpy
2. Pandas
3. Matplotlib
Numpy:
NumPy is used for numerical computations. It allows you to work with arrays, which are faster and
more efficient than Python lists for mathematical operations.
Pandas:
Pandas is great for data manipulation and analysis. It uses structures like DataFrame (a table-like
structure) to organize and explore data easily.
Matplotlib (Mathematical Plotting Library)
Matplotlib is used for data visualization. It helps you create charts and graphs.
25. REAL TIME EXAMPLE
Step 1: Load and Explore Data with Pandas python
import pandas as pd
# Load the CSV file into a DataFrame
df = pd.read_csv('sales_data.csv')
# Convert 'Order Date' to datetime format
df['Order Date'] = pd.to_datetime(df['Order Date'])
# Display the first few rows
print(df.head())
pd.read_csv() reads the CSV file into a DataFrame.
pd.to_datetime() converts the 'Order Date' column to datetime
objects for easier manipulation.
26. Perform Calculations with NumPy
import numpy as np
df['Profit Margin'] = np.round(df['Profit'] / df['Total Sales'], 2) #Calculate Profit Margin and add as a new column
print(df) # Display the updated DataFrame
np.round() rounds the calculated profit margin to two decimal places.
This operation adds a new column 'Profit Margin' to the DataFrame.
Visualize Data with Matplotlib
import matplotlib.pyplot as plt
# Plot Total Sales over Order Date
plt.figure(figsize=(10, 5))
plt.plot(df['Order Date'], df['Total Sales'], marker='o', linestyle='-')
plt.title('Total Sales Over Time')
plt.xlabel('Order Date')
plt.ylabel('Total Sales')
plt.grid(True)
plt.tight_layout()
plt.show()
27. Data Analysis and Visualization
Seaborn
Provides a high-level interface for drawing attractive and informative statistical graphics.
Use Cases: Creating complex visualizations like heatmaps, violin plots, and time series plots with minimal code.
Plotly
Facilitates interactive graphing and data visualization.
Use Cases: Building interactive dashboards and visualizations for web applications.
Machine Learning
scikit-learn :
Simple and efficient tools for predictive data analysis.
Use Cases: Implementing machine learning algorithms like classification, regression, clustering, and dimensionality reduction.
TensorFlow:
Provides a comprehensive ecosystem for building machine learning models.
Use Cases: Developing and training deep learning models for tasks like image and speech recognition.
28. RESOURCES AND MATERIALS
Python Tutorial Point
A beginner-friendly Integrated Development Environment (IDE) for Python that simplifies the learning process with its
user-friendly interface.
https://www.tutorialspoint.com/python/index.htm
W3Schools
A community-driven forum where learners can ask write, share resources, and get knowledge on learning Python.
https://www.w3schools.com/python/
AnalyticsVidhya
A detailed guide that covers best practices, tools, and resources for Python development.
https://www.analyticsvidhya.com/blog/2021/04/python-list-programs-for-absolute-beginners/
Python Wiki – Beginner’s Guide for Programmers
This wiki offers a collection of tutorials and tools tailored for those new to programming with Python.
https://wiki.python.org/moin/BeginnersGuide/Programmers