0% found this document useful (0 votes)
43 views50 pages

AI CHAPTER 5 PYTHON NOTES - Class IX

This document provides an introduction to Python programming, covering fundamental concepts such as data types, variables, operators, and control flow structures. It emphasizes Python's popularity for artificial intelligence applications due to its versatility and ease of use. The document also includes practical examples and exercises to illustrate the concepts discussed.

Uploaded by

tonig58650
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views50 pages

AI CHAPTER 5 PYTHON NOTES - Class IX

This document provides an introduction to Python programming, covering fundamental concepts such as data types, variables, operators, and control flow structures. It emphasizes Python's popularity for artificial intelligence applications due to its versatility and ease of use. The document also includes practical examples and exercises to illustrate the concepts discussed.

Uploaded by

tonig58650
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Artificial Intelligence

Chapter IV – Introduction to Python

I. Introduction to Python Language


II. Operators
III. Conditional Statements and Loops
IV. Strings in Python
V. Lists in Python
What is a program?

A computer program is a collection of instructions that perform


a specific task when executed by a computer. It is usually written by
a computer program in a programming language.

What is Python?

Why Python for AI?

Artificial intelligence is the trending technology of the future.


You can see so many applications around you. If you as an individual
can also develop an AI application, you will require to know a
programming language. There are various programming languages
like Lisp, Prolog, C++, Java and Python, which can be used for
developing applications of AI. Out of these, Python gains a maximum
popularity because of the following reasons:
Applications of Python:

Python is used for a large number of applications. Some of


them are mentioned below:
Python Statement and Comments

Python Statement

Instructions written in the source code for execution are called


statements. There are different types of statements in the Python
programming language like Assignment statement, Conditional
statement, Looping statements etc. These help the user to get the
required output. For example, n = 50 is an assignment statement.

Multi-line statement

In Python, end of a statement is marked by a newline


character.

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.
Python Comments

A comment is text that doesn't affect the outcome of a code, it


is just a piece of text to let someone know what you have done in a
program or what is being done in a block of code.

In Python, we use the hash (#) symbol to start writing a comment.

Python Keywords and Identifiers:

Keywords are the reserved words in Python used by Python


interpreter to recognize the structure of the program.
Identifier:
Note:

Python is a case-sensitive language.


This means, Variable and variable are not the same.
Always name identifiers that make sense.

While, c = 10 is valid. Writing count = 10 would make more sense


and it would be easier to figure out what it does even when you look
at your code after a long gap.

Multiple words can be separated using an underscore, for example


this_is_a_long_variable.
Variables and Datatypes

Variables

A variable is a named location used to store data in the memory. It is


helpful to think of variables as a container that holds data which can
be changed later throughout programming. For example,
These declarations make sure that the program reserves memory
for two variables with the names x and y. The variable names stand
for the memory location. It's like the two shoeboxes, which you can
see in the picture. These shoeboxes are labelled with x and y and
the corresponding values are stored in the shoeboxes. Like the two
shoeboxes, the memory is empty as well at the beginning.

Note:

Assignment operator is used in Python to assign values to


variables. For example, a = 5 is a simple assignment operator that
assigns the value 5 on the right to the variable a on the left.
Datatypes:

Every value in Python has a datatype. Since everything is an object


in Python programming, data types are actually classes and
variables are instance (object) of these classes.
There are various data types in Python. Some of the important types
are mentioned below in the image:
1) Python Numbers

Number data type stores Numerical Values. These are of three


different types:

a) Integer & Long


b) Float / floating point

Integer & Long Integer:

Range of an integer in Python can be from -2147483648 to


2147483647, and long integer has unlimited range subject to
available memory.

Integers are the whole numbers consisting of + or – sign with


decimal digits like 100000, -99, 0, 17. While writing a large integer
value, don’t use commas to separate digits. Also, integers should
not have leading zeros.

Floating Point:

Numbers with fractions or decimal point are called floating point


numbers.
A floating-point number will consist of sign (+,-) sequence of
decimals digits and a dot such as 0.0, -21.9, 0.98333328, 15.2963.
These numbers can also be used to represent a number in
engineering/ scientific notation.
-2.0 x 105 will be represented as -2.0e5
2.0X10-5 will be 2.0E-5

2) None

This is special data type with single value. It is used to signify the
absence of value/false in a situation. It is represented by None.

3) Sequence:

A sequence is an ordered collection of items, indexed by positive


integers. It is a combination of mutable and non-mutable data
types. Three types of sequence data type available in Python are:

a) Strings
b) Lists
c) Tuples

String

String is an ordered sequence of letters/characters. They are


