0% found this document useful (0 votes)
21 views19 pages

Introduction To Python Class 9 AI Notes

The document provides an introduction to Python programming for Class 9 AI students, covering its definition, features, and applications in AI. It explains Python's syntax, data types, and how to create and run Python programs, including the use of variables, operators, and expressions. Additionally, it outlines the structure of Python programs and the importance of indentation, keywords, and identifiers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views19 pages

Introduction To Python Class 9 AI Notes

The document provides an introduction to Python programming for Class 9 AI students, covering its definition, features, and applications in AI. It explains Python's syntax, data types, and how to create and run Python programs, including the use of variables, operators, and expressions. Additionally, it outlines the structure of Python programs and the importance of indentation, keywords, and identifiers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Introduction to Python Class 9 AI Notes

Class 9 AI Introduction to Python Notes

A computer program is a set of instructions written in a programming language that a


computer can understand and execute. These instructions enable the computer to perform
specific tasks, like calculations, data manipulation, and controlling hardware.
Programs are the building blocks of software applications and the operating system, which is
the core software that manages the computer’s resources.

Python is a general purpose interpreted, interactive, object oriented and high-level


programming language. It was initially designed by Guido Van Rossum in 1991 and
developed by Python Software Foundation.
This programming language lets you work quickly across integrated systems more efficiently.
Python is dynamically typed and garbage collected. Because of its simplicity in coding and
powerful features, it works brilliantly for both beginners to experts.
Python is based on two programming languages which are as follows:

 ABC language, is an interactive programming and teaching language, originally


intended as a good replacement of BASIC.

 Modula-3 supports interfaces, objects and generics.

Python interpreters are available for many operating systems such as Windows, MacOS etc.

Python uses English keywords frequently where as other languages use punctuations.
Python uses whitespace indentation rather than curly brackets to delimit blocks.

Python for AI

Python is a widely used programming language for artificial intelligence due to its
readability, extensive libraries, and strong community support. Data scientists and engineers
heavily rely on Python to build and prototype AI systems, making it a popular choice for
developing next-generation AI solutions.
Lisp, Prolog, C++, Java, and Python are some of the programming languages that can be used
to create AI applications. Python is the most popular of these because of the following
reasons:
1. Easy to use and Readable Python’s syntax is clear and concise, resembling natural
language, ‘making it easier to learn and understand for beginners and those
maintaining code.

2. Object-Oriented and Procedural Programming Python supports both Procedural and


Object-Oriented programming. Functions promote code reusability, while classes and
objects allow modeling real-world entities.

3. Portability Python code is portable across different operating systems (Windows,


Mac, Linux) without major modifications due to the use of a bytecode interpreter.

4. Free and Open-Source Python is free to use and distribute for any purpose, including
commercial projects, under an OSI-approved open-source license.

5. Extensive Standard Library Python boasts a rich standard library containing modules
for various tasks like string manipulation, networking, and file handling. This reduces
the need to write code from scratch.

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 types of Python applications

 Web and Internet Development

 Desktop GUI Application

 Software Development

 Business Application

 Database Access ‘

 Games and 3D Graphics

Getting Started with Python Class 9 Notes

 Python is a cross-platform programming language, which means it-runs on a variety


of platforms including Windows, MacOS or Linux operating system.

 A Python interpreter must be installed on our computer in order to write and run
Python programs.

 Python works on a number of popular operating systems, including windows server


operating system.

 Installation of Python on the windows server operating system is a simple.


 You must download the Python setup from [Link] and running it on your server.

Working in Python Class 9 Notes

Generally programmers write stand alone scripts, that are independent to live
environments. Then, they save it with a .py extension, which indicates to the operating
system and programmer that the file is actually a Python program. After the interpreter is
invoked, it reads and interprets the file.
User can run a program with three ways in Python

(i) Python (Command line)

Python is an interpreted language which can directly run on command prompt with no
argument.
To start Python with command line, follow given step
Start → All Programs → Python 3.7 → Python 3.7 (32-bit).
Python 3.7 (32-bit) window will appear in your computer, where you can write code and
execute it.

