Introduction to Python Class 9 Notes

Introduction to Python Class 9 Notes – The CBSE has changed the previous textbook and the syllabus of Std. IX. The new notes are made based on the new syllabus and based on the New CBSE textbook.  All the important Information are taken from the Artificial Intelligence Class IX Textbook Based on CBSE Board Pattern.

Introduction to Generative AI Class 9 Notes

A programming language is a vocabulary and set of grammatical rules for instructing a computer to perform specific tasks. Though there are many different programming languages such as BASIC, Pascal, C, C++, Java, Haskell, Ruby, Python, etc.

Introduction to Python Class 9 Notes

What is an Algorithm?

To write a logical step-by-step method to solve the identified problem is called algorithm, in other words, an algorithm is a procedure for solving problems.

What is a flowchart?

A flowchart is the graphical or pictorial representation of an algorithm with the help of different symbols, shapes and arrows in order to demonstrate a process or a program. The graphics below represent different parts of a flowchart.

flow chart in programming language

How to Use Flowcharts to Represent Algorithms

Example 1: Print 1 to 20

example of flow chart and Algorithm

Example 2: Convert Temperature from Fahrenheit (℉) to Celsius (℃)

Convert Temperature from Fahrenheit (℉) to Celsius (℃) flowchart and algorithm

What is program?

A computer program is a collection of instructions that perform a specific task when executed by a computer. This computer program usually written in a programming language. For example, C++, Java, Python, and Ruby are used to construct programs.

Why python for AI?

Nowadays, artificial intelligence is a trending technology of the future; there are many applications around us based on AI. To develop an AI application, you require any one of the following programming languages, like Lisp, Prolog, C++, Java, or Python. Nowadays, Python is the most popular programming language used to design AI applications.

Python is the most popular of these because of the following reasons:

  1. Simple to understand, read, and maintain
  2. Clear syntax and a simple keyword structure
  3. Python includes a large library of built-in functions that can be used to tackle a wide range of problems.
  4. Python features an interactive mode that enables interactive testing and debugging of code snippets.
  5. Python runs on a wide range of operating systems and hardware platforms, with the same user interface across all of them.
  6. Python includes interfaces to all major open source and commercial databases, as well as a more structured and robust framework and support for big systems than shell scripting.

Applications of Python

Python is a high-level, general-purpose programming language. It is different from other languages such as C and Java that are designed to be compiled to machine code. Python is easy to learn and can be used to write virtually anything that can be described in code.

There are different type of Python Application – 

  1. Web and Internet Development 
  2. Desktop GUI Application
  3. Software Development
  4. Database Access
  5. Business Application
  6. Games and 3D Graphics

Installation of Python

Python is a cross-platform programming language, which means it runs on a variety of platforms including Windows, MacOS or Linux operating system.

To write and run Python program, we need to have Python interpreter installed in our computer.

Downloading and setting up Python

  • Step 1: Download Python from python.org using link python.org/downloads
  • Step 2: Select appropriate download link as per Operating System [Windows 32 Bit/64 Bit, Apple iOS]
  • Step 3: Click on Executable Installer 
  • Step 4: Install 

Python IDLE installation

Python IDLE installation
Python IDLE installation 1

Run in the Integrated Development Environment (IDE)

After installing Python, you’ll need an IDE to write Python programmes. IDLE is a Python editor with a graphical user interface. IDLE stands for Integrated Development Environment. This IDLE is also known as the Python shell, and it has two modes of operation: interactive mode and script mode. Interactive Mode allows us to communicate with the operating system, whereas Script Mode allows us to generate and edit Python source files.

Interactive Mode

Python IDLE Shell provides a Python prompt, You can write single line python commands and execute them easily. 

python IDLE interactive mode
Script Mode

In Python, the Script Mode allows you to add numerous lines of code. In script mode, we type a Python programme into a file and then use the interpreter to run the code. Working in interactive mode is useful for beginners and for testing little parts of code because it allows us to test them right away.

python IDLE script mode

Python Statement and Comments

Python Statement

A statement is a piece of code that can be executed by a Python interpreter. So, in simple words, anything written in Python is a statement.  In The Python programming language, there are various types of statements, such as assignment statements, conditional statements, looping statements and so on. These assist the user in obtaining the desired result.

Multiline Statement 

