SlideShare a Scribd company logo
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)
 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
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.
● 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.
● 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.
● 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.
● 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.
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.
PYTHON ROADMAP
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
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
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().
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
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
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.
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.
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.
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
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.
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.
DATA STRUCTURES IN PYTHON
Data Structures in Python
 Lists
 Tuples
 Sets
 Dictionaries
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
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
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.
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.
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()
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.
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
Exploring Data Science Using Python Tools

More Related Content

Similar to Exploring Data Science Using Python Tools (20)

PDF
How To Tame Python
Mohd Anwar Jamal Faiz
 
PPTX
Python Programming 1.pptx
Francis Densil Raj
 
PDF
Python: An introduction A summer workshop
ForrayFerenc
 
PDF
Python_Programming_PPT Basics of python programming language
earningmoney9595
 
PDF
Python Basics Understanding Variables.pdf
codingmaster021
 
PDF
Python Basics Understanding Variables.pdf
codingmaster021
 
PPTX
Python basics
ssuser4e32df
 
PPTX
modul-python-part1.pptx
Yusuf Ayuba
 
PPTX
Programming paradigms Techniques_part2.pptx
ssuser5ecd1a
 
PPTX
2024-25 TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
sangeeta borde
 
PDF
Python for katana
kedar nath
 
PPTX
Introduction-to-Python.pptx
AyushDey1
 
PPTX
pengenalan python apa itu python untuk apa.pptx
aftaf3
 
PPTX
VARIABLES AND DATA TYPES IN PYTHON NEED TO STUDY
Rushikesh Kolhe
 
PPTX
Why Python in required in Civil Engineering
Rushikesh Kolhe
 
PPTX
Lecture1.pptx
akabiradam13
 
PPTX
Python-Mastering-the-Language-of-Data-Science.pptx
dmdHaneef
 
PPTX
bhaskars.pptx
NaveenShankar34
 
PPTX
PART 1 - Python Tutorial | Variables and Data Types in Python
Shivam Mitra
 
PDF
Python Programming for Beginners
DivyanganaBharadwaj
 
How To Tame Python
Mohd Anwar Jamal Faiz
 
Python Programming 1.pptx
Francis Densil Raj
 
Python: An introduction A summer workshop
ForrayFerenc
 
Python_Programming_PPT Basics of python programming language
earningmoney9595
 
Python Basics Understanding Variables.pdf
codingmaster021
 
Python Basics Understanding Variables.pdf
codingmaster021
 
Python basics
ssuser4e32df
 
modul-python-part1.pptx
Yusuf Ayuba
 
Programming paradigms Techniques_part2.pptx
ssuser5ecd1a
 
2024-25 TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
sangeeta borde
 
Python for katana
kedar nath
 
Introduction-to-Python.pptx
AyushDey1
 
pengenalan python apa itu python untuk apa.pptx
aftaf3
 
VARIABLES AND DATA TYPES IN PYTHON NEED TO STUDY
Rushikesh Kolhe
 
Why Python in required in Civil Engineering
Rushikesh Kolhe
 
Lecture1.pptx
akabiradam13
 
Python-Mastering-the-Language-of-Data-Science.pptx
dmdHaneef
 
bhaskars.pptx
NaveenShankar34
 
PART 1 - Python Tutorial | Variables and Data Types in Python
Shivam Mitra
 
Python Programming for Beginners
DivyanganaBharadwaj
 

Recently uploaded (20)

PPTX
Indigo dyeing Presentation (2).pptx as dye
shreeroop1335
 
PPTX
RESEARCH-FINAL-GROUP-3, about the final .pptx
gwapokoha1
 
PDF
ilide.info-tg-understanding-culture-society-and-politics-pr_127f984d2904c57ec...
jed P
 
PPTX
microservices-with-container-apps-dapr.pptx
vjay22
 
PPTX
covid 19 data analysis updates in our municipality
RhuAyungon1
 
PPTX
Monitoring Improvement ( Pomalaa Branch).pptx
fajarkunee
 
PDF
IT GOVERNANCE 4-2 - Information System Security (1).pdf
mdirfanuddin1322
 
PDF
NVIDIA Triton Inference Server, a game-changing platform for deploying AI mod...
Tamanna36
 
DOCX
brigada_PROGRAM_25.docx the boys white house
RonelNebrao
 
PPTX
Krezentios memories in college data.pptx
notknown9
 
PPTX
Model Evaluation & Visualisation part of a series of intro modules for data ...
brandonlee626749
 
PPTX
Data Analytics using sparkabcdefghi.pptx
KarkuzhaliS3
 
PPTX
MENU-DRIVEN PROGRAM ON ARUNACHAL PRADESH.pptx
manvi200807
 
PPTX
english9quizw1-240228142338-e9bcf6fd.pptx
rossanthonytan130
 
PDF
Exploiting the Low Volatility Anomaly: A Low Beta Model Portfolio for Risk-Ad...
Bradley Norbom, CFA
 
PPTX
Artificial intelligence Presentation1.pptx
SaritaMahajan5
 
PPTX
Module-2_3-1eentzyssssssssssssssssssssss.pptx
ShahidHussain66691
 
PPTX
Mynd company all details what they are doing a
AniketKadam40952
 
PDF
GOOGLE ADS (1).pdf THE ULTIMATE GUIDE TO
kushalkeshwanisou
 
PDF
TESDA License NC II PC Operations TESDA, Office Productivity
MELJUN CORTES
 
Indigo dyeing Presentation (2).pptx as dye
shreeroop1335
 
RESEARCH-FINAL-GROUP-3, about the final .pptx
gwapokoha1
 
ilide.info-tg-understanding-culture-society-and-politics-pr_127f984d2904c57ec...
jed P
 
microservices-with-container-apps-dapr.pptx
vjay22
 
covid 19 data analysis updates in our municipality
RhuAyungon1
 
Monitoring Improvement ( Pomalaa Branch).pptx
fajarkunee
 
IT GOVERNANCE 4-2 - Information System Security (1).pdf
mdirfanuddin1322
 
NVIDIA Triton Inference Server, a game-changing platform for deploying AI mod...
Tamanna36
 
brigada_PROGRAM_25.docx the boys white house
RonelNebrao
 
Krezentios memories in college data.pptx
notknown9
 
Model Evaluation & Visualisation part of a series of intro modules for data ...
brandonlee626749
 
Data Analytics using sparkabcdefghi.pptx
KarkuzhaliS3
 
MENU-DRIVEN PROGRAM ON ARUNACHAL PRADESH.pptx
manvi200807
 
english9quizw1-240228142338-e9bcf6fd.pptx
rossanthonytan130
 
Exploiting the Low Volatility Anomaly: A Low Beta Model Portfolio for Risk-Ad...
Bradley Norbom, CFA
 
Artificial intelligence Presentation1.pptx
SaritaMahajan5
 
Module-2_3-1eentzyssssssssssssssssssssss.pptx
ShahidHussain66691
 
Mynd company all details what they are doing a
AniketKadam40952
 
GOOGLE ADS (1).pdf THE ULTIMATE GUIDE TO
kushalkeshwanisou
 
TESDA License NC II PC Operations TESDA, Office Productivity
MELJUN 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