Python gives the output after you entered statement and press enter key. In command line
mode, you type

Indentation plays a very crucial role in Python programming.


For example, if you give extra space between >>> print, it will give syntax error.

(ii) Interactive Mode IDLE (Python GUI)

IDLE stands for Integrated Development Environment. You can run Python from a Graphical
User Interface (GUI) environment as well, if you have a GUI application on your system that
supports Python.
If you are not able to set-up the environment properly, then you can take help from your
system admin.
Make sure the Python environment is properly set-up and working perfectly fine.

To start Python with IDLE, follow the given step


Start → All Programs → Python 3.7 → IDLE (Python 3.7 (32-bit)).
Python 3.7.3 Shell window will appear.
In that window, >>> sign will appear, here you can write your code and press Enter.

If you want to exit from the IDLE window, there are various options
Press Ctrl+D from keyboard.

or Click on cross ⊗ button on title bar.


or Click File → Exit.

(iii) Python Script Mode

Python gives the output immediately as you entered code and press Enter button. But if you
want to see all output after completion of code, then you can use Python script mode. To
work with Python script mode, you will have to follow given steps:
Step 1 Create Script/Program File
To create script/program file, follow the given instructions:
Start button → All Programs → Python 3.7 → IDLE (Python 3.7 (32-bit)).
Python 3.7 .3 shell window will appear on your screen. From here select File → New File
window.
Named untitled window will appear where you can write your code.

After finish your code, select File → Save As.


Save As dialog box will appear. Enter program name in File name text field with .py extension
and click on Save button.

Step 2 Run Script/ Program File


To run script/program file after creation of script, follow the given instructions:

Structure of Python Program Class 9 Notes


Code Explanation

Line 1 in the above code starting with # is a comment line, which means the line is non-
executable and it is only for the programmer’s reference.
Line 2 will simply display
Hello
Line 3 will assign a string value “Sam” to a variable Name Line 4 will disple:” Learner and will
allow the next output to get displayed in the same line
Line 5 will display Sam in the same line as Learner
Line 6 will assign an integer 50 to a variable A
Line 7 will assign an integer 300 to a variable $B$
Line 8 will display 50 Times 300 is 15000
So, the complete output of the Python Code will be
Hello
Learner Sam
50 times 300 is 15000

The term IPO stands for Input, Process, and Output. This cycle is a fundamental concept in
computer science and system analysis. It describes the flow of information, where data is
entered (input), manipulated (process), and presented as a result (output).Sometimes, we
need to transfer some input to useful output. For this, program is used to process this input
and produce an appropriate output.

Python Character Set

Character set is a set of valid characters that a language can recognise. A character
represents any digit, alphabet and special symbol. The character used in a Python source
program belongs to unicode standard.
Python supports the following character set.

 Alphabets A to Z (uppercase), a to Z (lowercase)

 Digits 0 to 9

 Special Characters Space ()+-*/\^& % # $ {}[]! _(underscore) >< ? @.; : ” etc.

 White Space Blank space, Horizontal tab (‘), Carriage return, Newline, formfeed

 Other Characters Python can process any of the ASCII and unicode characters as data
or as literals

Python Tokens Class 9 Notes


A progarm consists of various statements and statement comprises a sequence of atomic
units called tokens.
Python tokens are:

 Identifiers

 Keywords

 Constants

 Operators

 Puntuators

In this chapter, we will discuss about -identifiers,keywords and operators.

Identifiers

Identifiers are the fundamental building blocks program which are used to give the name to
data items included by the programmer. It is required in all programming languages, where
the programmer has to include items like variables, objects, classes, functions, arrays, etc.,
to specify their names. The identifier is a sequence of characters taken from Python
character set.
The rules in Python for identifiers are

 Only alphabets, digits and underscores are permitted.

 Identifier name cannot start with a digit.

 Keywords cannot be used as identifier.

 Uppercase and lowercase letters are distinct because Python is case sensitive
language.

 Special characters are not allowed.

For example, Some valid identifiers : Name, name, name_1, _sum, FirstName etc.
Some invalid identifiers: global, name 1, 2num etc.