The token NEWLINE character is used at the end of a Python statement. However, Statements in Python can be extended to one or more lines using parentheses (), braces {}, square brackets [], semi-colon (;), continuation character slash (). When we need to do long calculations and cannot fit these statements into one line, we can make use of these characters.

Type of Multi-line StatementUsage
Using Continuation Character (/)s = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
Using Parentheses ()n = (1 * 2 * 3 + 4 – 5)
Using Square Brackets []footballer = [‘MESSI’,
‘NEYMAR’,
‘SUAREZ’]
Using braces {}x = {1 + 2 + 3 + 4 + 5 + 6 +
7 + 8 + 9}
Using Semicolons ( ; )flag = 2; ropes = 3; pole = 4

Python Comments

In Python, comments are lines of code that are skipped by the interpreter while the programme is being run. Comments improve the readability of the code and assist programmers in completely comprehending it. In Python there are two types of comment.

comments in python

Python Keywords and Identifiers

Keywords – Keywords are reserved words in Python . Keywords are predefined words with specific meanings. The keyword can’t be used as a variable name, function name, or identifier. Except for True and False, all keywords in Python are written in lower case.

Example of Keywords –

KeywordsKeywordsKeywordsKeywordsKeywords
faseclassfinallyisreturn
Nonecontinuefor lambdatryTrue
deffromnonlocalwhileand
delglobalnotwithas
elifassertifelseimport
passbreakexceptinraise