enclosed in single quotes (‘ ‘) or double (“ “). The quotes are not part
of string. They only tell the computer where the string constant
begins and ends. They can have any character or sign, including
space in them.

Lists

List is also a sequence of values of any type. Values in the list are
called elements / items. These are indexed/ordered. List is enclosed
in square brackets.
Tuples:

Tuples are a sequence of values of any type, and are indexed by


integers. They are immutable. Tuples are enclosed in ().

4) Sets

Set is an unordered collection of values, of any type, with no


duplicate entry.

Dictionaries

Dictionary is an unordered collection of key-value pairs. It is


generally used when we have a huge amount of data. Dictionaries
are optimized for retrieving data. We must know the key to retrieve
the value.

In Python, dictionaries are defined within braces {} with each item


being a pair in the form key: value. Key and value can be of any
type.
Example 1:

Example 2:

Boolean Data Type:

A Boolean or logical value can either be True or False.


Python Operators I:

Operators are special symbols which represent computation. They


are applied on operand(s), which can be values or variables. Same
operators can behave differently on different data types. Operators
when applied on operands form an expression. Operators are
categorized as Arithmetic, Relational, Logical and Assignment. Value
and variables when used with operator are known as operands.

Python Output Using print() function:

We use the print() function to output data to the standard output


device (screen).
We can also output data to a file. An example is given below.
User input

In all the examples till now, we have been using the calculations on
known values (constants). Now let us learn to take user’s input in
the program. In python, input () function is used for the same
purpose.
Type Conversion

The process of converting the value of one data type (integer, string,
float, etc.) to another data type is called type conversion. Python
has two types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion

Implicit Type Conversion:

In Implicit type conversion, Python automatically converts one data


type to another data type. This process doesn't need any user
involvement.

In the above program,

• We calculate the simple interest by using the variable


priniciple_amount and roi with time divide by 100
• We will look at the data type of all the objects respectively.
• In the output we can see the datatype of principle_amount is an
integer, datatype of roi is a float.
• Also, we can see the simple_interest has float data type because
Python always converts smaller data type to larger data type to
avoid the loss of data.

Example Programs for Implicit Conversion:

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.

Example: Adding of string and an integer using explicit conversion

In above program,

• We add Birth_day and Birth_month variable.


• We converted Birth_day from integer(lower) to string(higher) type
using str() function to perform the addition.
• We got the Birth_date value and data type to be string.
Example Programs for Explicit Conversion:
Python Operators II

Comparison operators
Introduction to Lists

List is one of the most frequently used and very versatile data type
used in Python. A number of operations can be performed on the
lists.

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.).
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:

1) List Index
2) 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. In order to access an
element in a list we need to use index operator [].

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.
Adding Element to a List

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

1) Using append() method


2) Using insert() method
3) Using extend() method

Using append() method


Using insert() method
Elements can be added to the List by using built-in append()
function. Only one element at a time can be added to the list by using
append() method, for addition of multiple elements with the append()
method, loops are used. Tuples can also be added to the List with the
use of append method because tuples are immutable. Unlike Sets,
Lists can also be added to the existing list with the use of append()
method.

Using insert() Method

append() method only works for addition of elements at the end of the
List, for addition of element at the desired position, insert() method
is used. Unlike append() which takes only one argument, insert()
method requires two arguments(position, value).

Using extend() method

Other than append() and insert() methods, there's one more method
for Addition of elements, extend(), this method is used to add multiple
elements at the same time at the end of the list.
Removing Elements from a List

Elements from a list can removed using two methods:


1) Using remove() method
2) Using pop() method
Elements can be removed from the List by using built-in remove()
function but an Error arises if element doesn't exist in the set.
Remove() method only removes one element at a time, to remove
range of elements, iterator is used. The remove() method removes the
specified item.

Note – Remove method in List will only remove the first occurrence
of the searched element.

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.

Slicing of a List

In Python List, 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] and to print whole List with the
use of slicing operation, use [:]. Further, to print whole List in reverse
order, use [::-1].
Slicing using negative index of list :
Introduction to Tuples

Tuple is a collection of Python objects which is ordered and


unchangeable. The sequence of values stored in a tuple can be of
any type, and they are indexed by integers. Values of a tuple are
syntactically separated by ‘commas’. Although it is not necessary, it
is more common to define a tuple by closing the sequence of values
in parentheses. This helps in understanding the Python tuples more
easily.

Example

fruits = ("apple", "banana", "cherry")


How to Create a tuple?

In Python, tuples are created by placing sequence of values separated


by ‘comma’ with or without the use of parentheses for grouping of
data sequence. It can contain any number of elements and of any
datatype (like strings, integers, list, etc.).

Accessing of Tuples

