APSSDC
Certificate Training Program
Programming with Python
Course outline
(i) Introduction to Python
(ii) Control Statements
(iii) Data Structures
(iv) Functions
(v) File Handling
(vi) Python Modules and Packages
(vii) Python – Object oriented Concepts
(viii) Exception Handling
(ix) Regular Expressions
(x) Database
(xi) Multithreading
(xii) Sending email
Introduction to Python
History of Python
Milestone Description
Late 1980s Python development initiated by Guido van Rossum.
Python 0.9.0: First official release, with basic features such as functions and
Feb 1991
modules
Jan 1994 Python 1.0: Introduction of lambda functions, establishing Python.
Oct 2000 Python 2.0: Added list comprehensions, garbage collection, and Unicode support.
Dec 2008 Python 3.0: Major simplification, causing compatibility issues with Python 2.
Subsequent Series of Python 3.x versions refining and enhancing the language.
Jan 2020 Python 2 End of Life, encouraging the transition to Python 3.
Ongoing Python 3's growth in popularity and adoption in various fields.
Oct 2023 latest release of Python is Python 3.12.0
Features of Python
Readability
and
simplicity
Cross-
Versatility
platform
Python
features
Open
Source and Interpreted
Communit language
y driven
Extensive
Library
Features of Python
Object
oriented
and
functional
Garbage Interopera
Collection bility
Python
features
Large eco
Mult- system of
threading third party
libraries
Exception
handling
ALGOL • Indentation
• simplicity
ABC • readability
• Modular approach
Modula-3 • Exception handling
• functions
C • low level facilities
• regular expressions
Perl • text processing
• object oriented concepts
C++, java • garbage collection
• lambda functions
LISP • dynamic typing
Haskell • list comprehensions and generators
Python Character set
• Character set is the set of valid characters that a language can
recognize.
• Python has the following character sets
Letter A to Z, a to z
Digits 0–9
Special symbols -, +, *, /, &, ^,%,#,(, etc.
White spaces Blank space, tab, Carriage return, new line
Python Tokens
Python
tokens
Keywords Identifiers Literals operators delimiters
Keywords
and del for is raise False
assert elif from lambda return True
break else global not try None
class except if or while
continue exec import pass with (2.5)
def finally in print yield
Identifiers
• An identifier is a name used to identify a variable, function, class,
module, or other object.
• characters to be used: letters(A-Z,a-z), digits (0 – 9), underscore ( _ )
• starts with a letter (A to Z or a to z) or an underscore (_)
• keyword should not be used as identifier
• no other special symbols should be used in identifiers
• Python is case-sensitive.
Literals / constants in python
Decimal
Integer Octal
Numeric hexadecimal
Fractional
Literals
Floating or real
exponential
Single line
String
Multiline
boolean
Literals / constants in python
String literals
Single line strings Multi line
String literals that are a) Adding backslash at
enclosed within single b) Using triple quotes
the end of every line-
quotes (‘’) are known as
single-line strings.
string that goes on for Triple quotes at the beginning and
multiple lines is a multi- end of the string literally will allow us
line string. to create a multi-line string in Python
Ex: ‘welcome to sjgc’
easily!
Ex:’ Welcome to\ """Welcome to silver
Silver jubilee\ jubilee
Govt .college’ Govt. college"""
It contains digits
Literals / constants in from 0 to 9. The
base for decimal
python Decimal values is 10.
Ex: 3412, -90, 12
It contains only two digits- 0 and 1. The base
Binary for binary values is 2 and prefixed with “0b”.
Ex:0b10101
Integer
It contains the digits from 0 to 7. The
base for octal values is 8. In Python, such
values are prefixed with “0o”.
Numerical
Octal
Literals
Ex: 0o234,0o777
It contains digits from 0 to 9 and
alphabets from A to F.
Hexadecimal
Ex: 0x3fff
Fractional Ex : 34.4444, -0.344
Floating point
Exponential Ex: 34.4E-4, 43e12
Literals / constants in python
None type
Boolean literal
literals
True False None
Operators in Python
Arithmetic operators
Comparison operators (or)
relational operators
Logical operators
Operators
Identity operators
Membership operators
Bitwise operators
Assignment operators
Special operators
Arithmetic operators
Operator Name Example Description
+ Addition x+y Adds x and y
- Subtraction x-y Subtracts y from x
* Multiplication x*y Multiplies x and y
/ Division x/y Gives quotient after
dividing x by y
% Modulus x%y Gives remainder after
dividing x by y
** Exponentiation x ** y x to the power of y
// Floor division x // y Gives integer quotient.
Discards the fractional
part in the quotient
Comparison operators in Python
• These operators compare the value of the left operand and the right
operand and return either True or False. Let x=10,y=20
Operator Name Example Result
== Equal x == y False
!= Not equal x != y True
> Greater than x>y False
< Less than x<y True
>= Greater than or equal to x >= y False
<= Less than or equal to x <= y True
Let a=10, b=20
Python Logical Operators
Operator Description Example
and Returns True if both statements are x < 5 and x < 10
true
or Returns True if one of the statements is x < 5 or x < 4
true
not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true
Python Identity Operators
Operator Description Example
is Returns True if both x is y
variables are the same object
is not Returns True if both x is not y
variables are not the same
object
Python Membership Operators
Operator Description Example
in Returns True if a sequence with x in y
the specified value is present in
the object
not in Returns True if a sequence with x not in y
the specified value is not present
in the object
Python Bitwise Operators
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left Shift left by pushing zeros in from the right and let the leftmost bits fall off
shift
>> Signed right Shift right by pushing copies of the leftmost bit in from the left, and let the
shift rightmost bits fall off
Truth tables
b1 b2 b1 & b2 b1 | b2 b1 ^ b2 ~ b1
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
Bitwise and (&) operator
A 20 00010100
B 24 00011000
A&B 00010000
Bitwise and (&) operator
A 20 00010100
B 24 00011000
A&B 16 00010000
Bitwise or (|) operator
A 20 00010100
B 24 00011000
A|B 00011100
Bitwise or (|) operator
A 20 00010100
B 24 00011000
A|B 28 00011100
Bitwise xor (^) operator
A 20 00010100
B 24 00011000
A ^B 00001100
Bitwise xor (^) operator
A 20 00010100
B 24 00011000
A ^B 12 00001100
Bitwise Not (~)
A=20 0 0 0 1 0 1 0 0
A=-21 1 1 1 0 1 0 1 1
1 1 1 0 1 0 1 1
0 0 0 1 0 1 0 0
1
- 0 0 0 1 0 1 0 1
Bitwise Left shift (<<) operator
A=19
0 0 0 1 0 0 1 1
0 0 1 0 0 1 1
0 1 0 0 1 1 0 0
Let B=2
A<<B ?
Bitwise Left shift (<<) operator
A<<B Shift all the bits of A to the left B times
0 0 0 1 0 0 1 1
Shift the bits to the left 1st time
0 0 0 1 0 0 1 1
Shift the bits to the left 2nd time
0 0 0 1 0 0 1 1
0 1 0 0 1 1 0 0
A <<B = A * 2^B
Bitwise Right shift (>>) operator
A>>B Shift all the bits of A to the right B times
0 0 0 1 0 0 1 1
Shift the bits to the right 2nd time
0 0 0 0 0 1 0 0
Bitwise Right shift (>>) operator
A >> B = A//(2^B)
A=19, B=2
A>>B
Assignment operators
Operator meaning example Equivalent statement
= assignment
+= add and assign a+=b a=a+b
-= subtract and assign a-=b a=a-b
*= multiply and assign a*=b a=a*b
/= divide and assign a/=b a=a/b
//= floor division and a//=b a=a//b
assign
**= power and assign a**=b a=a**b
Assignment operators
Operator meaning example Equivalent
statement
&= Bitwise and and assign a&=b a=a&b
|= Bitwise or and assign a|=b a=a|b
^= Bitwise xor and assign a^=b a=a^b
<<= Bitwise left shift and a<<=b a=a<<b
assign
>>= Bitwise right shift and a>>=b a=a>>b
assign
Punctuators in python
• Theses are symbols that are used in programming languages to
organize structures, statements, expressions etc.
• Most commonly used punctuators in Python are:
‘ “ # \ () {} [] @ , : . =
Lines and Indentation
• Python does not use braces to indicate blocks of code for class and
function definitions or flow control.
• Blocks of code are denoted by line indentation, which is rigidly
enforced.
• The number of spaces in the indentation is variable, but all
statements within the block must be indented the same amount.
Lines and Indentation
C language style for a block Python style for a block
if(a>0) if (a>0):
{ d=b*b-4*a*c
d=b*b-4*a*c ; e=b*b+4*a*c
e=b*b+4*a*c ; f=4*a*c
f=4*a*c ; x=y
}
x=y;
Lines and Indentation
• In Python all the continuous lines indented with same number of spaces would form
a block.
Multi-Line Statements:
• Statements in Python typically end with a new line.
• Python does, however, allow the use of the line continuation character (\) to denote
that the line should continue. For example −
total = item_one + \
item_two + \
item_three
Python data types
Text Type: str
Numeric Types: int, float, complex
Sequence list, tuple, range
Types:
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", frozenset
"cherry"})
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
Escape Characters:
In String literals we can use esacpe characters to associate a special
meaning.
The following are various important escape characters in Python
1) \n ===>New Line
2) \t ===>Horizontal tab
3) \’ ===>Single quote
4) \“ ===>Double quote
5)\\ ===>Back slash
Few Python built-in functions
1.type()
to check the type of variable
2. id()
to get address of object
3. print()
to print the value
4.input()
to read the input from the standard input
print() statement
• Python print() function prints the message to the screen or any other
standard output device.
Syntax:
print(value(s), sep= ' ', end = '\n', file=file, flush=flush)
print() statement
Parameters:
• value(s): Any value, and as many as you like. Will be converted to a
string before printed
• sep=’separator’ : (Optional) Specify how to separate the objects, if
there is more than one. Default separator is space(‘ ‘)
• end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
• file : (Optional) Speicifies where to write the output. Default is
sys.stdout (standard output i.e. terminal)
• flush : (Optional) A Boolean, specifying if the output is flushed (True)
or buffered (False). Default: False
Conditional statements in Python
Conditional statements in Python are used to make decisions in your
code based on whether certain conditions are true or false. they are
1. if
2. if – else
3. if – elif –else
4. nested statements
Conditional statements in Python
if Statement:
• The if statement is used to test a single condition or expression. If the
condition is true, the code block inside the if statement is executed.
Syntax:
if condition: Example:
x = 10
statement1 if x > 5:
print("x is greater than 5")
statement2
…
next statement
Conditional statements in Python
if - else Statement:
• The if-else statement allows you to specify two code blocks: one to execute if
the condition is true, and another to execute if the condition is false..
Syntax:
if condition:
x=3
statements if x > 5:
else: print("x is greater than 5")
else:
statements print("x is not greater than 5")
…
next statement
Conditional statements in Python
if – elif- else Statement:
• The if-elif-else statement is used when you have multiple conditions to test, and you want to execute different
code blocks based on which condition is true.
• elif stands for "else if." You can have multiple elif blocks in addition to the if and else blocks.
syntax:
if condition1: Example:
statements
…… x=7
elif condition2: if x > 10:
print("x is greater than 10")
statements
elif x > 5:
… print("x is greater than 5 but not
else: greater than 10")
statements else:
….. print("x is not greater than 5")
next statement
Conditional statements in Python
nested statements
• A compound conditional statement can be represented with nested statement. If it is required to test multiple
conditions to execute a block of statements, then we use nested if statements.
• syntax:
if condition1 and condition2 and condition3: Example:
statements
…….
next statement
if condition1:
if condition2:
if condition3:
statements
…….
next statement
Ternary operation in python
• In Python, there is no specific "conditional operator" like the ternary operator (? :) in
some other programming languages.
• However, Python provides a shorthand way of expressing conditional expressions
using the if-else statement.
• This is often referred to as a "conditional expression" or "ternary-like operation" in
Python.
Syntax:
value_if_true if condition else value_if_false
Example:
x = 10
y = 20
max_value = x if x > y else y
print(max_value)
Loops in Python
• In Python, loops are control structures that allow you to repeatedly
execute a block of code as long as a certain condition is met or for a
specified number of times.
• Python supports two main types of loops:
1. for loop
2. while loop
Loops in Python
While loop:
• The while loop is used when you don't know in advance how many
iterations you need and you want to continue looping as long as a
certain condition is true.
• Here's the basic syntax of a while loop:
while condition: Example:
# Code to be executed repeatedly count = 1
while count <= 5:
print(count)
count += 1
Loops in Python
for loop:
• The for loop is used when you know the number of iterations in
advance or when you want to iterate over elements in a sequence (e.g.,
a list, tuple, string, or dictionary).
• Here's the basic syntax of a for loop:
for variable in sequence: Example:
# Code to be executed repeatedly fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Unconditional statements in Python
• break
• continue
• pass
• return
break statement
while condition:
statement1
………….
break
statements
next statement
break statement
i=1
while(True):
print(i)
if(i==10):
break
i=i+1
Continue statement
continue
Continue statement
while condition:
statement1
………….
continue continue
statements2
next statement
Pass statement
while condition:
pass
return statement
def func_name(parameters):
statements
…..
return value