Babaji Vidhyashram School
AI - Reference Material
—------------------------------------------------------------------------------------------------------------------
-------
Subject : Artificial Intelligence
Chapter : Unit 5 - INTRODUCTION TO PYTHON
Grade : 9
—------------------------------------------------------------------------------------------------------------------
------
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.
●
Algorithms and Flowcharts
● Algorithms:
○ An algorithm is a logical, step-by-step method designed to solve a specific
problem.
○ This step-by-step breakdown is crucial for ensuring each part of the
process is clear and contributes effectively to the overall task.
○ Algorithms are created by carefully designing specific instructions that
break down each task into smaller, specific instructions the machine can
follow.
○ Basic rules for writing an effective algorithm include:
■ Starting with a clear understanding of the problem and the desired
outcome.
■ Specifying the data the algorithm will take in (inputs) and what it will
produce (outputs).
■ Organizing the algorithm in a logical, sequential order from start to
finish.
■ Making choices (like "if conditions") and defining what should
happen for each possible outcome.
■ Having a clear endpoint to prevent it from running indefinitely.
■ Reviewing the algorithm for any missing steps, redundancies, or
potential errors.
○ Algorithms involve calculations, reasoning, and data processing to achieve
the desired outcome. They can be represented in different formats like
Natural Language (describing steps in simple, everyday language) and
Pseudocode (writing steps in a simplified, code-like structure without
focusing on syntax).
To understand algorithms better, let us take an example of getting the Email address
and check if it is valid or not..
● Flowcharts:
○ A flowchart is a visual representation of an algorithm or process, using
various symbols to break down and illustrate each step in a logical and
sequential manner.
○ Flowcharts help communicate complex processes clearly and are
particularly useful for humans to understand and follow the flow of a
program or procedure.
○ They break a process into smaller parts and elaborate it using visual
representations.
○ Basic Characteristics of a Flowchart:
■ Shows the logic behind the algorithm.
■ Literally emphasizes individual steps and their inter-connections.
■ Clearly illustrates the flow of programming techniques, making
them valuable in the education of programmers.
■ Observes the control flow from one action to the next action.
○ Common Flowchart Symbols:
■ Terminal Box (Start / End): Represents the start and end of the
process.
■ Input / Output: Represents input and output operations like taking
user input or displaying results.
■ Process / Instruction: Indicates a step where an operation or task is
performed (e.g., calculations, assignments).
■ Decision: Used for decision-making steps where the process can
branch based on a condition (yes/no, true/false).
■ Flow Lines / Connector / Arrow: Shows the direction of the process
flow, indicating the sequence of steps and connecting different
parts of the flowchart.
■
■
■
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.
—------------------------------------------------------------------------------------------------------------------
-
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.
—------------------------------------------------------------------------------------------------------------------
-
Sample Programs and Code Examples
The sources provide numerous code examples to illustrate the concepts:
● Simple Print Statement:
None
x = 5
result = x + 3
print(result) # Output: 8
● Accepting User Input and Displaying Output:
None
name = input("Enter name: ")
age = int(input("Enter your age: ")) # Explicit type
conversion for age
print("Hello", name)
print("How are you,", name, "and age is", age, "years old")
● Basic Arithmetic Operations:
None
a = 20
b = 10
print("Addition:", a + b) # Output: 30
print("Subtraction:", a - b) # Output: 10
print("Multiplication:", a * b) # Output: 200
print("Division:", a / b) # Output: 2.0
print("Modulus:", a % b) # Output: 0
print("Floor Division:", a // b)# Output: 2
print("Exponent:", a ** b) # Output: 10000000000000
● Conditional Statements (if, if-else, if-elif-else):
○ if example: Check if a number is even:
None
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Number is even")
○ if-else example: Check eligibility to vote:
None
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote!")
else:
print("Sorry! you have to wait!!")
○ if-elif-else example: Check number range:
None
number = int(input("Enter the number: "))
if number == 10:
print("number is equal to 10")
elif number == 50:
print("number is equal to 50")
elif number == 100:
print("number is equal to 100")
else:
print("number is not equal to 10, 50 or 100")
● Loops (for, while):
○ for loop example: Iterating through a string:
None
str = "PYTHON"
for i in str:
print(i)
# Output: P, Y, T, H, O, N (each on new line)
○ for loop with range() example: Print numbers 0-9:
None
for i in range(10):
print(i)
# Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
○ while loop example: Print first 4 natural numbers:
None
n = 1
while n <= 4:
print(n)
n += 1
# Output: 1, 2, 3, 4
● List Operations:
○ Creating a list: a = [1, 'apple', 3.14,]
○ Accessing items: print(list)
○ Negative indexing: print(list[-1])
○ Slicing: print(list[1:3])
○ Changing items: list = "pigeon"
○ Adding items (append, extend, insert):
None
list = [1, 2, 'parrot', 'peacock', 'crane']
[Link]("pigeon")
[Link](["kite", "crow"])
[Link](2, "hen")
print(list) # Output: [1, 2, 'hen', 'parrot', 'peacock',
'crane', 'pigeon', 'kite', 'crow']
○ Deleting items (remove, pop, clear, del):
None
list = [1, 2, 'parrot', 'peacock', 'crane']
[Link]('parrot')
[Link](1)
# del list
# [Link]()
print(list)
○ Finding length: len(list)