Keywords

Keywords are predefined reserved words by the programming language that have some
special or predefined meanings. These are reserved for special purpose and must not be
used as identifier names. Some commonly used keywords in Python, which are listed below
Operators

Operators are those tokens that perform a specific task/computation when applied on
variable or some other objects in an expression (known as operands). Operators are used in
programs to operate on data and variables. Python carries a wide range of operators.
Operators in Python are mostly made of signs or little bit letters. Since, it mainly relies on
symbols and less on English words so it makes Python code shorter. There are two types of
operators as follows:
(i) Unary Operators Those operators that work on single operand to form an expression are
known as unary operators. Following are some unary operators:

 + : unary plus

 – : unary minus

 ∼ : Bitwise complement
 not : logical negation

(ii) Binary Operators The operators that work upon two operands are known as binary
operators. There are various types of binary operators in Python as follows.
(a) Arithmetic operator These operators are used to do arithmetic operations. These
operators are

 + Addition

 – Subtraction

 * Multiplication

 / Division

 % Remainder / Modulus

 * * Exponent (raise to power)

 // Floor division

(b) Logical operators These operators are used to make a decision on two conditions. Logical
operators are typically used with boolean values and what they return is also a boolean
value. These operators are
and : Logical AND
or : Logical OR

(c) Relational operators Relational operators compare two operands to one another. These
operators are

 < less than

 > greater than

 <= less than or equal to

 >= greater than or equal to

 == equal to

 != Not equal to

(d) Assignment operators Assignments operators are used to assign the value of an
expression to a variable. These operators are

 = assignment

 /= assign quotient

 += assign sum

 *= assign product

 %= assign remainder

 -= assign difference

 * *= assign exponent

 //= assign floor division

(e) Bitwise operators Bitwise operators work on bits and perform bit by bit operation. These
operators are

 & Bitwise AND

 ∧ Bitwise XOR
 | Bitwise OR

(f) Shift operators These operators are used to shift value left or right. These operators are

 << shift left

 >> shift right

(g) Identity operators These operators are


 is , – is the identity same?

 is not – is the identity not same?

(h) Membership operators These operators are

 in – whether variable in sequence

 not in – whether variable not in sequence

Expressions Class 9 Notes

An expression is a combination of operators, constants and variables as per rule of the


language. Any part in a program which can have a value, is an expression. It will have
operands and operators together to produce a value.
e.g. 4* i, x+y / 10, (a<b) etc.
From the above program, we have 5 expressions
50, 35, x-y+10, (z-5), z<30

Variable

Variable is a container object that stores a meaningful value that can be used throughout the
program.
In a Python program, to store different types of values such as, name of a shop and
quantities of items (goods) available in the shop during the run time. We require some sort
of storage area called variables. Each variable has a specific type, which determines the size
and layout of the variable’s memory, the range of values that can be stored within that
memory and the set of operations that can be applied to the variable. A variable is an
identifier that is used to represent specific data item. The data item may be a whole number,
a fractional number, a sequence of characters, a single character, etc.

Creating a Variable

Creating of variables meạns providing an initial value when it is declared. A variable can be
created anywhere in Python program.

e.g. Name = ‘Neha’


Subject = ‘Computer’
Marks = 80

Above is an assignment statements which used to assign values to a variables. The equal (=)
sign causes the value on the right hand side of the variables to be assigned to the variable on
the left.

Rules for Variables

 A variable name must start with a letter or the underscore character

 A variable name cannot start with a number


 A variable name can only contain alphanumeric characters and underscores ( Az, 09,
and _)

 Variable names are casesensitive (age, Age and AGE are three different variables)

 A variable name cannot be any of the Python keywords.

Data Types Class 9 Notes

The data that needs to be processed by a computer can be in various form. It can be
numbers with or without decimal places or it can be just a single character or a sequence of
characters. The data to be handled by the computer can also be in group. All computer
programming languages support wide variety of data that can be stored, processed and
manipulated in a computer system. ‘Data type is a term that is used to show the kind of data
values or the type of data that is expected to be handled.’ Data types are used to identify the
type of data and associated operations to handle it. Python has five standard data types
which shown in figure below