Identifiers – An identifier is a name given to a variable, function, class, module, or other object. The identification is made up of a series of digits and underscores. The identification should begin with a letter or an Underscore and then be followed by a digit. A-Z or a-z, an UnderScore (_), and a numeral are the characters (0-9). Special characters (#, @, $, percent,!) should not be used in identifiers.

  1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _.
  2. An identifier cannot start with a digit
  3. Keywords cannot be used as identifiers
  4. We cannot use special symbols like !, @, #, $, % etc. in our identifier
  5. Identifier can be of any length
  6. Python is a case-sensitive language.

Example of Identifier

IdentifierIdentifierIdentifierIdentifier
var1_var1_1_varvar_1

Variables, Constants and Data Types

1. Variables 

A variable is a memory location where you store a value in a programming language. In Python, a variable is formed when a value is assigned to it. Declaring a variable in Python does not require any further commands.

There are a certain rules and regulations we have to follow while writing a variable

  1. A number cannot be used as the first character in the variable name. Only a character or an underscore can be used as the first character.
  2. Python variables are case sensitive.
  3. Only alpha-numeric characters and underscores are allowed.
  4. There are no special characters permitted.

Examples on Variables

TaskSample CodeOutput
Assigning a value to a variableWebsite = “cbseskilleducation.com”
print (Website)
cbseskilleducation.com
Changing value of a variableWebsite = “xyz.com”
print (Website)
Website = “cbseskilleducation.com”
print (Website)
xyz.com
cbseskilleducation.com
Assigning different values to different variablesa, b, c = 5, 3.2, “Hello”
print(a)
print(b)
print(c)
5
3.2
Hello
Assigning same value to different variablex = y = z = “Same”
print(x)
print(y)
print(z)
Same
Same
Same

2. Constants

A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as containers that hold information which cannot be changed later.

Rules and Naming convention for variables and constants

  • Create a name that makes sense. Suppose, vowel makes more sense than v.
  • Use camelCase notation to declare a variable. It starts with lowercase letter. For example: myName
  • Use capital letters where possible to declare a constant. For example: PI
  • Never use special symbols like !, @, #, $, %, etc.
  • Constant and variable names should have combination of letters in lowercase or uppercase or digits or an underscore (_).

Example: Declaring and assigning value to a constant

Create a info.py

NAME = "Ajay" 
AGE = 24

Create a main.py

import info 
print(info.NAME) 
print(info.AGE) 

When you run the program the output will be,

Ajay 
24 

2. Datatype 

In Python, each value has a datatype. Data types are basically classes, and variables are instances (objects) of these classes, because everything in Python programming is an object.

Python has a number of different data types.

python datatypes

a. Number Datatype

Numerical Values are stored in the Number data type. There are four categories of number datatype –

  1. Int – Int datatype is used to store the whole number values. Example: x=500
  2. Float – Float datatype is used to store decimal number values. Example: x=50.5
  3. Complex – Complex numbers are used to store imaginary values. Imaginary values are denoted with ‘j’ at the end of the number. Example: x=10 + 4j
  4. Boolean – Boolean is used to check whether the condition is True or False. Example: x = 15 > 6      type(x)

 b. Sequence Datatype

A sequence is a collection of elements that are ordered and indexed by positive integers. It’s made up of both mutable and immutable data types. In Python, there are three types of sequence data types:

  1. String – Unicode character values are represented by strings in Python. Because Python does not have a character data type, a single character is also treated as a string. Single quotes (‘ ‘) or double quotes (” “) are used to enclose strings. These single quotes and double quotes merely inform the computer that the beginning of the string and end of the string. They can contain any character or symbol, including space. Example: name =” Rakesh Kumar”
  2. List – A list is a sequence of any form of value. The term “element” or “item” refers to a group of values. These elements are indexed in the same way as an array is. List is enclosed in square brackets. Example: dob = [19,”January”,1995] 
  3. Tuples – A tuple is an immutable or unchanging collection. It is arranged in a logical manner, and the values can be accessed by utilizing the index values. A tuple can also have duplicate values. Tuples are enclosed in (). Example: newtuple = (15,20,20,40,60,70)

c. Sets Datatype

A set is a collection of unordered data and does not have any indexes. In Python, we use curly brackets to declare a set. Set does not have any duplicate values. To declare a set-in python we use the curly brackets.

Example:

>>> a = {1,2,2,3,3,3} 
>>> a 
        {1,2,3} 

d. Mapping

This is an unordered data type. Mappings include dictionaries.

Dictionaries 

In Python, Dictionaries are used generally when we have a huge amount of data. A dictionary is just like any other collection array. A dictionary is a list of strings or numbers that are not in any particular sequence and can be changed. The keys are used to access objects in a dictionary. Curly brackets are used to declare a dictionary.  Example:

>>> d = {1:'Ajay','key':2} 
>>> type(d) 
        <class 'dict'> 

Operators

Operators are symbolic representations of computation. They are used with operands, which can be either values or variables. On different data types, the same operators can act differently. When operators are used on operands, they generate an expression.

 Operators are categorized as –

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators

Arithmetic Operators

Mathematical operations such as addition, subtraction, multiplication, and division are performed using arithmetic operators.

OperatorMeaningExpressionResult
+Addition20 + 2040
Subtraction30 – 1020
*Multiplication10 * 1001000
/Division30 / 1020
//Integer division25 // 102
%Reminder25 % 105
**Raised to power3 ** 29

Assignment Operator

When assigning values to variables, assignment operators are used.

OperatorExpressionEquivalent to
=x = 10x = 10
+=x += 10x = x + 10
-=x -= 10x = x = 10
*=x *= 10x = x * 10
/=x /= 10x = x / 10

Comparison Operator

The values are compared using comparison operators or relational operators. Depending on the criteria, it returns True or False.

OperatorMeaningExpressionReult
>Greater Than20 > 10True
<Less Than10 < 20True
==Equal To20 == 20True
!=Not Equal To20 != 10True

Logical Operator 

Logical operators are used to combine the two or more then two conditional statements –

OperatorMeaningExpressionResult
AndAnd Operator– True and True
– True and False
True
False
OrOr Operator– True or False
– False or False
True
False
NotNot Operator– Not False
– Not True
True
False

Type Conversion

Type conversion is the process of converting the value of one data type (integer, text, float, etc.) to another data type. There are two types of type conversion in Python.

  1. Implicit Type Conversion 
  2. Explicit Type Conversion

Implicit Type Conversion

Python automatically changes one data type to another via implicit type conversion. There is no need for users to participate in this process.

Example: 

x = 5y = 2.5z = x / z

In the above example, x is containing integer value, y is containing float value and in the variable z will automatically contain float value after execution. 

Explicit Type Conversion

Users transform the data type of an object to the required data type using Explicit Type Conversion. To do explicit type conversion, we employ predefined functions such as int(), float(), str(), and so on. Because the user casts (changes) the data type of the objects, this form of conversion is also known as typecasting.

Example : Birth_day = str(Birth_day) 

Python Input and Output

Output – To output data to the standard output device, we use the print() method.

Sample CodeOutput
a = 20
b = 10
print(a + b)
30
print(15 + 35)50
print(“My name is Kabir”)My name is Kabi
a = “tarun”
print(“My name is :”,a)
My name is : tarun
x = 1.3
print(“x = /n”, x)
x =
1.3
m = 6
print(” I have %d apples”,m)
I have 6 apples

Input – In python, input() function is used to take input from the users.

SyntaxMeaning
<String Variable>=input(<String>)For string input
<Integer Variable>=int(input(<String>))For integer input
<float Variable>=float(input(<String>))For float (Real no.) input

Flow of Control and Conditions

There are three control flow statements in Python – if, for and while.

If Statement

The if statement is used to check a condition: if the condition is true, we run a block of statements (called the if-block).

Note –

  • In Python, the body of the if statement is indicated by the indentation. Body starts with an indentation and the first unindented line marks the end.
  • Python interprets non-zero values as True. None and 0 are interpreted as False.

Syntax:

if test expression: 
   statement(s) 
if…else Statement

The if..else statement evaluates test expression and will execute body of if only when test condition is True. If the condition is False, body of else is executed. Indentation is used to separate the blocks.

Example:

#A program to check if a person can vote  
age = input(“Enter Your Age”) 
if age >= 18: 
   print(“You are eligible to vote”) 
else: 
   print(“You are not eligible to vote”) 
if…elif…else Statement

The elif is short for else if. It allows us to check for multiple expressions. If the condition for if False is, it checks the condition of the next elif block and so on. If all the conditions are False, body of else is executed.

Example:

#To check the grade of a student 
Marks = 60 
if marks > 75: 
   print("You get an A grade") 
elif marks > 60: 
   print("You get  a B grade") 
else: 
   print("You get a C grade") 
Python Nested if statements

We can have an if…elif…else statement inside another if…elif…else statement. This is called nesting in computer programming. Any number of these statements can be nested inside one another. Indentation is the only
way to figure out the level of nesting.

Example:

# In this program, we input a number 
# check if the number is positive or 
# negative or zero and display 
# an appropriate message 
# This time we use nested if 

num = float(input("Enter a number: ")) 
if num >= 0: 
    if num == 0: 
          print("Zero") 
    else: 
          print("Positive number") 
else: 
    print("Negative number") 
The For Loop

A for loop is a control flow statement in Python that allows you to execute a block of code repeatedly based on the condition given.

Syntax:

for val in sequence: 
      Body of for 

val is the variable that takes the value of the item inside the sequence on each iteration.

Example:

# Program to find the sum of all numbers stored in a list 
# List of numbers 

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] 
# variable to store the sum 

