0% found this document useful (0 votes)
3 views18 pages

Unit 1 - Materials

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

Effective Date 01.06.2024 Page No.

Page 1 of 18

VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN


(Autonomous)

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

Staff Incharge HoD Principal


VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN
(Autonomous)

Effective Date 01.06.2024 Page No. Page 2 of 18

UNIT I : Python Overview: Data Types, Expressions Python programming - variable,


Data type, Keywords, Literals, Operator, Expression, type conversion, Comments, input
and output, Strings, Assignment and Comments - Numeric Data Types and Character
Sets, Expressions.

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.

Introduction to Python and installation:


Pythonis a widely used general-purpose, high level programming language. It was
initiallydesigned by Guido van Rossum in 1991 and developed by Python Software
Foundation. Itwas mainly developed for emphasis on code readability, and its syntax
allows programmersto expressconceptsinfewerlinesof code.
Python is a programming language that lets you work quickly and integrate systems
moreefficiently.

There are two major Python versions - Python2 and Python3.


• On16 October 2000, Python2.0 was released with many new features.
• On3rdDecember2008, Python3.0 was released with more testing and
includes new features.
BeginningwithPythonprogramming:
1) Finding anInterpreter:
Effective Date 01.06.2024 Page No. Page 3 of 18

VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN


(Autonomous)

Before we start Python programming, we need to have an interpreter to interpret and


run our programs. There are certain online interpreters like
https://ide.geeksforgeeks.org/,http://ideone.com/orhttp://codepad.org/that can be
used to start Python without installing an interpreter.
Windows: There are many interpreters available freely to run Python scripts like
IDLE(Integrated Development Environment) which is installed when you install the
python software fromhttp://python.org/downloads/
2) Writingfirstprogram:

#ScriptBegins

Statement1
Statement2Statement3
#ScriptEnds

Differencesbetweenscriptinglanguageandprogramminglanguage:
VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN
(Autonomous)

Effective Date 01.06.2024 Page No. Page 4 of 18

Why to use Python:

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

VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN


(Autonomous)

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)

Working with Python Python Code Execution:


Python’s traditional runtime execution model: Source code you type is translated
to byte code, which is then run by the Python Virtual Machine (PVM). Your code is
automatically compiled, but then it is interpreted.

Source Bytecode Runtime

PVM
m.py m.pyc

Source code extensionis.py


Byte code extension is.pyc (Compiledpythoncode)

There are two modes for using the Python interpreter:

• Interactive Mode
• Script Mode
VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN
(Autonomous)

Effective Date 01.06.2024 Page No. Page 6 of 18

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.

The version 3.x of Python IDLE (Integrated Development LearningEnvironment)is used


to develop and run Python code. It can be downloaded from the web resource
www.python.org.

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:

Alternatively, programmers can store Python script source code in a file


with the .py extension, and use the interpreter to execute the contents of the file. To
execute the script by the interpreter, you have to tell the interpreter the name of the
file. For example, if you have a script name MyFile.py and you're working on Unix, to
run the script you have to type:
Effective Date 01.06.2024 Page No. Page 7 of 18

VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN


(Autonomous)

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:

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited


length.
Example:

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)

Effective Date 01.06.2024 Page No. Page 8 of 18

>>>
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, or "floating point number" is a number, positive or negative, containing one or


more decimals.

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

VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN


(Autonomous)

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

Strings in Python are identified as a contiguous set of characters represented in the


quotation marks. Python allows for either pairs of single or double quotes.

• 'hello' is the same as "hello".

• 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") mrcet is an autonomous (')

college

