UNIT 1 INTRODUCTION
SYLLABUS
• History of Python
• Introduction to the IDLE interpreter (shell)
• Expressions
• Data Types
• Built-in function
• Conditional statements
• Iterative statements
• Input/output
• Compound Data Types
• Nested compound statements
• Introduction to Object Oriented Concepts.
History
• Python was conceived in the late 1980s by
Guido van Rossum at Centrum Wiskunde &
Informatica (CWI) in the Netherlands
• Its implementation began in December 1989.
• Commercial use from 1990 onwards
Features of Python
Introduction to the IDLE interpreter
• Python is a freeware that can be installed on
your workstation or laptop.
• The current version of is Python 3.8.2. (Release
date: Feb 24, 2020). Python can be
downloaded from the
[Link] website
• IDLE (Integrated Development and Learning
Environment) is an IDE for Python
• Python programs can also be executed in
Python command line.
Points to Remember while Writing a Python Program
• Case sensitive
• Punctuation is not required at end of the
statement
• In case of string use single or double quotes i.e.
‘ ’ or “ ”
• Must use proper indentation
• Python Program can be executed in two
different modes:
– Interactive Mode Programming
– Script mode programming
Input & Output Statements
Input – to read values from the user
Syntax:
Variable=input()
Input() – function used to read values
Output- to display the result
Syntax:
print(“hello students”)
print(“welcome”)
Print(“value is”, x)
Expression
• An expression is a combination of variables,
operators, values and calls to functions.
• Expressions need to be evaluated
Example:
z=a+b
p = 3.14 * r * r
a>b
2 = ab - invalid expression
VARIABLES
• Variable is the name given to a reserved
memory location to store values.
• It is also known as Identifier in python.
• Naming and Initialization of a variable
1. A variable name is made up of alphabets (Both
upper and lower cases) and digits and is case
sensitive
2. No reserved words
3. Initialize before calling
4. Multiple variables initialized
5. Dynamic variable initialization
Example
X2=25
if=30
a=45
print(A)
x=y=z=50
a,b,c=1,2,3
print(a)
print(b)
print(c)
Data Types
• A Data type indicates which type of value a
variable has in a program.
• The most common data types used in python
are
str (string)
int(integer)
float (floating-point).
Numeric
• Integers –
int – both +ve and –ve values can be represented
• Float – float class is used to represent floating
point number which is a real number with
floating point representation.
– float
– fractional point E.g.: 3.415, 5.15
• Complex Numbers
― complex
― For example: 5 + 7j
― where 5 is the real part and 7 is the imaginary part
Number Type Conversion
• int(x) - to convert x to a plain integer.
• long(x) -to convert x to a long integer.
• float(x) -to convert x to a floating-point
number.
• complex(x) -to convert x to a complex number
with real part x and imaginary part zero.
• complex(x, y) - to convert x and y to a
complex number with real part x and
imaginary part y. x and y are numeric
expressions
Example
Program:
a = 10
print("Type of a: ", type(a))
b = 20.0
print("\nType of b: ", type(b))
c = 5 + 7j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
Mathematical Functions
[Link]. Function & Returns ( Description )
1 abs(x) -The absolute value of x: the (positive) distance between x and zero.
2 fabs(x) -The absolute value of x.
3 ceil(x)-The ceiling of x: the smallest integer not less than x.
4 floor(x) -The floor of x: the largest integer not greater than x.
5 log(x) -The natural logarithm of x, for x > 0.
6 min(x1, x2,...)-The smallest of its arguments: the value closest to negative infinity.
7 modf
(x) -The fractional and integer parts of x in a two-item tuple. Both parts have the sam
e sign as x. The integer part is returned as a float.
8 pow(x, y) -The value of x**y.
9 round(x [,n]) -x rounded to n digits from the decimal point. Python rounds away fro
m zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
A Demo
• Both abs() and fabs() represent the mathematical
functions which give us the absolute value of numbers.
But there is a subtle difference between both of them
which we can explore in the examples below.
• Example
• The abs() functions returns the absolute value as an
integer or floating point value depending on what value
was supplied dot it. But the fabs) function will always
return the value as floating point irrespective of
whether an integer or a floating point was supplied to it
as a parameter.
import math
n = -23
print(abs(n))
print([Link](n))
n = 21.4
print(abs(n))
print([Link](n))
n = complex(10,12)
print(abs(n))
#print([Link](n)) – Causes errorOutput
• Running the above code gives us the following result −
• 23 23.0 21.4 21.4 15.620499351813308
Boolean
• The Boolean data type has two built-in values True or
False.
• It is denoted by the class bool.
• Note – True and False with capital ‘T’ and ‘F’ are valid
boolean values.
# Python program to demonstrate Boolean type
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool’>
<class 'bool’>
NameError: name 'false' is not defined
Sequence Type
• A sequence is an ordered collection of similar
or different data.
• Using sequence, Multiple values can be stored
in the data type in an efficient manner.
• There are different types of sequence data
type such as
i) Strings ii) List iii) Tuple
Strings
• String is an array of bytes.
• Each byte represents a Unicode character.
• A string is a collection of one or more
characters put in a single quote, double-quote
or triple quote.
• In python there is no character data type, a
character is a string of length one.
• It is represented by str class.
• Individual characters of a string can be
accessed by using the method of Indexing
Example
Strings: Sequence of characters inside single quotes or double quotes.
E.g. myuniv = “Sathyabama !..”
PROGRAM:
# Python Program for String Manipulation
# Creating a String with single quotes, double quotes, tripple quotes
String1 = 'Welcome’
String2 = "Sathyabama"
String3 = '''CSE’‘’ # Triple Quotes allows multiple lines
String4 = '''Welcome
To
Sathyabama‘’’
print("\nUsing Single quote")
print(String1)
print("\nUsing Double quote")
print(String2)
print("\nUsing Triple quote")
print(String3)
print("\nUsing Triple quote to print multiline")
print(String4)
List
• The List is an ordered sequence of data items.
• It is one of the flexible and very frequently used
data type in Python.
• All the items in a list are not necessary to be of
the same data type.
• Declaring a list is a straight forward process.
• Items in the list are just separated by commas
and enclosed within brackets [ ]
Example: li=[10,2,3,45]
list1 =[3.141, 100, ‘CSE’, ‘ECE’, ‘IT’, ‘EEE’]
List Methods
• A single list may contain Data Types like Integers, Strings,
as well as Objects.
• Lists are mutable.
• Lists are ordered and have definite count.
• The list index starts with 0.
• Duplication of elements is possible in list. The lists are
implemented by list class.
Tuple
• Tuple is also an ordered sequence of items of
different data types like list.
• But, in a list data can be modified even after
creation of the list whereas Tuples are
immutable and cannot be modified after
creation.
• Example: t = (50,'python', 2+3j)
Set
• The Set is an unordered collection of unique data items.
• Items in a set are not ordered, separated by comma and
enclosed inside { } braces.
• Sets are helpful in performing operations like union and
intersection.
• The major advantage of using a set, as opposed to a list,
is that it has a highly optimized method for checking
whether a specific element is contained in the set.
Dictionary
• Dictionary is an unordered collection of data
values.
• It is used to store data values like a map.
• Dictionary holds key:value pair.
• Key-value is provided in the dictionary to make
it more optimized.
• Each key-value pair is separated by a colon :,
whereas each key is separated by a ‘comma’.
• Example: dict={1:”Jan”, 2:”Feb”, 3:”March”}
Difference Between List Tuple Set And
Dictionary
Python Built-in Functions
• A function is a group of statements that performs a specific
task. Python provides a library of functions like any other
programming language.
Mathematical Functions, String Functions
Mathematical Functions
Conditional Statements
• Logical Conditions Supported by Python
Equal to (==) Eg: a == b
Not Equal (!=) Eg : a != b
Greater than (>) Eg: a > b
Greater than or equal to (>=) Eg: a >= b
Less than (<) Eg: a < b
Less than or equal to (<=) Eg: a <= b
Types of Conditional Statements
• Simple if statement
• if – else statement
• elif- statement
• Nested if else statement
Iterative Statements
• Sometimes certain section of the code (block)
may need to be repeated again and again as long
as certain condition remains true.
– while loop statement
– For loop statement
While Loop
• A while loop statement in Python
programming language repeatedly executes a
target statement as long as a given condition
is true.
Using break, continue, else Statements
For loop
• With the for loop we can execute a set of
statements, once for each item in a list, tuple,
set etc.
The range() Function
• range() only works with the integers.
• All arguments must be integers.
• You can not use float number or any other type
in a start, stop and step argument of a range()
• _ -ve range()
• -ve to +ve range
• + ve to –ve range
Example
Compound Data Type
• List
• Tuple
• Set
• Dictionary
Compound Statements
• It is a statement comprise of group of statements
• The compound statements are usually executes,
when a condition satisfies or a code block is
called directly or through a function call.
Example:
If statement
While Statement
For Statement
Try-Catch in Exception Handling
Class Definition
Function Definition
Nested Compound Statement
Program to find the shipping cost of in Australia,
if the total cost is 25$.
Display Floyd’s triangle using
Python nested for loop
Functions
• A function is a block of organized, reusable
code that is used to perform a single, related
action.
• Functions provide better modularity for your
application and a high degree of code reusing.
Example
Pass by Value
Object Oriented Programming
• Python is a multi-paradigm programming language. It
supports different programming approaches.
• One of the popular approaches to solve a
programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).
• An object has two characteristics:
– attributes
– behavior
• Let's take an example:
– A parrot is can be an object, as it has the following
properties:
– name, age, color as attributes
– singing, dancing as behavior
OOPS Concepts
• Class and Object
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
Class
• A class is a blueprint for the object.
• We can think of class as a sketch of a parrot with
labels.
• It contains all the details about the name, colors,
size etc. Based on these descriptions, we can study
about the parrot.
• Here, a parrot is an object.
The example for class of parrot can be :
Class Parrot:
Data member
Method
Object
• An object (instance) is an instantiation of a
class. When class is defined, only the
description for the object is defined.
• Therefore, no memory or storage is allocated.
• The example for object of parrot class can be:
Obj=Parrot()
Here: obj-> object
Parrot()-> class
Creating Class and Object in Python
A program to understand class variables
s
Constructors
• Constructors are generally used for
instantiating an object.
• The task of constructors is to initialize(assign
values) to the data members of the class when
an object of class is created.
• In Python the __init__() method is called the
constructor and is always called when an
object is created.
Types of constructors
• Default constructor :
– The default constructor is simple constructor which
doesn’t accept any arguments.
– It’s definition has only one argument which is a
reference to the instance being constructed.
• parameterized constructor :
– constructor with parameters is known as
parameterized constructor.
– The parameterized constructor take its first argument
as a reference to the instance being constructed
known as self and the rest of the arguments are
provided by the programmer.
Default Constructor
Parameterized Constructor
Encapsulation & Abstraction
Encapsulation:
It is a mechanism where the data and the code that act on
the data will be bind together.
Example:
Class
Visibility Mode: By default Public
Abstraction:
Explore only the data that is of interest to the user.
Example: Car
Adv: Every user will get his own view of the data according
to his requirements and will not confused with
unnecessary data.
Keywords: public, private, protected
Access Modifiers in Python
Inheritance
• Inheritance allows us to define a class that inherits
all the methods and properties from another class.
• Parent class is the class being inherited from, also
called base class.
• Child class is the class that inherits from another
class, also called derived class.
Syntax for derived class:
Class A:
Base Class definition
Class B(A):
Derived Definition
Types of Inheritance
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Polymorphism
• Polymorphism is a very important concept in
programming.
• It refers to the use of a single type entity
(method, operator or object) to represent
different types in different scenarios.
Types:
– Function Overloading
– Operator Overloading
Function Overloading
• Process of using same function name to
perform multiple operation
Example:
Operator Overloading
• Defining methods for operator is known as
operator overloading.
Operator Overloading