ARTIFICIAL INTELLIGENCE
Python
Introduction
Working with python
Python Fundamentals
Data Types
Control Statements
String
List
Tuple
Dictionary
Introduction
Python is a High level Programming language, developed by Guido Van Rossum in 1991.
It is free to use.
It is an Interpreted language.
It is portable language which means it can run on any platform.
Syntax are less in python compared to c, c++.
It has wide range of built in functions, modules & libraries.
Working with python
+ Installation of python is available on www.python.org, which carry the python installation
package.
15 | P a g e
ARTIFICIAL INTELLIGENCE
Working Modes in Python Programming
Python works in two modes:
(i) Interactive Mode
(ii) Script Mode
Interactive Mode: User gives one command at a time and python executes the command and
produces the output.
To work with Interactive mode, click on StartAll programspython3.7.xIDLE
A screen will appear shown as below:
Interactive mode : In Interactive mode, user gives commands to python command prompt(>>>>)
which indicates that python is waiting for user response.
Script Mode: In this mode, multiple statements are written and saved as a file in .py extension and
execute it.
• To work with script mode, open IDLE. In IDLE click FileNew File
A screen will appear shown as below:
• To save the file in script mode, click FileSave & save the file.
• To execute the file click RunRun Module and get the output if there is no error.
16 | P a g e
ARTIFICIAL INTELLIGENCE
Python fundamentals
• The fundamental and smallest unit of a program is token.
• There are five categories in token:
Keywords
Identifiers
Literals
Operators
Punctuators
Keywords-: Keywords are the reserved words and have special meaning for python interpreter. Every
keyword is assigned specific work and it can be used only for that purpose. Keywords can not be any
identifiers.
Some of the keywords in python is-:
Identifiers-: These are the names given to different parts of program like variables, objects,
classes, functions etc.
Identifier forming rules of Python are :
Is an arbitrarily long sequence of letters and digits
The first character must be letter or underscore
Upper and lower case are different
The digits 0-9 are allowed except for first character
It must not be a keyword
No special characters are allowed other than underscore is allowed.
Space not allowed
• Valid identifiers: myfile, _file, no2ab
• Invalid identifiers: 2no, na me,cs-12
•
17 | P a g e
ARTIFICIAL INTELLIGENCE
Literals/Values:
Literals are data items that have a fixed value. Python supports several kinds of literals:
String Literal
Numeric Literals
Boolean Literals
Special Literals – None
Literal Collections
String Literals
It is a collection of character(s) enclosed in a double or single quotes
Examples of String literals
“Python”
‘123456’
‘Hello Everyone’
Size of the string is determined by len() function.
Example: name=‘rajesh’
len(name)=6
Numeric Literals
The numeric literals in Python can belong to any of the following numerical types:
1) Integer Literals: it contain at least one digit and must not contain decimal point. It may
contain (+) or (-) sign.
2) Floating point Literals: also known as real literals. Real literals are numbers having
fractional parts. It is represented in two forms Fractional Form or Exponent Form
Numeric values with commas are not considered for int or float value, rather Python treats
them as tuple.
User can check the type of literal using type() function.
18 | P a g e
ARTIFICIAL INTELLIGENCE
Boolean Literals
A Boolean literals in Python is used to represent one of the two Boolean values i.e. True or
False
These are the only two values supported for Boolean Literals
Special Literals None
Python has one special literal, which is None. It indicate absence of value. In other languages it is
knows as NULL. It is also used to indicate the end of lists in Python.
Operators
Operators are symbol that perform specific operation when applied on variables i.e. operator operates
on operand.
Some operator requires two operand and some requires only one operand to operate.
Example: a + b is an expression, a & b are operands and + is an operator.
Types of Operators
Unary operators: are those operators that require one operand to operate upon.
Binary Operators: These are those operators that require two operand to operate upon. Following
are some Binary operators
19 | P a g e
ARTIFICIAL INTELLIGENCE
Arithmetic Operators
Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
** Exponent
// Floor division
Conditional Operators / Relation Operators
• It compares the values
Logical Operators
Operator Description Example
and Retrun true if both conditions are true (4<5 and 5!=7), return true because both
conditions are true
or Retrun true if at least one condition is (5==9 or ‘ram’>’rajesh’), return true
true because one condition is true.
not reverse the condition not(5==5), return false because it
reverse true.
20 | P a g e
ARTIFICIAL INTELLIGENCE
Assignment Operators
Operator Description Example Example
= Assigns values from right side operands to left side operand a=b a=5
a+=6
+= Add 2 numbers and assigns the result to left operand. a+=b
a=a+6
/= Divides 2 numbers and assigns the result to left operand. a/=b a=a/b
*= Multiply 2 numbers and assigns the result to left operand. a*=b a=a*b
-= Subtracts 2 numbers and assigns the result to left operand. a-=b a=a-b
%= modulus 2 numbers and assigns the result to left operand. a%=b a=a%b
Perform floor division on 2 numbers and assigns the result to a//=b a=a//b
//=
left operand. b//=a b=b//a
Punctuators / Delimiters
• Used to implement the grammatical and structure of a Syntax.
Following are the python punctuators.
21 | P a g e
ARTIFICIAL INTELLIGENCE
Input & Output in python:
input() function in python is used to allow user to give input values via keyboard in form of string.
Syntax is-: variable = input(<message to display>)
• In python, we use int() and float() functions to convert the string values in integer and float
respectively.
• Example:
a=input(“enter name”)
b=int(input(“enter your age”))
c=float(input(“enter your percentage”))
so a will take string values, b will take integer values & c will take float values from user.
• Note: float values are fractional values like 7.5, 89.5, while string values are set of characters
like ‘ram’, ‘rakesh’. String values should always enclosed in ‘ ‘ or ‘’ ‘’, otherwise it will give an
error.
Conversion from one type to another
Python allows converting value of one data type to another data type.
If it is done by the programmer then it will be known as type conversion or type casting
If it is done by compiler automatically then it will be known as implicit type conversion.
Explicit type conversion To perform explicit type conversion, Python provide functions like int(), float(),
str(), bool().
22 | P a g e
ARTIFICIAL INTELLIGENCE
print() function in python is used to give output to user.
Syntax of print function: print(expression/value, sep, end)
• If sep(seperator) is not defined in print then by default it will take whitespace.
• If end keyword is not defined then it will take new line character by default.
Open a new script file and type the following code & Execute the code:
num1=int(input("Enter Number 1 "))
num2=int(input("Enter Number 2 "))
a = num1 + num2
b= num1 - num2
c= num1 * num2
d= num1/num2
print(“Add =",a)
print(“Subtraction =",b)
print(“Multiplication =",c)
print(“Division =",d)
23 | P a g e
ARTIFICIAL INTELLIGENCE
Variable: variable is a location or container that holds some value. Python is dynamic typed programming
language which means user don’t have to declare the type of variable. When a value is assigned to a
variable, the type is automatically assigned and data type of variable can be changed.
Lets see through example in which a is variable and value of a and type is changing:
In above example, we can see that we can assign multiple values to multiple variable, same value to
multiple variables, so multiple assignment is possible in python.
24 | P a g e
ARTIFICIAL INTELLIGENCE
DATA TYPES
Data type in Python specifies the type of data we are going to store in any variable, the amount of
memory it will take and type of operation we can perform on a variable. Data can be of many types e.g.
character, integer, real, string etc.
Python supports following data types:
Numbers ( int, float, complex)
String
List
Tuple
Dictionary
NUMBERS
Number data types are used to store numeric values. Numbers in Python can be of following types:
(i) Integers
a) Integers(signed)
b) Booleans
(ii) Floating point numbers
(iii) Complex Numbers
Integers
Integers allows to store whole numbers only and there is no fraction parts.
Integers can be positive and negative e.g. 100, 250, -12, +50
There are two integers in Python:
1) Integers(signed) : it is normal integer representation of whole
numbers. Integers in python can be on any length, it is only limited
by memory available. In Python 3.x int data type can be used to
store big or small integer value whether it is +ve or –ve.
2) Booleans: it allows to store only two values True and False. The
internal value of boolean value True and False is 1 and 0 resp. We
can get boolean value from 0 and 1 using bool() function.
25 | P a g e
ARTIFICIAL INTELLIGENCE
FLOATING POINT NUMBERS
It allows to store numbers with decimal points. For e.g. 2.14. The decimal point indicate that it is not
an integer but a float value. 100 is an integer but 100.5 is a float value.
COMPLEX NUMBERS
Python represent complex numbers in the form A+Bj. To represent imaginary numbers, Python uses j
or J in place of i. Both real and imaginary parts are of type float
Python allows to retrieve real and imaginary part of complex number using attributes: real and imag.
If the complex number is a then we can write a.real or a.imag
STRING
• String is a collection of any valid characters in a quotation marks (single quotation or double
quotation )
• Each character of String in Python is a Unicode character.
• Strings are used to store information like name, address, descriptions. For example:
“hello”, “welcome‟, “computer science”.
• In Python, string is a sequence of characters and each character can be individually access
using index.
• From beginning, the first character in String is at index 0 and last will be at len-1.
• From backward direction, last character will be at index -1 and first character will be at –len.
26 | P a g e
ARTIFICIAL INTELLIGENCE
Forward indexing
Backward Indexing
Forward indexing
Backward Indexing
To access individual character of String, we can use the syntax:
StringName[index position]
27 | P a g e
ARTIFICIAL INTELLIGENCE
User cannot change the individual letters of string by assignment because string in python is immutable
and Python will raise an error “object does not support Item assignment”
>>>name=“Hello”
>>>name[1]=‘t’ # error
However user can assign string to another string. Like
>>>name=“Computer Science”
>>>name=“Information technology”
>>>> print(name)
Information technology
LIST & TUPLES
• List and Tuple are compound data types i.e. they allows to store multiple values under one
name of different data types.
• The main difference between List and Tuple is List can be changed/modified i.e. mutable type
whereas Tuple cannot be changes or modified i.e. immutable type.
List: A list in python represents a list of comma-separated values of any data type between square
brackets.
Example: [1,2,4,8,9], [‘hello’, ‘everyone’], [1,’h’,’y’,4.5]
• The values stored in List are internally indexed numbering from 0 onwards. i.e. first element will
be at position 0 and second will be at 1 and so on.
• User can check the number of items in list using len() function
28 | P a g e
ARTIFICIAL INTELLIGENCE
Tuple: A tuple in python represents a list of comma-separated values of any data type between
parenthesis. It is immutable data type i..e it can not be modified.
Like List, Tuple values are also internally numbered from 0 and so on for forward indexing and -1, -2
from backward indexing.
Example:
>>> favorites=("Blue","Cricket","Gajar Ka Halwa")
>>> print(favorites)
("Blue","Cricket","Gajar Ka Halwa")
>>>print(favorites[1])
Cricket
>>>print(favorites[-2])
Cricket
>>>favorites[0]=‘Football’ #Error, tuple does not support assignment i.e. immutable
29 | P a g e
ARTIFICIAL INTELLIGENCE
DICTIONARY
• Dictionary is another feature of Python.
• It is an unordered set of comma separated key:value pairs. Dictionary Items are defined in Curly
Brackets { }.
• Keys defined in Dictionary cannot be same i.e. no two keys can be same.
• Keys should be of immutable data types i.e. string, number or tuple.
• Dictionary is mutable. i.e. We can modify dictionary elements.
• In dictionary, values can be accessed using keys. The syntax is:
dictionary-name[key]
• User can modify dictionary elements in following syntax:
dictionary-name[key]=new value
Conditional Statements
While coding in Python, a lot of times we need to take decisions. For example, if a person needs to create a
calculator with the help of a Python code, he/she needs to take in 2 numbers from the user and then ask the
user about which function he/she wishes to operate. Now, according to the user’s choice, the selection of
function would change. In this case, we need the machine to understand what should happen when. This is
where conditional statements help. Conditional statements help the machine in taking a decision according to
the condition which gets fulfilled. There exist different types of conditional statements in Python.
30 | P a g e
ARTIFICIAL INTELLIGENCE
There are basically three types of selection statement:
1. if statement
2. if….else statement
3. Nested if…else statement (if…..elif statement)
if statement: It is the basic form of selection statement. It checks the condition & if the condition is true,
then statements under if will get executed & if the condition is false, then will not be executed.
Syntax: if condition:
statement1
statement2
statement3
if….else statement: It checks the condition & if condition is true then some statements will be executed
and if condition is false then some other statements will be executed.
Syntax: if condition:
statement1(s)
else:
statement2(s)
program of senior citizen is example of if…else statement.
Some program exercise:
1. Write a program in python to decide whether a given number is even or odd.
2. Write a program in python to decide whether a number is divisible by 5 or not.
if….elif statement: it is used when multiple chain of conditions have to be checked. Each elif condition
must be followed by condition and then followed by colon. After elif condition user can give else
condition and else condition will get executed if all above condition evaluates to false.
Syntax: if condition:
statement1(s)
elif condition:
statement2(s)
elif condition:
statement3(s)
else:
statement4(s)
31 | P a g e
ARTIFICIAL INTELLIGENCE
Lets take an example of finding a day based on number, for example if we will input the number as 1, it
should give Monday, 2 for Tuesday and so on.
Loop Statement
These statements are used to execute the statement(s) in repeated manner until the condition is true.
There are two types of loop statements:
1. for loop
2. While loop
3. Do while loop
32 | P a g e
ARTIFICIAL INTELLIGENCE
for loop-: It is used to iterate over a sequence like string, list. User can execute a set of statement, once
for each item in a sequence.
Syntax:- for value in sequence: statement
• Lets take an example
In above example, range(2,9,2) will generate a list of values [2,4,6,8] and each time variable a
corresponds to single item one by one, so value of a will be 2,4,6,8 and for each time “Hello World” will
be executed and after fourth time control will come out from the loop and print “Exit”. print(“Exit”) is
outside of loop so control will printed only once when it will come out from loop.
while loop-: It is used to execute a block of statement as long as a given condition is true & when the
condition become false, the control will come out of the loop. The condition is checked every time at the
beginning of the loop.
Syntax: while condition:
statement(s)
Lets take an example of printing multiplication table of a number which is given by user.
33 | P a g e
ARTIFICIAL INTELLIGENCE
In above example, we have input a number from user using input() function & then initialize x to 1. In
while loop we put the condition that loop body will execute again and again until value of x becomes
more than 10 & we have multiplied x to number, but the main point is after printing the value we have
to increase value of x by 1, so when it will go for printing the value the value of x is now 2 and value of
8 will get printed and so on.
34 | P a g e