0% found this document useful (0 votes)
2 views20 pages

AI Unit 3 Python Programming Notes2627

This document provides comprehensive notes on Python programming for Class 11, covering its features, modes of operation, character sets, tokens, data types, control flow statements, and libraries like NumPy and Pandas. It explains the importance of Python in artificial intelligence, detailing how to manipulate data using libraries and perform tasks such as reading and writing CSV files. Additionally, it includes exercises to reinforce learning and understanding of Python concepts.

Uploaded by

Ak Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views20 pages

AI Unit 3 Python Programming Notes2627

This document provides comprehensive notes on Python programming for Class 11, covering its features, modes of operation, character sets, tokens, data types, control flow statements, and libraries like NumPy and Pandas. It explains the importance of Python in artificial intelligence, detailing how to manipulate data using libraries and perform tasks such as reading and writing CSV files. Additionally, it includes exercises to reinforce learning and understanding of Python concepts.

Uploaded by

Ak Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Artificial Intelligence

Class 11
UNIT 3: Python Programming Notes

Python is a general-purpose, high level programming language. It was


created by Guido van Rossum, and released in 1991. Python got its
name from a BBC comedy series – “Monty Python’s Flying Circus”

Features of Python
1. High Level language
2. Interpreted Language
3. Free and Open Source
4. Platform Independent (Cross-Platform) – runs virtually in every
platform if a
5. compatible python interpreter is installed.
6. Easy to use and learn – simple syntax similar to human language.
7. Variety of Python Editors – Python IDLE, PyCharm, Anaconda,
Spyder
8. Python can process all characters of ASCII and UNICODE.
9. Widely used in many different domains and industries.

Interactive Mode
Programmers can quickly run the commands
and try out or test code without generating a
file by using the Python interactive mode,
commonly known as the Python interpreter or
Python shell.

