Quantcast
Channel: Learn CBSE
Viewing all articles
Browse latest Browse all 10029

Introduction to Python Class 9 AI Notes

$
0
0

These AI Class 9 Notes Chapter 7 Introduction to Python Class 9 AI Notes simplify complex AI concepts for easy understanding.

Class 9 AI Introduction to Python Notes

Program Class 9 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.

Introduction to Python Class 9 AI Notes

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.

Introduction to Python Class 9 AI Notes

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 Python.org and running it on your server.

Introduction to Python Class 9 AI Notes

Downloading Python

To download a Python setup, follow the steps given below

  1. Enter Python.org in URL. A window will be appear. Select Downloads tab, after this a pop-up will appear.
  2. Click on Python 3.7 .3 button to download. The file named 3.7.3.exe should start downloading into your standard download folder.
  3. Move this file to more permanent location, so that you can install Python.

Installing Python

To install Python, follow the steps given below
(i) Open Downloads folder where Python setup was saved. Double click on the file python-3.7.3.exe.
(ii) An Open File-Security Warning dialog box will appear as shown below.

Introduction to Python Class 9 AI Notes 1

(iii) Click on Run button.

A Python 3.7 .3 (32-bit) Setup pop-up window will appear.
(iv) Highlight the install now (or upgrade now) message and then click it. A user account control pop-up window will appear, that asked the question. Do you want to allow the following program to make changes to this computer?
(v) Click on Yes button. A new Python 3.7 .3 (32-bit) Setup pop-up window will appear, with a Setup Progress message and a progress bar.

Introduction to Python Class 9 AI Notes 2

During installation, it will show the various components that are installing and move the progress bar towards completion. Soon, a new Python 3.7.3 ( 32 bit) Setup pop-up window will appear, with a “Setup, was successful” message.
(vi) Click the Close button.

Introduction to Python Class 9 AI Notes

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.

Introduction to Python Class 9 AI Notes 3

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

Introduction to Python Class 9 AI Notes 10

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.

Introduction to Python Class 9 AI Notes 4

If you want to exit from the IDLE window, there are various options
Press Ctrl+D from keyboard.
or Click File → Exit.
or Click on cross ⊗ button on title bar.

(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.

Introduction to Python Class 9 AI Notes

Introduction to Python Class 9 AI Notes 5

Named untitled window will appear where you can write your code.

Introduction to Python Class 9 AI Notes 6

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:

Now, open the IDLE file, which was opened in Step1.
Select File → Opentand type file name in File name: box which file you want to open for executing.
Click on Open button. Filename.py file will appear on your screen.
Select Run → Run Module or press F5 key from keyboard.

Introduction to Python Class 9 AI Notes 7

It will execute and output will print in your IDLE window.

Introduction to Python Class 9 AI Notes 8

Structure of Python Program Class 9 Notes

Introduction to Python Class 9 AI Notes 9

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

Introduction to Python Class 9 AI Notes

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.

In many languages, some elements are used to write programs. So, for working in any language you must to know all elements, which are used to write code. In Python, various elements are used as character set, token, expressions, statements, input, output etc.

Python Character Set Class 9 Notes

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.

Introduction to Python Class 9 AI Notes

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

Introduction to Python Class 9 AI Notes 11

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

Introduction to Python Class 9 AI Notes

(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 Class 9 Notes

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.

Introduction to Python Class 9 AI Notes

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

Introduction to Python Class 9 AI Notes 12

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.

Introduction to Python Class 9 AI Notes

(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.

(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.

Introduction to Python Class 9 AI Notes 13

where, a.real will give the real part of complex number and a.imag 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.

Introduction to Python Class 9 AI Notes 14

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.

Introduction to Python Class 9 AI Notes 15

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,

Introduction to Python Class 9 AI Notes 16

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,

Introduction to Python Class 9 AI Notes 17

(iii) Tuples

Tuple is an ordered sequence of items same as list. The only difference is that tuples are immutable and lists are mutable. Tuples once created cannot be modified. Tuples are used to writeprotect data and are usually faster than list as it cannot change dynamically. Tuples are defined by parentheses ( ).

Introduction to Python Class 9 AI Notes 18

Output
(‘Maths’, ‘English’, ‘Hindi’, ‘Computer’)
English
(‘Hindi’, ‘Computer’)
(‘Games’, ‘Dancing’)
(‘Maths’, ‘English’, ‘Hindi’, ‘Computer’, ‘Games’, ‘Dancing’)

Set

In Python, a set is an unordered collection of unique elements: Sets are defined using curly braces \{\ or the set() function and are commonly used to eliminate duplicate items from a list or to perform mathematical set operations like union, intersection, and difference. Elements in a set must be immutable, which means you can include strings, numbers, and tuples, but not lists or other sets. Sets are highly efficient for membership tests and support various methods to manage the collection of elements.
Example of creating and using a set:

Introduction to Python Class 9 AI Notes 19

Dictionary

Dictionaries in Python are lists of key: value pairs. This is a very powerful data type to hold a lot of related information that can be associated through keys. The main operation of a dictionary is to extract a value based on the key name. Dictionaries can also be used to sort, iterate and compare data. Dictionaries are created by using braces with pairs separated by a comma ( ) ) and the key values associated with a colon (:). In dictionaries, the key must be unique.

Introduction to Python Class 9 AI Notes 20

Output
dict_keys([‘Name’, ‘Salary’, ‘Post’])
dict_values([‘Neha’, 25000, ‘Coordinator’])
2 5 0 0 0
Coordinator

Data Type Conversion Class 9 Notes

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

Introduction to Python Class 9 AI Notes 21

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.

Introduction to Python Class 9 AI Notes

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:

Introduction to Python Class 9 AI Notes 22

(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

Introduction to Python Class 9 AI Notes 23

Comments Class 9 Notes

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″‘

Introduction to Python Class 9 AI Notes

Programs Class 9 Notes

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

Introduction to Python Class 9 AI Notes 24

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.

Introduction to Python Class 9 AI Notes 25

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.

Introduction to Python Class 9 AI Notes 26

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
Introduction to Python Class 9 AI Notes 27

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

Introduction to Python Class 9 AI Notes

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.

The post Introduction to Python Class 9 AI Notes appeared first on Learn CBSE.


Viewing all articles
Browse latest Browse all 10029

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>