sum = 0 
# iterate over the list 

for val in numbers: 
      sum = sum+val 

# Output: The sum is 48  
print("The sum is", sum)
The while Statement

The while statement allows you to repeatedly execute a block of statements as long as a condition is true. A while statement is an example of what is called a looping statement. A while statement can have an optional else clause.

Syntax

while test_expression: 
         Body of while

Example:

# Program to add natural 
# numbers upto  
# sum = 1+2+3+...+n 
# To take input from the user, 
# n = int(input("Enter n: ")) 

n = 10 
# initialize sum and counter 

sum = 0 
i = 1 

while i <= n: 
         sum = sum + i 
         i = i+1    # update counter 

# print the sum 
print("The sum is", sum)

More About Lists and Tuples

Introduction to Lists

List is a sequence of values of any type. Values in the list are called elements / items. List is enclosed in square brackets.

Example:

a = [1,2.3,"Hello"]
How to create a list?

In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ], separated by commas. It can have any number of items and they may be of different types (integer, float, string etc.).

Example:

#empty list
empty_list = []

#list of integers
age = [15,12,18]

#list with mixed data types
student_height_weight = ["Ansh", 5.7, 60]

Note: A list can also have another list as an item. This is called nested lists.

# nested list
student marks = ["Aditya", "10-A", [ "english",75]]
How to access elements of a list?

A list is made up of various elements which need to be individually accessed on the basis of the application it is used for. There are two ways to access an individual element of a list:

  • List Index
  • Negative Indexing
List Index

A list index is the position at which any element is present in the list. Index in the list starts from 0, so if a list has 5 elements the index will start from 0 and go on till 4.

Negative Indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.

index and negative index

Adding Element to a List

We can add an element to any list using two methods :

  • Using append() method
  • Using insert() method
  • Using extend() method

Using append() method

