0% found this document useful (0 votes)
3 views17 pages

Unit7-Advanced Python

The document provides an overview of advanced Python concepts relevant to artificial intelligence for 10th-grade students, covering topics such as Python basics, data types, operators, control flow, and data structures like lists and tuples. It explains the role of Python in AI, the significance of Python's syntax and structure, and how to perform various operations using Python. Additionally, it includes practical examples and rules for coding in Python, emphasizing the importance of indentation and variable management.

Uploaded by

perimeter71
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)
3 views17 pages

Unit7-Advanced Python

The document provides an overview of advanced Python concepts relevant to artificial intelligence for 10th-grade students, covering topics such as Python basics, data types, operators, control flow, and data structures like lists and tuples. It explains the role of Python in AI, the significance of Python's syntax and structure, and how to perform various operations using Python. Additionally, it includes practical examples and rules for coding in Python, emphasizing the importance of indentation and variable management.

Uploaded by

perimeter71
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

Babaji Vidhyashram School

AI - Reference Material

Subject : Artificial Intelligence


Chapter : Unit 7 - ADVANCED PYTHON
Grade : 10

Introduction to Python and AI Concepts

●​ Machines and AI: Machines can be operated by following a set of instructions or


"programs" that define specific tasks and actions to perform efficiently.
AI-enabled machines add an additional layer of adaptability by learning from data
to make decisions or predictions, enabling them to handle more complex or
varied tasks.
●​ Python's Role: Python is a high-level and general-purpose language that can be
used for designing different types of applications.

●​

Python Basics

●​ Python Applications: Python is used for various applications, including Web


Applications, Desktop GUI Applications, Console-based Applications, and
Software Development. It is also widely used in Scientific and Numeric
applications, often involving complex mathematical calculations.
●​ Python IDLE (Integrated Development and Learning Environment):
○​ IDLE is a standard Python development environment.
○​ It is used to execute a single statement just like Python Shell, and also to
create, modify, and execute Python scripts.
○​ IDLE provides a fully-featured text editor to create Python script that
includes features like syntax highlighting, auto-completion, smart indent,
and a debugger.
○​ It also has a debugger with stepping and breakpoint features.
○​ IDLE allows interactive mode, where users can type commands and
execute them immediately, showing outputs on the display.

○​
○​ Python Script Mode: Allows writing multiple lines of code, saving them as
a .py file, and executing them as a program.

○​
●​ First Python Program:
○​ To write and run a Python program, you need to have a Python interpreter
installed.
○​ Programs can be written in interactive mode (for testing small pieces of
code) or script mode (for larger, more complex programs).
○​ In script mode, multiple lines of code are saved in a file and then
executed.
○​ Popular Python IDEs include PyCharm, Spyder, atom, PyDev, Jupyter,
and MS Visual Studio Code.
●​ Python Character Set: A character set consists of a set of valid characters
recognized by a language. Python supports:
○​ Letters: A-Z, a-z.
○​ Digits: 0-9.
○​ Symbols: Space, +, -, *, /, %, =, !=, <, >, <=, >=, &&, ||, !, &, |, (, ), [, ], {, },
#, @, $, etc..
○​ White Spaces: Blank spaces, new line, tabs.
○​ Other Characters: ASCII and Unicode characters.
●​ Python Identifiers:
○​ Identifiers are names given to various program elements like variables,
functions, and classes.
○​ Rules for identifiers:
■​ Always start with a letter (A-Z, a-z) or an underscore (_).
■​ Cannot start with a digit.
■​ Spaces are not permitted.
■​ Keywords cannot be used as identifiers.
■​ No special character other than underscore (_) is allowed.
■​ Identifiers can be of any length.
■​ Python is case-sensitive (e.g., NAME and name are different).
●​ Keywords: These are reserved words that have special meaning in Python and
cannot be used as identifiers. Examples include False, None, True, and, as,
assert, break, class, continue, def, del, elif, else, except, finally,
for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass,
raise, return, try, while, with, yield.
●​
●​ Punctuation: Punctuation marks are used to separate tokens and organize
statements in a Python program. Examples include . (period), , (comma), :
(colon), ; (semicolon), " (double quote), ' (single quote), () (parentheses), []
(square brackets), {} (curly bracket), @ (at the rate), = (assignment), / (forward
slash), # (hash sign).
●​ Indentation in Python:
○​ Leading space or tab at the beginning of a line is considered an
indentation level.
○​ Indentation is significant in Python, indicating a group or block of
statements.
○​ Proper indentation improves program readability and is crucial for correct
execution.
○​ Python recommends four spaces as indentation. Do not mix space and
tab in the same block.
○​ A block can have inner blocks with next level indentation.
●​ Statements in Python: Instructions written in the source code to be executed. A
statement can extend over one or more lines using the parentheses (), braces
{}, square brackets [], or semi-colon ;.