Numbers

Numbers data type contains only numeric value in Python. The types of numbers data type
are as follows:

(i) Integers
Integers are the whole numbers having different storage range supported by particular
machine. Integers have no fractional parts. They can be positive or negative.
There are two types of integers in Python as follows:
(I) Integers (signed) It is a simple whole numbers integers. In Python 3.X, integers are
represented by of any length and its length is limited that depends on memory availability. It
is signed representation.
(II) Booleans These represent the values either True or False. True value is represent as 1 and
False value is represent as 0.
e.g. 8, 17, -195 etc.
(ii) Floating Point Numbers
The float type in Python designates a floating point number. Float values are specified with a
decimal point. The decimal point signals that it is a floating point number not an integer. e.g.
159.12, 734.30 etc. Integer and floating points are separated by decimal points. 1 is integer
and 1.0 is floating point number. Floating point numbers can also be written in exponent
notation.
e.g. 786.456 would be written as 7.86456 E 02.

Floating point numbers are used for measurable quantities like distance, area, temperature
etc, and typically have fractional parts. Floating point identifier represents real numbers.

Discover more

coding

Programming language

Python programming

programming languages

Science

computer&#8217;s

python

Python

Computer programming

py

(iii) Complex Numbers


A complex number is a number expressed in the form a+b i, where, a (real part) and b
(imaginary part) are real numbers and i is the imaginary part. So, we can say that complex
number is made up of both real numbers and imaginary numbers. e.g. 2+3 i, 1+4 i, 2-5 i etc.
Here, you will learn about how to declare complex numbers in Python and extract their real
and imaginary parts.
where, [Link] will give the real part of complex number and [Link] will give the imaginary
part of complex number.

Boolean

Data type with one of the two builtin values, True or False. Boolean objects that are equal to
True are truthy (true), and those equal to False are falsy (false). However non-Boolean
objects can be evaluated in a Boolean context as well and determined to be true or false. It
is denoted by the class bool.

Output.
<class ‘bool’>
<class ‘bool’>
NameError : name ‘false’ is not defined
Note True and False with capital ‘T’ and ‘F’ are valid Booleans otherwise python will throw
an error.

Sequence

The sequence Data Type in Python is the ordered collection of similar or different Python
data types. Sequences allow storing of multiple values in an organized and efficient fashion.
There are several sequence data types of Python:
(i) Strings

Strings are sequence of character data. The string type in Python is called str. String literals
may be delimited using either single quotes or double quotes.

A string in Python can contain as many characters as you want. The string limit is depend on
your machine’s memory resources. A string can also be empty.
(ii) Lists

Lists are a very useful variable type in Python. A list can contain a series of values. List
variables are declared by using brackets [ ] following the variable name and separated by
comma(,). Lists are mutable that means they can be change after creation. e.g.
x = []
y = [1,2,3, ‘Neha’]
z = [23,34,56,67]

All lists in Python are zero based indexed. When referencing a member or the length of a list
the number of list elements is always the number shown plus one. In IDLE Python,

Output
[34, 45, ‘Neha’, 56, ‘Kabir’]
34
[45, ‘Neha’]
23

[34, 45, ‘Neha’, 56, ‘Kabir’, 34, 45, ‘Neha’, 56, ‘Kabir’]
[34, 45, ‘Neha’, 56, ‘Kabir’, ‘Riya’, 23, 43.3]
If you want to change any element in list then follow this,

The process of converting the value of one data type (integer, string, float, etc.) to another
data type is called type conversion.

The type() function is used to get the type of an object. It returns the type of the given
object, which could be a builtin data type or a userdefined class. Python has two types of
type conversion.

Implicit Type Conversion

For implicit type conversion, the python interpreter automatically assigns a data type to a
variable once it is declared. For instance, if we have a variable x and we assign the value 10
to it, the variable x automatically becomes an integer datatype.
Example