>>>print('mrcet is an autonomous (")

college') mrcet is an autonomous (")

college

Suppressing Special Character:

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:

>>>print("mrcet is an autonomous (\')

college")mrcet isan autonomous(') college

>>>print('mrcet is an autonomous (\")

college')mrcet isan autonomous(")college


Page 11 of
Effective Date 01.06.2024 Page No.
18

VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN


(Autonomous)

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

Keywords are special words used by Python interpreter to recognize the


structure of program. As these words have specific meaning for interpreter, they
cannot be used for any other purpose.
Python’s Keywords

False class finally is return

None continue for lambda try

True def from nonlocal while


VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN
(Autonomous)

Page 12 of
Effective Date 01.06.2024 Page No.
18

and del global not with

as elif if or yield

assert else import pass

break except in raise

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:

• Numeric - Numeric Literals consists of digits and are immutable (unchangeable).


Numeric literals can belong to 3 different numerical types Integer, Float and Complex.

• String - string literal is a sequence of characters surrounded by quotes.

• Boolean - A Boolean literal can have any of the two values: True or False.

String Literals

In Python a string literal is a sequence of characters surrounded by quotes. Python


supports single, double and triple quotes for a string. A Character literal is also
considered as string literal in Python.

A character literal is a single character surrounded by single or double quotes. The


value with triple-quote "' '" is used to give multiline string literal.

Some common type conversion functions and their uses.

EXAMPL
CONVERSIONFUNCTION EUSE VALUERETURNED

int(<anumberorastring> int(3.77) 3
)
Page 13 of
Effective Date 01.06.2024 Page No.
18

VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN


(Autonomous)

int(“33”) 33

float(<anumberor float(22) 22.0


astring>)
str(<anyvalue>) str(99) '99'

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:

print(“string to be displayed as output”)print(variable)

print (“String to be displayed as output ”, variable) print (“String1 ”, variable,“String


2”,variable,“String3”….)

Example

>>>print(“Welcome to Python Programming”)


Welcome to Python Programming
>>> x=5>>>y= 6
>>> z = x+y
>>>print(z)
VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN
(Autonomous)

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

The print() evaluates the expression before printing it on the monitor.


The print () displays an entire statement which is specified within print (
).Comma(,)is used as a separator in print ()to print morethan one item.

Input() Function

In Python, input() function is used to accept data as input at runtime.

Syntax for input() function is:

Variable=input(“prompt string”)

Where, prompt string in the syntax is a statement or message to the user, to


know what input can be given.

Theinput()takeswhateveristypedfromthekeyboardandstorestheentereddatainthegivenva
riable.

>>>city=input()
Rajarajan
>>> print (“I am from”, city)
Iamfrom Rajarajan

STRINGS

 In Python, a string is a sequence of characters enclosed in single or


double quotation marks.
 Notethattheemptystringisdifferentfromastringthatcontainsasingleblank space
character,““.
 Double-quoted strings are handy for composing strings that contain single
quotation marks or apostrophes.

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

VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN


(Autonomous)

>>>”Sun”+”Flower”
SunFlower
>>>“ “*10+“Python”
Ƒ Python

ASSIGNMENT AND COMMENTS

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

NUMERIC DATA TYPES AND CHARACTER SETSINTEGERS

 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

 Python uses floating-point numbers to represent real numbers. Python’s


float type range from –10308to10308andhave 16digitsofprecision.
 A floating-point number can be written using either ordinary decimal
notation or scientific notation (for large numbers).

DECIMALNOTA SCIENTIFICNOTA
MEANING
TION TION

3.78 3.78e0 3.78 × 100

3780.0 3.78e3 3.78 × 103


0.378 3.78e-1 3.78 × 10-1

0.00378 3.78e-3 3.78 × 10-3

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

VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN


(Autonomous)

 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

0 NUL SOH STX ETX EOT ENQ ACK BEL BS HT

1 LF VT FF CR SO SI DLE DCI DC2 DC3

2 DC4 NAK SYN ETB CAN EM SUB ESC FS GS

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

[TABLE]The original ASCII character set


VIVEKANANDHA COLLEGE OF ARTS AND SCIENCES FOR WOMEN
(Autonomous)

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'
>

You might also like