Python Data Types

●​ Data types classify data items, representing the kind of value that tells what
operations can be performed on a particular data.
●​
●​ Standard Built-in Data Types: Numeric, Dictionary, Boolean, Set, and
Sequence Type.
●​ Numeric Types:
○​ Represent numeric values.
○​ Integer: Whole numbers (positive, negative, or zero) without a fractional
part. No limit to how long an integer value can be.
○​ Float: Real numbers with a floating-point representation, defined by a
decimal point.
○​ Complex: Complex numbers represented by complex class (e.g.,
2+3j).
●​ Dictionary: An unordered collection of data values used to store data like a map,
containing key-value pairs. Keys are separated by a comma, and values are
assigned using a colon.
●​ Boolean: A data type with two built-in values: True and False. Boolean objects
are used to evaluate whether a condition is true or false.
●​ Set: An unordered collection of data that is iterable, mutable, and has no
duplicate elements.
●​ Sequence Type:
○​ A sequence allows storing multiple values in an organized and efficient
fashion.
○​ String: A contiguous set of characters represented in the quotation marks.
Strings are immutable.
○​ List: An ordered collection of data types where elements are enclosed in
square brackets []. Lists are mutable (changeable). They can contain
different data types.
○​ Tuple: Similar to lists but immutable (cannot be modified after creation).
Elements are enclosed in parentheses ().

Data Type Conversion


●​ Implicit Type Conversion (Coercion): Python automatically converts data types
in certain situations when performing operations. For example, when an integer
and a float are added, Python converts the integer to a float for the operation.
●​ Explicit Type Conversion (Casting): Involves built-in functions or constructors
to change the data type explicitly. Common conversion functions include int(),
float(), str(), list(), tuple(), dict(), and set().

Python Variables

●​ Variables: A variable is a named memory location used to store values. The


process of creating a variable involves reserving some memory space.
●​ Variable Naming Rules:
○​ Must start with an English letter or an underscore (_).
○​ Cannot start with a numeral (0-9).
○​ Cannot include special characters other than an underscore (_).
○​ The variable name is case sensitive (e.g., Rahul and rahul are
different).
●​ Declaring and Assigning Values:
○​ Python does not bind us to declare variables before using them; they are
created when a value is assigned.
○​ The assignment operator (=) is used to assign a value to a variable.
○​ Assigning a Single Value to Multiple Variables: Allows assigning the same
value to multiple variables at once (e.g., x = y = z = 50).
○​ Assigning Multiple Values to Multiple Variables: Allows assigning different
values to multiple variables at the same time (e.g., a, b, c = 10, 20,
15).
●​ Object Identity: Python handles data internally as objects. When a variable is
assigned a value, it points to that object in memory. If multiple variables are
assigned the same value, they might point to the same object. When a variable's
value is changed, a new object is created, and the variable points to it.
●​ Deleting a Variable: Variables can be deleted using the del keyword (e.g., del
variable_name).

Input and Output in Python

●​ Accepting User Input:


○​ The input() function is used to take input from the user.
○​ By default, the keyboard input is always of string type. You may need to
convert it to other data types (e.g., int, float) if numbers are expected.
●​ Displaying Output:
○​ The print() function is used to display output on the console.
○​ It can print single variables, multiple variables, and expressions.
○​ You can print text messages by enclosing them in single or double quotes.

Python Operators

●​ Operators are symbols that perform an operation between two operands.