In Implicit type conversion, Python automatically converts one data type to another data
type. This process doesn’t need any user involvement.

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the predefined functions like int(), float(), str(), etc to perform explicit type
conversion.
This type of conversion is also called typecasting because the user casts (changes) the data
type of the objects.
Syntax:
(required_datatype) (expression)
Typecasting can be done by assigning the required data type function to the expression.

Input and Output in Python Class 9 Notes

In computing, input/output or I/O is the communication between an information processing


system (such as a computer) and the outside world, possibly a human or another
information processing system.
Inputs are the data received by the system, and outputs are the data sent from it. In almost
every computer program, the user has to input some data that will be stored in computer’s
memory and then subsequently processed.

The devices such as keyboard, mouse are input devices and are used to input data. The input
data may be taken from a disk file or from another computer via a communication channel.
The intermediate and final results of the computations are also stored in computer’s
memory. And finally, there is need to output the results of the computations. The output can
be displayed on the computer screen, stored on a disk or transmitted via a communication
channel to other computer. A program needs to interact with the user to accomplish the
desired task, this is done using Input-Output facility

Input from User

A function is defined as a block of organised, reusable code used to perform a single, related
action. Python has many built-in functions, you can also create your own. Python has an
input function which lets you ask a user for some text input. You call this function to tell the
program to stop and wait for the user to key in the data.
Python provides two built-in functions to read a line of text from standard input, which by
default comes from the keyboard. These functions are as follows

(i) input()

This function first takes the input from the user and then evaluates the expression, which
means Python automatically identifies whether user entered a string or number or list. If the
input provided is not correct, then either syntax error or exception is raised by Python.
Before input() method was not capable of handling anything other than numbers.
But in Python 3, input( ) is capable of handing anything other than numbers like string.

Syntax:

(ii) print()

To output your data to the screen, use the print () function. Print evaluates the expression
before printing it on the monitor. Print statement gives output an entire (complete) line and
then goes to next line for subsequent output. To print more than one item on a single line,
comma (.) may be used.

Syntax

Comments

Comments are the entries in a computer program for the purpose of documentation or
explanation. Comments are non-executable statements that are ignored by the interpreter
or compiler and are not executed by the computer.
Types of Comments

There are two types of comments used in programs as follows.


(a) Single line comment A single line comment starts with # symbol.
e.g. # Here is define the function of addition # It helps to know the process of function
(b) Multiline comment A multiline comment starts with a “‘symbol and ends with”‘.
e.g. a=20 “‘Here we initialise the value of variable a as 20″‘

1. Program to obtain length, breadth and height of a cuboid and calculate its volume.

Output
Enter the length of the cuboid : 5
Enter the breadth of the cuboid: 4
Enter the height of the cuboid : 7
Length =5
Breadth =4
Height =7
The volume of cuboid =140

2. Program to convert kilometers to miles.

Output
Enter value in kilometers : 5.5
5.500 kilometers is equal to 3.418 miles

3. Program to find simple interest for entered principal amount, time and rate of interest.
Output
Enter principal amount : 5000
Enter time : 2
Enter rate of interest : 10
Simple interest is 1000.0

4. Program to convert Celsius to Fahrenheit using formula. F = C × 1.8 + 32

Output
Enter temp in Celsius : 25.4
Temperature in Celsius is : 2 5 . 4
Temperature in Fahrenheit is : 77.72

Glossary:

 Program A computer program is a set of instructions written in a programming


language that a computer can understand and execute.

 Python It is a general purpose interpreted, interactive, object oriented and high-level


programming language.

 IDLE Integrated Development Environment.

 Character Set It is a set of valid characters that a language can recognise.

 Tokens A progarm consists of various statements and statement comprises a


sequence of atomic units called tokens.
 Identifiers They are the fundamental building blocks program which are used to give
the name to data items included by the programmer.

 Keywords They are predefined reserved words by the programming language that
have some special or predefined meanings.

 Operators They are those tokens that perform a specific task/computation when
applied on variable or some other objects in an expression (known as operands).

 Variable It is a container object that stores a meaningful value that can be used