Script Mode
In the script mode, a Python programme can
be written in a file, saved, and then run
using the interpreter.
Python scripts are stored in files with the
“.py” extension. Python scripts are saved by
default in the Python installation folder.
Python character set
The character set in Python refers to the collection of characters used in writing
Python programs. Python supports various characters, including:
1. Letter: Python allows both uppercase (A – Z) and lowercase (a – z) letters.
2. Digit: Digits (0 – 9) can be used but cannot be the first character of a variable.
3. Special Characters: Python supports special characters like arithmetic
operators (+, -, *, /), special symbols (@, #, %, $), and brackets ({}, [], ()).
4. Escape Sequences: Python uses backslash (\) for escape sequences. New line
(\n), tab (\t)
5. Unicode Characters: Python supports Unicode characters, emojis and
mathematical symbols. smiley = “????

Getting Started with Python Programs


Python program consists of Tokens. It is the smallest unit of a program
that the interpreter or compiler recognizes. Tokens consist of
keywords, identifiers, literals, operators, and punctuators. They
serve as the building blocks of Python code.

a. Keywords: Keywords are reserved words. Each keyword has a


specific meaning to the Python interpreter, and we can use a
keyword in our program only for the purpose for which it has been
defined.
As Python is case sensitive, keywords must be written exactly.
b. Identifier:
1. An identifier is a name used to identify a variable, function, class,
module or other object.
2. Generally, keywords (list given above) are not used as variables.
3. Identifiers cannot start with digit and also it can’t contain any special
characters except underscore.
Rule:-
1. The name should begin with an uppercase or a lowercase alphabet or
an underscore sign (_).
2. It can be of any length.
3. It should not be a keyword or reserved word.
4. We cannot use special symbols like !, @, #, $, %, etc.

c. Literals:
In Python, a literal represents a fixed value directly using the
program. It is raw data assigned to a variable.
Literals are immutable, meaning the value of a literal cannot be
changed during program execution.
Python supports several types of literals:
1. Numeric Literals: integer_literal = 100, float_literal = 10.5,
complex_literal = 3 + 5j
2. String Literals: string_literal = ‘Hello, Python!’
3. Boolean Literals: boolean_literals = True
4. Special Literals: x = None
5. List Literals: my_list = [1, “Amit”, 34]
6. Tuple Literals: my_tuple = (1, “Amit”, 34)
7. Dictionary literals: my_dict = {“rollno”: 1, “name”: “Amit”, “age”:
34}
8. Set Literal: my_set = {1, 2, 3}

d. Operators: Operators are symbols or keywords that perform


operations on operands to produce a result. Python supports a wide
range of operators:
1. Arithmetic operators (+, -, *, /, %)

2. Relational operators (==, !=, <, >, <=, >=)

3. Assignment operators (=, +=, -=)

4. Logical operators (and, or, not)

5. Bitwise operators (&, |, ^, <<, >>)

6. Identity operators (is, is not)

7. Membership operators (in, not in)

e. Punctuators: Common punctuators in Python include: ( ) [ ] { } , ; . `


‘ ‘ ” ” / \ & @ ! ? | ~ etc.

Data Types
1. Data types are the classification or categorization of data items.

2. It represents the kind of value that tells what operations can be

performed on a particular data.


3. Python supports Dynamic Typing.
Data Type Description

Accepting values from the user


The input() function retrieves text from the user by prompting
them with a string argument. For instance:
name = input("What is your name?")
Return type of input function is string. So, to receive values of other
types we have to use conversion functions together with input function
Sample Program,
Sample Program,
Write a program to read name and marks of a student and display the total
mark.

In the above example float () is used to convert the datatype into


floating point. The explicit conversion of an operand to a specific type is
called type casting.

Mutable and Immutable Data Types


1. Once a variable of a certain data type has been created and given values,

Python does not enable us to modify its values.


2. Mutable variables are those whose values can be modified after

they have been created and assigned.


3. Immutable variables are those whose values cannot be modified

once they have been created and assigned.


Type Conversion

Type conversion is also known as type casting in Python.


Type conversion refers to the process of changing a value from one data
type to another.
Python supports two main types of type conversion:
1. Explicit Conversion
2. Implicit Conversion

Explicit Conversion
Explicit type conversion, also known as type casting, is used when
a programmer manually converts a value from one data type to another
using a built-in function, such as int(), float(), or str().

Implicit Conversion
When Python converts data types automatically without a programmer’s
instruction, this is referred to as implicit conversion, also known as
coercion.
Implicit type conversion from int to float
Control flow statements in Python
Control flow is the order in which statements, instructions or functions are
executed.

Selection Statement
The if/ if..else statement evaluates test expression and the statements
written below will execute if the condition is true otherwise the statements
below else will get executed.
Indentation is used to separate the blocks.

Sample Program,
Asmita with her family went to a restaurant. Determine the choice of food
according to the options she chooses from the main menu.
Looping Statements
Looping statements in programming languages allow you to execute a
block of code repeatedly. In Python, there are mainly two types of looping
statements: for loop and while loop.

For loop
The “for” keyword is used to start the loop. The loop variable takes
on each value in the specified sequence (e.g., list, string, range).
The colon (:) at the end of the for statement indicates the start of the loop
body. The statements within the loop body are executed for each iteration.

The for loop iterates over each item in the sequence until it reaches the
end of the sequence or until the loop is terminated using
a break statement.

Understanding CSV file (Comma Separated Values)


CSV files are delimited files that store tabular data (data stored in
rows and columns).

It looks similar to spread sheets, but internally it is stored in a


different format. In csv file, values are separated by comma.

Data Sets used in AI programming are easily saved in csv format.

Let us see an example of opening, reading and writing formats for a file
[Link].
Python program,
Write a Program to open a csv file [Link] and display its details

Introducing Libraries
In Python, functions are organized within libraries similar to how library
books are arranged by subjects such as physics, computer science, and
economics.
For example, the “math” library contains numerous functions like
sqrt(), pow(), abs(), and sin(), which
facilitate mathematical operations and calculations.
For example, if we wish to use the sqrt() function in our program,
we include the statement “import math”. This allows us to access and
utilize the functionalities provided by the math library.

NUMPY
NumPy is also known as a numerical Python, is a powerful library in
Python, which helps for numerical computing. NumPy is used
for scientific computing and working with arrays.

Where and why do we use the NumPy library in Artificial


Intelligence?
1. NumPy is a powerful tool for AI that provides multidimensional
arrays and mathematical functions, which are critical in artificial
intelligence.
2. The NumPy library can also be used in data cleaning, model training,
and the foundation of feature engineering.

Creating a Numpy Array – Arrays in NumPy can be created by multiple


ways. Some of the ways are programmed here:
PANDAS
Pandas is an open-source Python library used for working with data sets.
Pandas functions can analyze, explore, clean, and manipulate data. Pandas
are used when we want to work on tabular data like CSV, Excel sheets,
etc. The popularity of pandas in AI is for data analysis.

Where and why do we use the Pandas library in Artificial


Intelligence?
Pandas provides powerful data manipulation and aggregation
functionalities, making it easy to perform complex analysis and generate
insightful visualizations. This capability is invaluable in AI and data-driven
decision-making processes, allowing businesses to gain actionable insights
from their data.
Series
A series is a one-dimensional labeled array that can hold any data
types, like integers, floating numbers, strings, Python objects, etc. An index
is the data label that corresponds to a specific value. For example,

DataFrame
In data science, we often encounter datasets with two-dimensional
structures. This is where Pandas Data Frames
come into play.

A Data Frame is used when we need to work on


mu ltiple columns at a time, i.e., we need to
process the tabular data
Creation of DataFrame
There are several methods to create a DataFrame in Pandas, but here we
will discuss two common approaches:

Dealing with Rows and Columns


A data frame is a two-dimensional data structure; data is arranged in
tabular format in the form of rows and columns. To deal with rows and
columns, some of the basic operations are required like adding new row or
column, deleting row and column, accessing data frame element.
Computer Science
Adding a New Column to a DataFrame:
We can add a new column ‘Fathima’, by mentioning column name as given
below
Adding a New Row to a DataFrame:
We can add a new row to a DataFrame using the [Link][ ] method.
Let us add marks for English subject in Result ➔

Deleting Rows and Columns from a DataFrame:


We need to specify the names of the labels to be dropped and the axis
from which they need to be dropped.

Delete the columns having labels ‘Rajat’, ‘Meenakshi’ and


‘Karthika’’:

Accessing DataFrame Elements


1. Data elements in a DataFrame can be accessed using different ways.

2. Two common ways of accessing are using loc and iloc.

3. [Link][ ] uses label names for accessing and

4. [Link][ ] uses the index position for accessing the

elements of a DataFrame. Let us check an example


Understanding Missing Values
During Data Analysis, it is common for an object to have some missing
attributes. If data is not collected properly it results in missing data. Pandas
provide a function isnull() to check whether any value is missing or not in
the DataFrame.

Attributes of DataFrames
Attributes are the properties of a DataFrame that can be used to fetch data
or any information related to a particular DataFrame.
Let us understand the attributes of DataFrames with the help of DataFrame
Teacher DataFrame:Teacher

Displaying Row Indexes – [Link]


Displaying column Indexes – [Link]

Displaying datatype of each – [Link]

Displaying data in Numpy Array form – [Link]

Displaying total number of rows and columns (row, column) –


[Link]

Displaying first n rows (here n = 2) – Teacher. head (2)

Displaying last n rows (here n = 2) – Teacher. tail (2)


Importing and Exporting Data between CSV Files and DataFrames
We can create a DataFrame by importing data from CSV files. Similarly, we
can also store or export data in a DataFrame as a .csv file.

Importing a CSV file to a DataFrame


Using the read_csv() function, you can import tabular data from CSV
files into pandas dataframe by specifying a parameter value for the file
name.

Exporting a DataFrame to a CSV file


We can use the to_csv() function to save a DataFrame to a text or csv file.
For example, to save the DataFrame Teacher into csv file resultout, we
should write
Teacher.to_csv(path_or_buf=’C:/PANDAS/[Link]’, sep=’,’)

Scikit-learn (Learn)
1. Scikit-learn (Sklearn) is the most useful and robust library for machine

learning in Python.
2. It provides a selection of efficient tools for machine learning and

statistical modeling via a consistent interface in Python.


3. Sklearn is built on (relies heavily on) NumPy, SciPy and Matplotlib.

4. Scikit-learn offers a variety of modules that simplify the process of

building, training, and evaluating machine learning models, making it a


popular choice for various tasks in this domain.
Key Features:
1. Offers a wide range of supervised and unsupervised learning algorithms.
2. Provides tools for model selection, evaluation, and validation.
3. Supports various tasks such as classification, regression, clustering,
dimensionality reduction, and more.
4. Integrates seamlessly with other Python libraries like NumPy, SciPy, and
Pandas.
load_iris (In [Link]): The Iris dataset is a classic and widely
used dataset in machine learning, particularly for classification tasks.

train_test_split (In sklearn.model_selection): Datasets are usually


split into training set and testing set. The training set is used to train the
model and testing set is used to test the model. Most common splitting
ratio is 80: 20. (Training -80%, Testing-20%)
KNeighborsClassifier (In [Link]): Scikit-learn has wide
range of Machine Learning (ML) algorithms which have a consistent
interface for fitting, predicting accuracy, recall etc. Here we are going to
use KNN (K nearest neighbors) classifier.

EXERCISES
A. Multiple choice questions
1. Identify the datatype L = “45”
a. String b. int c. float d. tuple
2. Which of the following function converts a string to an integer
in python?
a. int(x) b. long(x) c. float(x) [Link](x)
3. Which special symbol is used to add comments in python?
a. $ b.// c. /*.... */ d.#
4. Which of the following variable is valid?
a. Str name b.1str c._str d.#Str
5. Elements in the list are enclosed in _____ brackets
a. ( ) b. { } c. [ ] d. /* */
6. Index value of last element in list is ____________________
a. 0 b.-10 c. -1 d.10
7. What will be the output of the following code?
a = [10,20,30,40,50]
print(a[0])
a.20 b.50 c. 10 d.40
8. Name the function that displays the data type of the variable.
a. data( ) b. type( ) c. datatype( ) d. int( )
9. Which library helps in manipulating csv files?
a. files [Link] c. math d. print
10. Which keyword can be used to stop a loop?
a. stop [Link] c. brake d. close
11. What is the primary data structure used in NumPy to
represent arrays of any dimension?
a) Series b) DataFrame c) ndarray d) Panel
12. Which of the following is not a valid method to access
elements of a Pandas DataFrame?
a) Using column names as attributes.
b) Using row and column labels with the .loc[] accessor.
c) Using integer-based indexing with the .iloc[] accessor.
d) Using the .get() method.
13. What is the purpose of the head() method in Pandas?
a) To display the first few rows of a DataFrame.
b) To display the last few rows of a DataFrame.
c) To count the number of rows in a DataFrame.
d) To perform aggregation operations on a DataFrame.
14. Which method is used to drop rows with missing values from
a DataFrame in Pandas?
a) drop_rows()
b) remove_missing()
c) dropna()
d) drop_missing_values
15. Which is not a module of Sklearn?
a) load_iris sb)train_test_split
c)metrics d)Scikit

You might also like