●​ Types of Operators:
1.​ Arithmetic Operators: Used for numerical calculations.
■​ + (Addition): Adds values.
■​ - (Subtraction): Subtracts right operand from left.
■​ * (Multiplication): Multiplies values.
■​ / (Division): Divides left operand by right operand.
■​ % (Modulus/Remainder): Divides and returns the remainder.
■​ ** (Exponent): Performs exponential (power) calculation.
■​ // (Integer Division): Division that returns the quotient in which the
digits after the decimal point are removed (rounds down).
2.​ Comparison (Relational) Operators: Compare two values and return
True or False.
■​ == (Equal to): If values of two operands are equal.
■​ != (Not Equal to): If values of two operands are not equal.
■​ > (Greater than): If left operand is greater than right.
■​ < (Less than): If left operand is less than right.
■​ >= (Greater than or Equal to): If left operand is greater than or
equal to right.
■​ <= (Less than or Equal to): If left operand is less than or equal to
right.
3.​ Assignment Operators: Used to assign values to variables. Many are
shorthand for arithmetic operations combined with assignment (e.g., +=,
-=, \*=).
4.​ Logical Operators: Perform logical operations on boolean values and
return boolean results (True or False).
■​ AND: Returns True if both operands are true.
■​ OR: Returns True if any of the two operands are true.
■​ NOT: Used to reverse the logical state of its operand.
●​ Operators Precedence: Defines the order in which operators are evaluated.
1.​ Exponentiation (**).
2.​ Complement, unary plus, and minus (+, -).
3.​ Multiply, divide, modulo, and floor division (*, /, %, //).
4.​ Addition and subtraction (+, -).
5.​ Comparison operators (<, <=, >, >=, !=, ==).
6.​ Equality operators.
7.​ Assignment operators (=, +=, -=, etc.).
8.​ Logical operators (NOT, AND, OR).

Flow of Control: Conditional Statements

●​ Conditional Statements: Control the flow of a program by making decisions


based on certain conditions.
●​ Block: A group of statements logically grouped and executed as a single unit.
Blocks are defined by their indentation level. Python uses indentation to denote
blocks.
●​ if statement: Used to test a particular condition. If the condition is true, a block
of code will be executed.
●​ if-else statement: Provides an alternative block of code to execute if the if
condition is false.
●​ nested if statement: Allows for multiple conditions to be checked. It is an if
statement inside another if statement. Used to create more complex
decision-making logic.
●​ if-elif-else statement: Enables checking multiple conditions and specific
blocks of statements. elif stands for "else if". If the if condition is false, it
checks the next elif block, and so on. If all conditions are false, the else block
is executed.

Flow of Control: Loops

●​ Looping: Allows a program to repeat a specific code segment multiple times. This
reduces code repetition.
●​ Types of Loops: for loop, while loop, and do-while loop.
●​ for loop:
○​ Used to iterate over a sequence (like a string, tuple, or list) or other
iterable objects.
○​ The for loop continues until the given condition is satisfied.
○​ Using range() function with for loop: The range() function generates
a sequence of numbers. The for loop iterates a counter variable along
with the range() function. It can take (start, stop, step)
arguments.
●​ while loop:
○​ Used to repeatedly execute a block of code as long as a specified
condition remains True.
○​ The loop terminates when the condition becomes False.
○​ It is a pre-tested loop, meaning the condition is checked before each
iteration.
○​ The body of the while loop is indented.

Python Lists

●​ Lists:
○​ Ordered collections of data types where elements are enclosed in square
brackets [].
○​ Can contain any number of items and elements of different data types
(integer, float, string, etc.).
○​ Mutable: Elements can be changed, added, or deleted.
○​ Dynamic: Lists are resizable.
○​ Ordered: Elements maintain their order.
○​ Traversable: An index is used to traverse a list.
●​ Creating a List: Lists are created by placing elements inside square brackets []
separated by commas.
●​ Accessing Items:
○​ Items are accessed using indexes, which start from 0 for the first element.
○​ Negative indexing: Allows access from the end of the list, with -1 referring
to the last item.
○​ Range of indexes (Slicing): Used to get a range of elements by specifying
a start and end index (e.g., list[start:end]). The element at the
end index is excluded.
●​ Changing Items: Elements can be changed using assignment operators with
their index (e.g., list[index] = new_value).
●​ Adding Items:
○​ append(): Adds an element to the end of the list.
○​ extend(): Adds all elements of an iterable (like another list) to the end of
the current list.
○​ insert(index, element): Inserts an item at a specified index.
○​ + operator: Can concatenate two lists.
●​ Deleting Items:
○​ pop(index): Removes and returns the element at the given index. If no
index is specified, it removes the last item.
○​ remove(element): Removes the first occurrence of a specified value.
○​ clear(): Empties the list (removes all elements).
○​ del list[index] or del list: Deletes specific items by index or
deletes the entire list. The del keyword cannot delete the list entirely if not
specified, only elements at a given index.
●​ Finding the Length of the List: The len() method determines the number of
items in a list.

Python Tuple:
A tuple in Python is a collection of objects. It is a type of a sequence like strings and lists, but it
is immutable. It means you cannot change the elements of a tuple. The elements of a tuple are
enclosed within parenthesis (). They can be used to store values of different data types.
Characteristics of tuples:
●​ Ordered - Tuple items are stored in an order and this order canno be changed.
●​ Immutable - Tuples are unchangeable or immutable. You v=cannot change, add or
remove items after the tuple has been created.
●​ Allows duplicate values- Tuples can contain duplicate items.
●​ Allows different data type values - The tuples can contain items of different data types.
●​ Creating Tuples:
tup1=(‘Jai’,10,80,’Delhi’)
print(tup1)
O/P
(‘Jai’,10,80,’Delhi’)
#Empty Tuple creation
tup2=()
print(tup2)
O/P
()
●​ A tuple can be created by enclosing elements inside parentheses() and all the elements
can be separated by commas. An empty type can also be created.
●​ A tuple with a single element can be created by putting a comma after the element inside
the parentheses.
●​ Example:
​ t=(20,)
​ print(t)
​ O/P
​ (20,)
●​ You can perform many operations on a tuple like concatenation, repetition, slicing,etc.
●​
●​ Tuple items can be accessed by using the slicing operator colon’:’. Slicing uses indexing,
either positive or negative.
Syntax: SI = T(Start:Stop:Step)
●​ To access the non-consecutive items, you can use the step value in slicing.

●​
●​ Concatenation means to join two values together. You can concatenate two tuples
together in Python using ‘+’ operator. While concatenating, a tuple allows you to add
duplicate values.

●​
●​ The ‘*’ operator is used to repeat the elements of a tuple by a specified number of times.
The elements in the tuple are not copied, but are referenced multiple items. Consider the
following example to understand the working of the repetition operator in tuples.

●​
●​ The ‘in’ and ‘not in’ operators are the membership operators. They are used to check
whether a value exists in the tuple or not. If the value is found it returns True, otherwise it
returns False.

●​
●​ Traversing a tuple means to visit the elements of the tuple at least once. This can be
done by using loops. Traversing is also called iterating. The following examples show the
use of loops to traverse the tuples. Print all the items of a tuple by referring to their index
numbers using a loop.

●​
●​ Built In functions:
○​ len()- to find the length of the tuple
○​ tuple()- constructor function. Used to create an empty tuple at will as a
tuple with values by passing a sequence to the tuple() function.
item=tuple() #creates empty tuple
Item = tuple(‘Computer’)# create a tuple with these sequence
(‘C’,’o’,’m’,’p’,’u’,’t’,’e’,’r’)
●​ count() - returns the total number of times an element has appeared in a
tuple.
●​ index()- returns the index of the first occurrence of a given element in the
tuple.
●​ sorted()- the function sorts the elements of a tuple. The sorting is done in
an ascending order by default. It returns a new sorted tuple and does not
mostly the original tuple.
Eg:
numbers=(27.67,55,43,69,98,64)
print(sorted(numbers))
O/P
(27,43,55,64,67,69,98)
●​ Python Libraries and Packages:
Python libraries and packages are collections of pre-written code modules that provide a
wide range of functionalities. These packages provide modules, functions and other
resources that can be used to perform specific tasks. These packages can be installed
and imported into your Python programs to utilise their functionalities.

●​
●​ There are several ways to import modules into python
○​ Importing the entire module: import <modulename> allows you to access all
functionalities provided by the package.
○​ Eg: import numpy
○​ You can import module with an alias name also: import numpy as np
○​ Importing all functions from the library using from keyword: will import all
functions and objects from the library.
○​ Eg: from numpy import *
○​ Importing Specific function alone using from keyword: with this we can
import only required functions and objects from the library.
○​ Eg: from numpy import array
●​ NumPy - stands for numerical python. It is a fundamental package for numerical
computations. It provides support for arrays and matrices.
○​ ndarray Object: At the core of NumPy is the ndarray object, which represents a
high-performance, multi-dimensional array. These arrays are significantly faster
and more memory-efficient than standard Python lists for numerical data,
especially for large datasets.

○​ Example:
import numpy as np
# Create a NumPy array from a Python list
arr = [Link]([1, 2, 3, 4, 5])
print("NumPy array:", arr)

# Perform a vectorized operation (element-wise addition)


arr_plus_one = arr + 1
print("Array after adding 1:", arr_plus_one)

# Create a 2D array (matrix)


matrix = [Link]([[1, 2], [3, 4]])
print("2D array (matrix):\n", matrix)

# Perform matrix multiplication


matrix_product = [Link](matrix, matrix)
print("Matrix product:\n", matrix_product)
●​ Pandas- is a powerful data manipulation and analysis library. It offers data structures like
Series and DataFrame for efficient handling of structured data.
●​ Matplotlib- is a comprehensive library for creating static, animated and interactive
visualizations in Python. It is often used for creating plots, charts and graphs.
○​ Example:
import [Link] as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 5, 3]