throughout the program.

 Strings The sequence of character data.

 List it is a sequence data type which is used to store the collection of data.

 Tuple It is an ordered sequence of items same as list.

 Set It is an unordered collection of unique elements.

 Dictionaries lists of key: value pairs.

 Type Coversion The process of converting the value of one data type (irteger, string,
float, etc.) to another data type is called type conversion.

Common questions

Powered by AI

Python's extensive standard library plays a crucial role in software development by providing modules and functions for a wide range of tasks, including string manipulation, networking, file I/O operations, and more. This comprehensive set of built-in tools reduces the need for external libraries and custom code, speeding up development times and improving code reliability. The library's extensive documentation and wide community support also make it easier for developers to find solutions and implement features without starting from scratch .

Operators in Python are diverse and include unary, binary, logical, relational, assignment, and bitwise operators, among others. Compared to some other languages, Python primarily uses symbols rather than words for operators, making code shorter and often more readable. This symbolic approach reduces verbosity and can make complex expressions easier to understand at a glance. Additionally, Python supports unique operators like identity and membership operators, which add expressive power for common programming tasks, such as checking object identity and membership in collections .

Python is considered suitable for both beginners and experts due to its simple syntax resembling natural language, which makes it easy to read and understand. It also supports both procedural and object-oriented programming, which caters to different styles of programming. Additionally, it is dynamically typed and garbage collected, reducing the complexity involved in variable declaration and memory management. This simplicity allows beginners to learn quickly while providing powerful features that experts can leverage .

Python handles data types dynamically, meaning the type of a variable is determined at runtime and can change as needed. This allows for increased flexibility and faster coding, as programmers do not need to explicitly declare data types when defining new variables. However, the trade-off is that errors related to type mismatches can only be detected at runtime, which may complicate debugging. Despite this, the benefits of reduced verbosity and improved code readability often outweigh these disadvantages .

Python supports cross-platform development by being a portable language whose code can run on various operating systems such as Windows, MacOS, and Linux. This is largely facilitated by the use of a bytecode interpreter, which allows Python programs to be interpreted and executed across these systems without significant modification. The Python interpreter must be installed on the system, enabling the execution of Python code by reading and running Python scripts, regardless of the underlying platform .

Python's prevalence in artificial intelligence applications is due to its readability, extensive libraries, and support for object-oriented and procedural programming. Its syntax is clear and concise, resembling natural language, which eases learning and maintenance. Python is portable across different operating systems, further contributing to its popularity. Moreover, Python is free and open-source, and it comes with a rich standard library that reduces the need to write code from scratch, facilitating rapid prototyping of AI systems .

Identifiers in Python are names used to identify a variable, function, class, module, or other object, and are fundamental for programming. The rules governing their creation include: an identifier can only contain alphabets, digits, and underscores; it must not start with a digit; keywords cannot be used as identifiers; it is case-sensitive; and special characters are not allowed. These rules ensure that identifiers are clear, meaningful, and do not conflict with Python's reserved keywords .

Python's sequence data types, such as lists, contribute to its versatility by allowing flexible and efficient storage, access, and manipulation of collections of items. Lists, in particular, are mutable and can hold a variety of data types, enabling complex data structures and dynamic data changes without needing rigid data type definitions. This ability to easily handle different types of data aligns with Python's overall design philosophy of simplicity and versatility, making it suitable for tasks ranging from simple scripts to complex data analysis .

Python's handling of complex numbers is built-in and allows for straightforward creation and manipulation of complex numbers using native syntax. This differs from many other programming languages where handling complex numbers may require additional libraries or tools. In Python, complex numbers are created using the format `a + bj`, where `a` is the real part and `b` is the imaginary part. This native support facilitates mathematical computations involving complex numbers, making Python particularly suitable for scientific and engineering applications that frequently use complex arithmetic .

In Python, whitespace is significant and is used to delimit code blocks instead of using braces, as is common in many other programming languages. This design choice enforces consistent indentation and readability of code, reducing confusion over where blocks of code start and end. It also aligns with Python's philosophy of simplicity and clarity. However, it requires programmers to be mindful of their indentation style, as incorrect indentation can lead to syntax errors .

You might also like