We can use the index operator [] to access an item in a tuple where


the index starts from 0. So, a tuple having 6 elements will have
indices from 0 to 5. Trying to access an element outside of tuple (for
example, 6, 7,...) will raise an IndexError. The index must be an
integer; so, we cannot use float or other types. This will result in
TypeError.

Example

fruits = ("apple", "banana", "cherry")


print(fruits[1])

The above code will give the output as "banana"

Deleting a Tuple

Tuples are immutable and hence they do not allow deletion of a part
of it. Entire tuple gets deleted by the use of del() method.
Example

num = (0, 1, 2, 3, 4)
del num

Flow of Control and Conditions

Decision making statements in programming languages decide the


direction of flow of program execution. Decision making statements
available in Python are:

● if statement
● if..else statements
● if-elif ladder

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

Here, the program evaluates the test expression and will execute
statement(s) only if the text expression is True.
If the text expression is False, the statement(s) is not executed.
Python if...else Statement
Python if...elif...else Statement
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. This can
get confusing, so must be avoided if it can be.
The For Loop

The for..in statement is another looping statement which iterates over


a sequence of objects i.e. go through each item in a sequence.
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.

In while loop, test expression is checked first. The body of the loop is
entered only if the test_expression evaluates to True. After one
iteration, the test expression is checked again. This process
continues until the test_expression evaluates to False. In Python, the
body of the while loop is determined through indentation. Body starts
with indentation and the first unindented line marks the end. Python
interprets any non-zero value as True. None and 0 are interpreted as
False.
Exercises:

Python program that ask for our name and age, and then displays
it on
the screen.

Program:

name = input("What is your name?...:")


age = input("How old are you?...:")
print("Welcome! Your Name is " + name)
print("You are " + age + " years old")
To input two numbers and find their sum, product, exponent.

Code to calculate simple interest by inputting the value of Principal


amount and rate from the user for a period of 1 year.
Python code to find whether the given number is positive or negative.

Python program that accepts a number and then prints a table for that number.

number = int (input ("Enter a number:") )


num = str(number) # convert int to string for printing in line 3
print("The Multiplication table for "+ num + " is:")
a = number*1
b = str(a)
print (num + " x 1 = " + b)
a = number*2
b = str(a)
print (num + " x 2 = " + b)
a = number*3
b = str(a)
print (num + " x 3 = " + b)
a = number*4
b = str(a)
print (num + " x 4 = " + b)
a = number*5
b = str(a)
print (num + " x 5 = " + b)
a = number*6
b = str(a)
print (num + " x 6 = " + b)
a = number*7
b = str(a)
print (num + " x 7 = " + b)
a = number*8
b = str(a)
print (num + " x 8 = " + b)
a = number*9
b = str(a)
print (num + " x 9 = " + b)
a = number*10
b = str(a)
print (num + " x 10 = " + b)

Python code to find out whether a person is eligible for vote or


not.

Python code to print all natural numbers from 1 to n using


while loop.
Python code to find the factorial of a number using while loop.

Python code to print the sum of first 10 integers using while


loop.

Python code to Print each fruit in a fruit list using for loop.
Python code to Print all numbers from 1 to 10 using for, and
print a message when the loop has ended.

To write python code to print the following pattern:


1
11
111
1111
11111
Python code to read an integer and reverse that number.

Create a list with the following numbers


List = [10,11,12,13,14,15,16,17,18,19,20]
And perform the following task on the list in sequence:
1. Add the second and third item on the list. Store the value as
the fourth item.
2. Delete the fourth item on the list.
3. Add 13 as the fourth item on the list.

Program:

list = [10,11,12,13,14,15,16,17,18,19,20]
print ("Elements of the List")
print (list)
list[3]=list[1]+list[2]
print("Added 2nd & 3rd items and store the added result as 4th
item")
print (list)
list.pop(3)
print("List after deleting 4th item")
print (list)
list.insert(3,13)
print ("List after adding 13 as the 4th item")
print (list)

Python program to enter three numbers into a list (user input)


and printing their sum and product.

Program:

print ("Enter three numbers which is to be created as list")


list = [int(input()),int(input()),int(input())]
print (list)
a = (int(list[0]) + int(list[1]) + int(list[2]))
print ("The sum of three numbers is:" +str(a))
b = (int(list[0]) * int(list[1]) * int(list[2]))
print ("The product of three numbers is:" +str(b))

Python program to check if a given number is an Armstrong


number.

A number is called Armstrong number if it is equal to the


sum of the cubes of its own digits. For example: 153 is an
Armstrong number since 153 = 1*1*1 + 5*5*5 + 3*3*3. The
Armstrong number is also known as narcissistic number.

You might also like