Unit 1 - Materials
Unit 1 - Materials
Unit 1 - Materials
Page 1 of 18
Course Material
B.Sc
Department Computer Science Programme Information
Technology
Artificial Intelligence Using
Course Title Course Code 24U4ITC04
Python
Semester &
Class &
III B.Sc IT & A Academic qha52dc
Section
Year
Handling Assistant
N.Premalatha Designation
Staff Professor
PYTHON–OVERVIEW
Python is a high-level, multi-paradigm programming language. As Python is an
interpreter- based language.
Python is a dynamically typed language with very intuitive datatypes.
Python is an open - source and cross - platform programming language.
It is available for use under Python Software Foundation License (compatible to
GNU General Public License) on all the major operating system platforms
Linux, Windows and Mac OS.
The design philosophy of Python emphasizes on simplicity, read ability and
unambiguity.
Python is known for its batteries included approach as Python software is
distributedwithacomprehensivestandardlibraryoffunctionsandmodules.
Introduction to Python and installation, data types: Int, float, Boolean, string,
and list; variables, expressions, statements, precedence of operators, comments;
modules, functions---function and its use, flow of execution, parameters and
arguments.
#ScriptBegins
Statement1
Statement2Statement3
#ScriptEnds
Differencesbetweenscriptinglanguageandprogramminglanguage:
VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN
(Autonomous)
The following are the primary factors to use python in day-to-day life:
1. Python is object-oriented
Structure supports such concepts as polymorphism, operation
overloading and multiple inheritance.
2. Indentation
Indentation is one of the greatest feature in python. It’s free (open source)
Downloading python and installing python is free and easy.
3. It’sPowerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities(e.g.Numeric, NumPy, sciPy)
Automatic memory management
4. It’s Portable
Python runs virtually every major platform used today
As long as you have a compatible python interpreter installed,
python programs will run inexactly the same manner,
irrespective of platform.
5. It’s easy to use and learn
No intermediate compile
Python Programs are compiled automatically to an intermediate
form called byte code, which the interpreter then reads.
This gives python the development speed of an interpreter
without the performance loss inherent in purely interpreted
languages.
Structure and syntax are pretty intuitive and easy to grasp.
6. Interpreted Language
Python is processed at runtime by python Interpreter
7. Interactive Programming Language
Users can interact with the python interpreter directly for writing the
programs
8. Straight forward syntax
The formation of python syntax is simple and straight forward which also
makes it popular.
Effective Date 01.06.2024 Page No. Page 5 of 18
Installation:
There are many interpreters available freely to run Python scripts like IDLE
(IntegratedDevelopmentEnvironment)whichisinstalledwhenyouinstallthepythonsoftware
fromhttp://python.org/downloads/
Stepstobefollowedandremembered:
Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step3: Run Executable Installer.
Step4: Verify Python Was Installed On Windows.
Step5: Verify Pip Was Installed.
Step6:Add Python Path to Environment Variables (Optional)
PVM
m.py m.pyc
• Interactive Mode
• Script Mode
VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN
(Autonomous)
1. The Interactive mode allows us to write codes in Python command prompt (>>>).
The prompt (>>>) indicates that Interpreter is ready to
acceptinstructions.ThepromptonscreenmeansIDLEisworkingininteractivemode.
2. In script mode programs can be written and stored as separate file with
theextension.pyandexecuted.Scriptmodeisusedtocreateandeditpythonsourcefile.
RunningPythonininteractivemode:
>>>print ("hello world") hello world
#Relevant output is displayed on sub sequent lines without the>>>symbol
>>>x= [0,1,2]
#Quantities stored in memory are not displayed by default.
>>> x
#If a quantity is stored in memory, typing its name will display it.[0,1,2]
>>>2+3
The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python
interpreter uses to indicate that it is ready. If the programmer types 2+6, the inter
preterreplies8.
Running Pythoninscriptmode:
pythonMyFile.py
Working with the interactive mode is better when Python programmers deal with small
pieces of code as you can type and execute them immediately, but when the code is
morethan2-4lines,using the script for coding can help to modify and use the code in
future.
Example:
Datatypes:
The data stored in memory can be of many types. For example, a student roll number
is stored as a numeric value and his or her address is stored as alphanumeric
characters. Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.
Int:
102,4567,567 # Decimal
integers0o102,0o876,0o432
#Octalintegers0X102,0X876,0X
432 #Hexa decimal integers
34L,523L #Long decimal integers
-------------------------------------------------------------------------------------------
>>>print(24656354687654+
2)24656354687656
>>>print(20
)20
VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN
(Autonomous)
>>>
print(0b10)
2
>>>
print(0B10)
2
>>>
print(0X20)
32
>>> 20
20
>>>
0b102
>>>a=10
>>>
print(a)10
# To verify the type of any object in Python, use the type()function:
>>>type(10)
<class'int'>
>>>a=11
>>>print(type(a))
<class'int'>
Float:
A Floating Point Data is represented by a sequence of decimal digits that includes a
decimal point. An Exponent data contains decimal digit part, decimal point, exponent
part followed by one or more digits.
Example:
123.34,456.23,156.23 # Floating point data12.E04,
24.e04 # Exponent data
Complex number is made up of two floating point values, one each for the real and
imaginary parts.
Float can also be scientific numbers with an "e" to indicate the power of 10.
Effective Date 01.06.2024 Page No. Page 9 of 18
>>>y=2.8
>>> y2.8
>>>y=2.8
>>>print(type(y))
<class'float'>
>>>type(.4)
<class'float'>
>>>2.
2.0
Example:
x = 35e3y=12E4
z=-87.7e100
print(type(x))print(type(y))print(type(z))
Output:
<class'float'>
<class'float'>
<class'float'>
Boolean:
Objects of Boolean type may have one of two values, True or False:
Example:
Bool_var1=True
Bool_var2=False
---------------------------
>>>type(True)
<class'bool'>
>>>type(False)
<class'bool'>
String:
• Stringscanbeoutputtoscreenusingtheprintfunction.
For example: print("hello").
VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN
(Autonomous)
Page 10 of
Effective Date 01.06.2024 Page No.
18
>>>print("mrcet
college")
mrcet college
>>>type("mrcetcollege")
<class'str'>
>>>print('mrcet
college')
mrcet college
>>> ""
''
If you want to include either type of quote character within the string, the simplest way
is to delimit the string with the other type. If a string is to contain a single quote,
delimit it with double quotes and vice versa:
>>>print("mrcet is an autonomous (')
college
college
Specifying a backslash (\) in front of the quote character in a string “escapes” it and
causes Python to suppress its usual special meaning. It is then interpreted simply as a
literal single quote character:
The following is a table of escape sequences which cause Python to suppress the
usual special interpretation of a character in a string:
>>>print('a\....b')
a. b
>>>print('a\ b\c')
abc
>>>print('a \n b')
a
b
>>>print("mrcet \n college")
mrcet
college
EscapeSe Usual Interpretation
quence ofCharacter(s)AfterBack “Escaped”Interpretatio
slash n
\' Terminates string with single quote opening Literal single quote(')
delimiter character
\" Terminates string with double quote opening Literal double quote(")
delimiter character
\newline Terminates input line New line is ignored
\\ Introduces escape sequence Literal backslash
(\)character
In Python (and almost all other common computer languages) ,at a b character can be
specified by the escape sequence\t:
>>> print("a\tb")
a b
KEYWORDS
Page 12 of
Effective Date 01.06.2024 Page No.
18
as elif if or yield
LITERALS
A literal is the way a value of a data type looks to a programmer. The programmer can
use a literal in a program to mention a data value. When the Python interpreter
evaluates a literal, the value it returns is simply that literal.
Literal is a raw data given to a variable or constant. In Python, there are various types
of literals.
They are:
• Boolean - A Boolean literal can have any of the two values: True or False.
String Literals
EXAMPL
CONVERSIONFUNCTION EUSE VALUERETURNED
int(<anumberorastring> int(3.77) 3
)
Page 13 of
Effective Date 01.06.2024 Page No.
18
int(“33”) 33
COMMENTS
In Python, comments begin with hash symbol (#). The lines that begins with #are
considered as comments and ignored by the Python interpreter. The multiline
comments should be enclosed within a set of ''' '''(triple quotes) as given below.
#It is Single line Comment
''' It is multiline comment which contains more than one line '''Indentation:
Python uses whitespace such as spaces and tabs to define program blocks. The
number of whitespaces (spaces and tabs) in the indentation is not fixed, but all
statements within the block must be indented with same amount spaces.
INPUT AND OUTPUT FUNCTIONS
The input() function helps to enter data at run time by the user and the output
function print() is used to display the result of the program on the screen aftere
xecution.
Print() Function
In Python, the print() function is the output function used to display result
onthescreen.
Thesyntaxforprint()isasfollows:
Example
Page 14 of
Effective Date 01.06.2024 Page No.
18
11
>>>print(“The sum=”,z)
The sum=11
>>>print(“The sumof”,x, “and”,y,“ is”,z)
Thesumof 5and6is11
Input() Function
Variable=input(“prompt string”)
Theinput()takeswhateveristypedfromthekeyboardandstorestheentereddatainthegivenva
riable.
>>>city=input()
Rajarajan
>>> print (“I am from”, city)
Iamfrom Rajarajan
STRINGS
String Concatenation
You can join two or more strings to form a new string using the concatenation operator+.
Here is an example:
Page 15 of
Effective Date 01.06.2024 Page No.
18
>>>”Sun”+”Flower”
SunFlower
>>>“ “*10+“Python”
Ƒ Python
Assignment operators
In Python, = is a simple assignment operator to assign values to variable.
There are various compound operators in Python like+=, -=, *=, /=, %=, **=and //=
are also available.
Operato Description Example
r
Assumex=10
>>>x=10
= Assigns right side operands to left variable
>>>b=”Computer”
Added and assign back the result to left >>>x+=20#
+=
Operand i.e. x=30 x=x+20
Subtracted and assign back the result to left
-= >>>x-=5 #x=x-5
Operand i.e. x=25
Multiplied and assign back the result to left
*= >>>x*=5#x=x*5
Operand i.e. x=125
Divided and assign back the result to left
/= >>>x/=2 #x=x/2
Operand i.e. x=62.5
Taken modulus(Remainder) using two operands
%= and assign the result >>>x%=3 #x=x%3
To left operand
i.e. x=2.5
Performed exponential (power) calculation on
**= operators and assign value to the left Operand >>>x**=2# x=x**2
i.e. x=6.25
//= Performed floor division on operators and assign >>>x//=3
value to the left operand
i.e. x=2.0
VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN
(Autonomous)
Page 16 of
Effective Date 01.06.2024 Page No.
18
COMMENTS
A comment is a piece of program text that the interpreter ignores but that
provides usefull documentation to programmers.
For name and purpose of a program this type of comment, called a docstring. end-
of- line comments can document a program. These comments begin with the
#symbol and extend to the end of a line.(already seent his…)
The Integers include 0, all of the positive whole numbers, and all of the
negative whole numbers. The most common implementation of the int data
type in many programming languages consists of the integers from –
2,147,483,648(–231) to2,147,483,647(231– 1).
FLOATINGPOINTNUMBERS
DECIMALNOTA SCIENTIFICNOTA
MEANING
TION TION
CHARACTER SETS
In Python, character literals look just like string literals and are of the string type.
But they also belong to several different character sets, among them the ASCII set
and the Unicode set.
The term ASCII stands for American Standard Code for Information
Interchange. In the 1960s, the original ASCII set encoded integers from
0through127.
An example of a control character is Control + D, which is the command to
terminate a shell window.
Page 17 of
Effective Date 01.06.2024 Page No.
18
Asnewfunctionkeysandsomeinternationalcharacterswereaddedtokeyboards,
the ASCII set doubled in size to 256 distinct values in themid-1980s.
Then, when characters and symbols were added from languages other than
English, the Unicode set was created to support 65,536 values in the early
1990s.
The digits in the left column represent the leftmost digits of an ASCII code, and
the digits in the top row are the rightmost digits. Thus, the ASCII code of the
character 'R' atrow8,column 2is82. Which is in below table…
0 1 2 3 4 5 6 7 8 9
3 RS US SP ! “ # $ % & `
4 ( ) * + , - . / 0 1
5 2 3 4 5 6 7 8 9 : ;
6 < = > ? @ A B C D E
7 F G H I J K L M N O
8 P Q R S T U V W X Y
9 Z [ \ ] ^ _ ‘ a b c
10 d e f g h i j k l m
11 n o p q r s t u v w
12 x y z { | } ~ DEL
Page 18 of
Effective Date 01.06.2024 Page No.
18
The ASCII character set maps to a set of integers. Python’s ord and chr
functions convert characters to their numeric ASCII codes and back again,
respectively.
The next session uses the following functions to explore the ASCII system:
>>>ord('a')97
>>>ord('A')65
>>>chr(65)'A'
>>>chr(66)'B'
>