# Create a line plot


[Link](x, y)

# Add labels and title


[Link]("X-axis Label")
[Link]("Y-axis Label")
[Link]("Simple Line Plot")

# Display the plot


[Link]()
●​ NLTK(Natural Language Toolkit): is a library for working with human language
data(text). It is basically used in NLP applications.
●​ OpenCV - is a library used in computer vision applications. It is used in image
manipulation and processing like resizing, cropping object detection etc.
●​ Statistics- is a built-in module that provides functions for calculating mathematical
statistics of numeric data.
○​ Measures of Central Tendency:
■​ mean(): Calculates the arithmetic mean (average) of the data.
■​ median(): Calculates the median (middle value) of the data.
■​ mode(): Calculates the mode (most frequent value) of the data.
■​ harmonic_mean(): Calculates the harmonic mean of the data.
■​ median_low(), median_high(), median_grouped(): Provide specialized
median calculations for different data scenarios.
○​ Measures of Variability (Spread):
■​ stdev(): Calculates the sample standard deviation.
■​ pstdev(): Calculates the population standard deviation.
■​ variance(): Calculates the sample variance.
■​ pvariance(): Calculates the population variance.
○​ Example:
import statistics

data = [1, 2, 2, 3, 4, 5, 5, 5, 6]

print(f"Mean:”, [Link](data))
print(f"Median:”, [Link](data))
print(f"Mode:”,[Link](data))
print(f"Standard Deviation:”,[Link](data))

●​ Math - is a built-in library that provides access to a wide range of mathematical functions
and constants. It is designed to perform standard mathematical operations on
floating-point numbers with precision.
○​ Constants: It includes important mathematical constants like [Link] (for the
value of pi), math.e (for Euler's number), and [Link].
○​ Numeric functions: Provides functions for basic numerical operations such as
[Link]() (square root), [Link]() (absolute value), [Link]() (round up),
[Link]() (round down), [Link]() (truncate to integer), [Link]() (greatest
common divisor), and [Link]().
○​ Logarithmic and power functions: Offers functions for logarithms and powers,
including [Link]() (natural logarithm), math.log10() (base-10 logarithm),
math.log2() (base-2 logarithm), [Link]() (e raised to a power), and [Link]()
(x raised to the power of y).
○​ Trigonometric functions: Includes functions for trigonometric calculations like
[Link](), [Link](), [Link](), and their inverse counterparts ([Link](),
[Link](), [Link]()). It also provides hyperbolic trigonometric functions.
○​ Angle conversion: Functions like [Link]() and [Link]() are
available for converting angles between radians and degrees.
○​ Example:
import math
# Accessing constants
print([Link])
print(math.e)

# Using functions
print([Link](25))
print([Link](10))
print([Link]([Link](90)))

—------------------------------------------------------------------------------------------------------------------

Important Notes and Points

●​ Input Handling: The input() function, used to accept input from the user,
always returns the input as a string. If numeric input is required, type
conversion (e.g., using int() or float()) must be performed.
●​ Output Display: The print() function is used to display output and can also
display the values of variables.
●​ Variable Scope (Implicit): Variables are assigned values directly, and the
print() function can be used to display these values.
●​ Literals: Literals are immutable objects, representing fixed numeric or string
values.
●​ Special Literal: Python has a special literal, None.
●​ Punctuation Marks: These are used to separate tokens and organize
statements in Python.
●​ Python File Extension: Python program files typically have the .py extension.
●​ Python Module Importing: Usage of Python modules and its functions, how to
access functions(use .(dot) operator).

Sample Viva Questions:

●​ Who invented Python?


●​ How do you print something on the screen in Python?
●​ How do you take input from the user in Python?
●​ What are variables in Python?
●​ What is the default type of input()?
●​ Name some datatypes in Python?
●​ Name a few functions used in lists?
●​ Name the function used to create a list?
●​ What is the difference between a list and a tuple?
●​ Explain the use of if-else statements.
●​ What is a for loop used for?
●​ What is a while loop used for?
●​ Explain the difference between append(), extend() and insert().
●​ How do you access individual characters or part of a list?
●​ What is indentation in Python?
●​ What are comments in Python and why are they used?

—------------------------------------------------------------------------------------------------------------------
-

You might also like