In Python, the append() method is used to add a single element to the end of a list.

python list append() method
List = []
print("Initial blank List: ")
print(List)

# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)

print("\nList after Addition : ")
print(List)

Using insert() method

In Python, the insert() method is used to add a single element at the specified position.

# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)

# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Kabir')
print("\nList after Insert Operation: ")
print(List)

Output: 

Initial List:
[1, 2, 3, 4]

List after Insert Operation:
['Kabir', 1, 2, 3, 12, 4]

Using extend() method

In Python, the extend() method is used to add multiple elements at the same time at the end of the list.

# Creating new list
List = [1,2,3,4]
print("Initial List: ")
print(List)

# Addition of multiple elements
# to the List at the end
# (using Extend Method)
List.extend([8, 'Artificial', 'Intelligence'])
print("\nList after Extend Operation: ")
print(List)

Output:

Initial List: 
[1, 2, 3, 4]

List after Extend Operation:
[1, 2, 3, 4, 8, 'Artificial', 'Intelligence']

Removing Elements from a List

Elements from a list can removed using two methods :

  • Using remove() method
  • Using pop() method

Using remove() method

In Python, the remove() method is used to remove the first occurrence of searched element from the list.

# Creating a List
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12]
print("Intial List: ")
print(List)

# Removing elements from List
# using Remove() method
List.remove(5)
List.remove(6)
print("\n List after Removal: ")
print(List)

Output:

Intial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

List after Removal:
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]

Using pop() method

Pop() function can also be used to remove and return an element from the set, but by default it removes only the last element of the set, to remove an element from a specific position of the List, index of the element is passed as an argument to the pop() method.

# Removing element from the
# Set using the pop() method
List.pop()
print("\nList after popping an element: ")
print(List)

# Removing element at a
# specific location from the
# Set using the pop() method
List.pop(2)
print("\nContent after pop ")
print(List)

Output: 

List after popping an element:
[1, 2, 3, 4]

List after popping a specific element:
[1, 2, 4]

Slicing of a List

In python, there are multiple ways to print the whole List with all the elements, but to print a specific range of elements from the list, we use Slice operation. Slice operation is performed on Lists with the use of colon(:).

  • To print elements from beginning to a range use [:Index]
  • To print elements from end use [:-Index]
  • To print elements from specific Index till the end use [Index:]
  • To print elements within a range, use [Start Index: End Index]
  • To print whole List with the use of slicing operation, use [:]
  • To print whole List in reverse order, use [::-1].
Slice operation in python

Slicing

# Creating a List
List= ['G','O','O','D','M','O', 'R','N','I','N','G']
print("Initial List: ")
print(List)

# using Slice operation
Sliced_List = List[3:8]
print("\nSlicing elements in arange 3-8: ")
print(Sliced_List)

Output:

Initial List:
['G','O','O','D','M','O','R','N','I','N','G']

Slicing elements in a range 3-8:
['D', 'M', 'O','R', 'N']

Slicing using negative index of list

# Creating a List
List= ['G','O','O','D','M','O', 'R','N','I','N','G']
print("Initial List: ")
print(List)

# Print elements from beginning
# to a pre defined point using Slice
Sliced_List = List[:-6]
print("\nElements sliced till 6th element from last: ")
print(Sliced_List)

Output:

Initial List:
['G','O','O','D','M','O','R','N','I','N','G']

Elements sliced till 6th element from last:
['G','O','O','D','M','O']

Updated Class 9 AI Notes

Subject Specific skills Notes (40 Marks)

Employability skills Notes ( 10 Marks )

Old Subject Specific skills Notes (For revision)

Disclaimer: We have taken an effort to provide you with the accurate handout of “AI Reflection Project Cycle and Ethics Class 9 Notes“. If you feel that there is any error or mistake, please contact me at anuraganand2017@gmail.com. The above CBSE study material present on our websites is for education purpose, not our copyrights. All the above content and Screenshot are taken from Artificial Intelligence Class 9 CBSE Textbook and Support Material which is present in CBSEACADEMIC website, This Textbook and Support Material are legally copyright by Central Board of Secondary Education. We are only providing a medium and helping the students to improve the performances in the examination. 

For more information, refer to the official CBSE textbooks available at cbseacademic.nic.in

2 thoughts on “Introduction to Python Class 9 Notes”

Leave a Comment

error: Content is protected !!