python
python
Introduction
•Van Rossum picked the name Python for the new language
from the TV show, Monty Python’s Flying Circus.
• Simple
• Easy to learn
• Open source
• High level language
• Dynamically typed
• Platform Independent
• Portable
• Procedure and object oriented
Features of Python
• Interpreted
• Huge library
• Scripting language
• Database Connectivity
• Scalable
• Batteries included
Features of Python contd…
• Simple
• Easy to learn
Python uses very few keywords. Its programs use very simple
structure. So, developing programs in python become easy.
• Dynamically typed
• Portable
Python programs will give the same result since they are
platform independent. Once a python program is written, it can
run on any computer system using PVM.
Features of Python contd…
• Procedure and object oriented
• Huge Library
• Scripting language
• Database Connectivity
• Scalable
Python programs are scalable since they can run on any platform
and use the features of the new platform effectively.
Features of Python contd…
• Batteries included
A B C
• Even if the objects A, B and C are no longer used in the Python
program, still these objects contain 1 reference to each one. Since
the reference count for each object is 1, the garbage collector will
not remove these objects from memory.
• These objects stay in memory even after the program execution
completes. To get around this, garbage collector uses an algorithm
(logic) for detecting reference cycles and removing objects in the
cycle.
• Garbage collector classifies the objects into three generations.
• The newly created objects are considered as generation 0 objects.
First time, when the garbage collector examines the objects in
memory and does not remove an object from memory due to the
reason that the object is used by the program, then that object is
placed into next generation, say generation 1.
• When the garbage collector intends to delete the objects for the
second time and the object also survives for the second time, then it
is placed into generation 2.
• Thus, older objects belong to generation 2.,
•Garbage collector tries to delete younger objects which
are not referenced in the program rather than the old
objects.
•Garbage collector runs automatically.
•In some cases, where reference cycles are found in the
program, it is better to run the garbage collector
manually.
•For this purpose, collect() method of gc module can be
used.
•Manual garbage collection can be done in two ways:
time-based and event-based. If the garbage collector is
called in certain intervals of time, it is called time-based
garbage collection.
•If the garbage collector is called on the basis of an event,
for example, when the user disconnects from an
application, it is called event-based garbage collection.
C vs Python
C Python
C Python C is procedure-oriented
Python is object-oriented oriented language. It
programming language. It does not contain the
contains features like classes, objects,
features like classes, objects, inheritance,
inheritance, polymorphism, etc.
polymorphism, etc.
The programmer should allocate and Memory allocation and deallocation is done
deallocate memory using automatically by PVM.
malloc(), calloc(), realloc() or free()
functions.
C does not contain a garbage collector. Automatic garbage collector is available in
Python.
C supports single and multi-dimensional Python supports only single dimensional
arrays. arrays. To work with multi-dimensional
arrays, we should use third party
applications like numpy.
The array index should be positive integer. Array index can be positive or negative
integer number. Negative index represents
locations from the end of the array.
C does not have exception handling facility Python handles exceptions and hence
and hence C programs are weak. Python programs are robust.
The programmer should allocate and Memory allocation and deallocation is done
deallocate memory using automatically by PVM.
malloc(), calloc(), realloc() or free()
functions.
Java vs Python
Java Python
Java is object-oriented Python blends the functional
programming language. programming with object-oriented
Functional programming features programming features. Lambdas
are introduced into Java 8.0 are already available in Python.
through lambda expressions.
Java language type discipline is Python type discipline is dynamic
static and weak. and strong.
It is compulsory to declare the Type declaration is not required
datatypes of variables, arrays etc. in Python.
in Java.
Java programs are verbose. It Python programs are concise and
means they contain more number compact. A big program can be
of lines. written using very less number of
lines.
Memory allocation and deal Memory allocation and deal
location is done automatically by location is done automatically by
JVM (Java Virtual Machine). PVM (Python Virtual Machine).
The variable in for loop does not The variable in the for loop
increment automatically. But in for increments automatically.
each loop, it will increment
automatically.
Java has do... while, while, for and Python has while and for loops.
for each loops.
Java has switch statement. Python does not have switch
statement.
Java supports single and Python supports only single
multi-dimensional arrays. dimensional arrays. To work with
multi-dimensional arrays, we should
use third party applications
like numpy.
#include<stdio.h> class Addition a = 10
{ b = 20
void main()
public static void main(String print("The Sum : ",(a+b))
args[ ])
{
{
a=10; a = 10;
b=20; b = 20;
System.out.println("The Sum :
printf("The Sum : %d",(a+b)); "+(a+b));
}
}
}
Comments in Python
•Comments can be used to explain Python
code.
•Comments can be used to make the code
more readable.
•Comments can be used to prevent execution
when testing code.
•There are two types of comments in Python:
•Single line comments
•Multiline Comments
•Single line comments
#This is a comment
print("Hello, World!")
"""
This is first line
This second line
Finally comes third """
'''
This is first line
This second line
Finally comes third '''
• The triple double quotes ("") or triple single quotes ("") are
called 'multi line comments' or block comments'. They are
used to enclose a block of lines as comments.
Docstrings
• Python supports only single line comments.
• Multi line comments are not available in Python.
• The triple double quotes or triple single quotes are actually
not multi line comments but they are regular strings with
the exception that they can span multiple lines.
• Memory will be allocated to these strings internally.
• If these strings are not assigned to any variable, then they
are removed from memory by the garbage collector and
hence these can be used as comments.
•using """ or '''are not recommended for comments by
Python people since they internally occupy memory and
would waste time of the interpreter since the interpreter has
to check them.
•If we write strings inside """ or ''' and if these strings are
written as first statements in a module, function, class or a
method, then these strings are called documentation strings
or docstrings.
•These docstrings are useful to create an API documentation
file from a Python program.
Datatypes in Python
•A datatype represents the type of data stored into a
variable or memory.
•The datatypes which are already available in Python
language are called Built-in datatypes.
•The datatypes which can be created by the
programmers are called User-defined datatypes.
•The built-in datatypes are of five types:
•None Type
•Numeric types
•Sequences
•Sets
•Mappings
None Type
•In Python, the 'None' datatype represents an object
that does not contain any value.
•In languages like Java, it is called 'null' object. But in
Python, it is called 'None' object.
•In a Python program, maximum of only one 'None'
object is provided.
•In Boolean expressions , None data type represents
False.
Numeric Types
•The Numeric type represent numbers.
•There are three sub types:
•int
•float
•complex
int Datatype
•The int datatype represents an integer number.
•An integer number is a number without any decimal
point.
•For example:
a=-57
•In Python, there is no limit for the size of an int
datatype.
float Datatype
•The float datatype represents floating point
numbers.
•Floating point number is a number that contains
decimal point.
•For example:
num=55.67
x=22.55e4 //22.55x103
Complex datatype
•A complex number is a number that is written in the
form of a + bj or a + bJ.
•Here, 'a' represents the real part of the number and
'b' represents the imaginary part of the number.
•The suffix j or 'J' after 'b' indicates the square root
value of -1.
•The parts 'a' and b' may contain integers or floats.
•For example: 3+5j, -1-5.5J, 0.2+10.5J are all complex
numbers.
c1=-1-5.5J
Representing Binary, Octal and
Hexadecimal numbers
•A binary number should be written by prefixing Ob
(zero and b) or OB (zero and B) before the value.
•For example, Ob110110, OB101010011 are treated as
binary numbers.
•Hexadecimal numbers are written by prefixing Ox
(zero and x) or OX (zero and big X) before the value,
as OxA180 or OX11fb91 etc.
• Octal numbers are indicated by prefixing Oo (zero
and small o) or 00 (zero and then O) before the
actual value.
•For example, 00145 or 00773 are octal values.
bool Datatype
•The bool datatype in Python represents boolean
values.
•There are only two boolean values True or False that
can be represented by this datatype.
•Python internally represents True as 1 and False as 0.
•A blank string like " " is also represented as False.
•Conditions will be evaluated internally to either True
or False.
•For example,
a = 10
b = 20
if(a<b): print("Hello") # displays
Sequences in Python
•Sequence represents a group of elements or items.
•There are six types of sequences in Python:
•str
•bytes
•bytearray
•list
•tuple
•range
str Datatype
•str represents string datatype.
• string is represented by group of characters.
•string are enclosed in single quotes or double
quotes.
•For example:
str=“welcome”
str=‘welcome’
•We can also write strings inside “”” (triple double
quotes) or ‘’’(triple single quotes)
•Example:
s= “welcome to python class”
print(s)
#0
#1
#2
#3
•Syntax of range()
•The range() function can take a maximum of three
arguments:
range(start, stop, step)
•The start and step parameters in range() are
optional.
•Example : range() with Stop Argument
•If we pass a single argument to range(), it means we are
passing the stop argument.
•In this case, range() returns a sequence of numbers starting
from 0 up to the number (but not including the number).
fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())
# update value
my_dict['age'] = 27
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
Literals in Python
•A Literal is a constant value that is stored into a
variable in a program.
•Types of Literals in Python:
•Numeric literals
•Boolean Literals
•String literals
Numeric Literals
•Numeric Literals are immutable (unchangeable).
Numeric literals can belong to 3 different numerical
types: Integer, Float, and Complex.
a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal
#Float Literal
float_1 = 10.5
float_2 = 1.5e2
#Complex Literal
x = 3.14j
print(a, b, c, d)
print(float_1, float_2)
print(x, x.imag, x.real)
String Literals
•A group of characters is called a string literal.
•These string literals are enclosed in single quotes or
double quotes or triple quotes .
• In Python, there is no difference between single
quoted strings and double quoted strings. Single or
double quoted strings should end in the same line.
•When a string literal extends beyond a single line
we should use triple quotes.
Determining the Datatype of a Variable
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)
Comparison(Relational) operators
print('x or y is',x or y)
print('not x is',not x)
Bitwise operators
•Bitwise operators act on operands as if they were
strings of binary digits. They operate bit by bit.
# Examples of Bitwise operators
a = 10
b=4
# Print bitwise AND operation
print(a & b)
# Print bitwise OR operation
print(a | b)
# Print bitwise NOT operation
print(~a)
# print bitwise XOR operation
print(a ^ b)
# print bitwise right shift operation
print(a >> 2)
# print bitwise left shift operation
print(a << 2)
Assignment operators
•Assignment operators are used in Python to assign
values to variables.
# Examples of Assignment Operators
a = 10
# Assign value
b=a
print(b)
# Add and assign value
b += a
print(b)
# Subtract and assign value
b -= a
print(b)
# multiply and assign
b *= a
print(b)
# bitwise leftshift operator
b <<= a
print(b)
Identity operators
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Mathematical Functions
•In Python, a module is a file that contains a group of
useful objects like functions, classes or variables.
•math is a module that contains several functions to
perform mathematical operations.
•If we want to use any module in our Python
program, first we should import that module into
our program by writing 'import' statement. For
example, to import math' module, we can write:
import math
•Once this is done, we can use any of the functions
available in math module. Now, we can refer to
sqrt() function from math module by writing
module name before the function as:
math.sqrt().
•X=math.sqrt(16)
•We can also write import math as m
•X=m.sqrt(16)
•If we want to import only one or two functions from
math module then we can write as follows:
from math import sqrt,factorial
Function Description
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
•Understanding indentation is very important in
Python.
•Indentation refers to spaces that are used in the
beginning of a statement.
•The statements with same indentation belong to
same group called a suite.
•By default, Python uses 4 spaces but it can be
increased or decreased by the programmers.
The if... else statement
•The if... else statement executes a group of statements
when a condition is True; otherwise, it will execute another
group of statements.
•The syntax of if... else statement is given below:
if test expression:
Body of if
else:
Body of else
•The if..else statement evaluates test expression and
will execute the body of if only when the test
condition is True.
•The if block can have only one else block. But it can
have multiple elif blocks.
Nested if statements
'''In this program, we input a number check if the number is positive or
negative or zero and display an appropriate message This time we use
nested if statement'''
while i <= n:
sum = sum + i
i = i+1 # update counter
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
x='ABCDEF‘
n=len(x)
for i in range(n):
print(x[i])
#to find sum of list of numbers using for
list=[10,20,30,40,50]
sum=0
for i in list
print(i)
sum+=i
print(‘sum=‘,sum)
The else Suite
•In python it is possible to use ‘else’ statement along with for
loop or while loop.
group1 = [1,2,3,4,5]
search = int(input('Enter element to search:'))
for element in group1:
if search == element:
print('Element found in group')
break #come out of for loop
else:
print('Element not found in group1') #this is else suite
lower = int(input("Enter starting number : "))
upper = int(input("Enter ending number: "))
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,end='\t')
The break Statement
print("The end")
num = 0
for i in range(10):
num += 1
if num == 8:
break
print("The num has value:", num)
print("Out of loop")
Python Continue Statement
•Python Continue Statement skips the execution of
the program block from after the continue
statement and forces the control to start the next
iteration.
•Python Continue statement is a loop control
statement that forces to execute the next iteration
of the loop while skipping the rest of the code
inside the loop for the current iteration only, i.e.
when the continue statement is executed in the
loop, the code inside the loop following the
continue statement will be skipped for the current
iteration and the next iteration of the loop will
begin.
# Program to show the use of continue statement inside loops
print("The end")
Python pass statement
•The pass statement does not do anything.
•It is used with if statement or inside a loop to represent no
operation.
•In Python programming, the pass statement is a null
statement. The difference between a comment and a pass
statement in Python is that while the interpreter ignores a
comment entirely, pass is not ignored.
•However, nothing happens when the pass is executed. It
results in no operation (NOP).
•Suppose we have a loop or a function that is not
implemented yet, but we want to implement it in
the future. They cannot have an empty body. The
interpreter would give an error. So, we use the pass
statement to construct a body that does nothing.
Python Assert Statement
•The assert statement is useful to check if a
particular condition is fulfilled or not.
•Assertions are simply boolean expressions that
check if the conditions return true or not. If it is
true, the program does nothing and moves to the
next line of code. However, if it's false, the program
stops and throws an error.
•It is also a debugging tool as it halts the program as
soon as an error occurs and displays it.
•Syntax for using Assert in Python:
assert <condition>
assert <condition>,<error message>
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)
mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark1:",avg(mark1))
Python return statement
• A return statement is used to end the execution of the function call and
“returns” the result to the caller.
Syntax:
def fun():
statements
.
.
return [expression]
Example:
def cube(x):
r=x**3
return r
# Python program to
# demonstrate return statement
def add(a, b):
def is_true(a):
# returning boolean of a
return bool(a)
# calling function
res = add(2, 3)
print("Result of add function is {}".format(res))
res = is_true(2<5)
print("\nResult of is_true function is {}".format(res))
Functions
•In Python, a function is a group of related statements that
performs a specific task.
•Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
•Function definition that consists of the following
components.
•Keyword def that marks the start of the function header.
•A function name to uniquely identify the function.
Function naming follows the same rules of writing
identifiers in Python.
•Parameters (arguments) through which we pass values to
a function. They are optional.
•A colon (:) to mark the end of the function header.
•Optional documentation string (docstring) to describe
what the function does.
•One or more valid python statements that make up the
function body. Statements must have the same
indentation level (usually 4 spaces).
•An optional return statement to return a value from the
function.
Calling a function in python
• Once we have defined a function, we can call it
from another function, program, or even the
Python prompt.
•To call a function we simply type the function name
with appropriate parameters.
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
greet(‘XYZ')
•Note: In python, the function definition should
always be present before the function call.
Otherwise, we will get an error.
Returning results from a function
• We can return the result or output from the function using return
statement in the body of the function.
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
Returning Multiple Values from a function
# A Python program to return multiple
# values from a method using tuple
Value of my list is
OUTPUT changed after
function call
Address is same
•In python Integers, floats , strings and tuples are
immutable. Their data cannot be modified, when
we try to change the value, a new object is created
with a modified value.
•Lists and dictionaries are mutable, when we change
the data the same object gets modified and new
object is not created.
FUNCTION ARGUMENTS
add_numbers(2, 3)
• In the above example, the function add_numbers() takes two
parameters: a and b.
add_numbers(2, 3)
• Here, add_numbers(2, 3) specifies that parameters a and b will get
values 2 and 3 respectively.
• When a function is defined, it may have some parameters. These
parameters are useful to receive values from outside of the function.
They are called 'formal arguments'.
• When we call the function, we should pass data or values to the
function. These values are called 'actual arguments'.
• In the following code, 'a' and 'b' are formal arguments and 'x' and 'y'
are actual arguments.
In this code,
argument ‘b’
has given a default
value.
ie (b=90)
OUTPUT
def find_sum(*numbers):
result = 0
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# Driver code
myFun(first=‘hello', mid=‘welcome to', last=‘Hubli')
def fun(value,*val):
print('formal arguments=',value) def fun(value,*val):
print('formal arguments=',value)
for i in val: for i in val:
print(i) print(i)
fun(5,10,20)
fun(5,10,20) fun(10)
Local and Global Variables
myfunction()
print(a)
Output
Global Variables
•These are those which are defined outside any
function and which are accessible throughout the
program, i.e., inside and outside of every function.
a=1 #this is global variable
def myfunction():
b=2
print('a=', a)#display global variable
print('b=',b)#display local variable
myfunction()
print(a)
print(b)
Output
a=1 #this is global variable
def myfunction():
a=2
print('a=', a)#display global variable
myfunction()
print('a=', a)
Output
The Global Keyword
myfunction()
print('a=', a)
Output
Passing a Group of Elements to a Function
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
#recursive function to calculate factorial
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result
For i in range(1,11):
print(“Factorial of {} is {}”.format(I,factorial(i)))
•Every recursive function must have a base condition
that stops the recursion or else the function calls
itself infinitely.
•The Python interpreter limits the depths of
recursion to help avoid infinite recursions, resulting
in stack overflows.
# lambda call
greet_user(‘XYZ')
def da(basic):
da = basic *80/100
return da
def hra(basic):
hra=basic*15/100
return hra
def pf(basic):
pf=basic *12/100
return pf
def itax(gross):
tax =gross*0.1
return tax
# using employee module to calculate gross and net salaries of an employee
from employee import *
# calculate net_salary
net = gross - pf (basic)-itax (gross)
print("Your net salary: {:10.2f}'. format (net))