Python
Programming
1
© Ms. Sandra & Ms. Anina | Python Programming
What is
Python?
★ Python is an interpreted, object-oriented, high-level
programming language
★ Python is Open Source. It freely usable and distributable
★ Python provides a big set of built-in libraries for Rapid
Application Development of different types of
applications
○ GUI Development
○ Web Development
○ Game Development
○ Scientific Development
○ Data Science and Visualization
○ Machine Learning etc. 2
© Ms. Sandra & Ms. Anina | Python
History of
Python
● Created by Guido van Rossum and first released in
1991
● Python 2.0 was released in 2000
● Python 3.0 was released in 2008
● Current version is 3.8.1
● Downloadable from [Link]
3
© Ms. Sandra & Ms. Anina | Python
4
© Ms. Sandra & Ms. Anina | Python
Using
Anaconda IDEsource IDE for Windows, Linux, Mac OS X
● Anaconda is an open
● It is used for Data Science and Machine Learning using
Python/R/Julia etc.
● Download and install it from [Link]
● It provides online notebook called Jupyter Notebook to
write the program code and prepare notes
simultaneously
5
© Ms. Sandra & Ms. Anina | Python
6
© Ms. Sandra & Ms. Anina | Python
Clic
k
Her
e
7
© Ms. Sandra & Ms. Anina | Python
Click
Here to
New
NoteBoo
k
8
© Ms. Sandra & Ms. Anina | Python
Rename
to
Notebook
name
Cell to write program code
Press Shift+Enter to Execute the
code
9
© Ms. Sandra & Ms. Anina | Python
How to start Python
Programming?
Every program is divided in three
parts
● Input
● Process
● Output
For every process Python provides
● Functions e.g. input(), print()
● Operators e.g. + - * /
● Statements e.g. if, while, for
10
© Ms. Sandra & Ms. Anina | Python
What are the
variables?
A name given to some memory location to store and retrieve
some data is called as variable.
e.g.
name="Amit"
empid=1234
salary=56000
11
© Ms. Sandra & Ms. Anina | Python
Variable
naming rules
● A variable name can have alphabet (a-z, A-Z), digits (0-9) and
underscore only
● Can never start with the digit
● Can be upto any length
● Case sensitive
12
© Ms. Sandra & Ms. Anina | Python
How to declare
variables?
● We can declare the variables wherever we need them and no
data type required
● Python is dynamic type language. It automatically identifies type
of data in it
● Use type() function to see the data type of some variable
13
© Ms. Sandra & Ms. Anina | Python
Some Important
Points
● Python do not have concept of characters
● Python have the strings
● Strings can be enclosed in single quote, double quote or triple
quote
● Use # to define the comments
© Ms. Sandra & Ms. Anina | Python 14
Assigning values to the
variables
Python allows different ways to assign values to the
variables
● Single variable - Single value
● Single Variable - Multiple values
● Multiple variables - Same value
● Multiple variables - Different values
© Ms. Sandra & Ms. Anina | Python 15
© Ms. Sandra & Ms. Anina | Python 16
Formatting Output Data
in Python
Python provides print() function with different formats to format
the data
● Using comma operator
● Using format specifiers e.g. %d, %f, %s
● Using placeholders {} with format() function
© Ms. Sandra & Ms. Anina | Python 17
How to perform type
conversion?
Python provides type conversion from one type of data to
another type of data using conversion functions
● int() convert to integer data
● float() convert to floating data
● str() convert to string data
● bool() convert a number to
boolean
© Ms. Sandra & Ms. Anina | Python 18
How to input data
from user?
● Use input() function to input some data from user
● It always returns string type data only
● To convert string type data to numeric data using int() or float()
functions
Syntax 1
variable=input()
Syntax 2
variable=input("message")
© Ms. Sandra & Ms. Anina | Python 19
Example using
Syntax 1input a number and show
Problem: WAP to
square of it
© Ms. Sandra & Ms. Anina | Python 20
Example using
Syntax 2input a number and show
Problem: WAP to
square of it
© Ms. Sandra & Ms. Anina | Python 21
Operators in
Python
● Arithmetic Operators
● Relational Operators
● Logical Operators
● Bitwise Operators
● Assignment Operators
Note: Some more operators to be discussed later
© Ms. Sandra & Ms. Anina | Python 22
Arithmetic
Operators
● + addition
● - subtraction
● * multiplication
● / division (floating)
● / / division (integer)
● % remainder or
modulus
● * * power
© Ms. Sandra & Ms. Anina | Python 23
Relational
Operators
● == Equals to
● != Not equals to
● > Greater than
● >= Greater than or equals
to
● < Less than
● <= Less than or equals to
Compares two values and returns True or False
only
© Ms. Sandra & Ms. Anina | Python 24
Logical
Operators
● and
● or
● not
Used to combine two conditions or negate result of a condition
Example: WAP to detect a year to be leap year
Note: A year divisible by 4 and not divisible by 100 or divisible by 400 is
called as leap year
© Ms. Sandra & Ms. Anina | Python 25
Truth table of & Truth table of | Truth table of ^
Bitwise 0 0 = 0 0 0 = 0 0 0 = 0
Operators
● & Bitwise And
0
1
1
0
=
=
0
0
0
1
1
0
=
=
1
1
0
1
1
0
=
=
1
1
1 1 = 1 1 1 = 1 1 1 = 0
● | Bitwise Or
● ^ Bitwise XOR
● ~ Bitwise Not
● << Left Shift
● >> Right Shift
Note:
Use bin() function to
convert a number from
decimal to binary
© Ms. Sandra & Ms. Anina | Python 26
Assignment
Operators
Used to assign value to the
variables
Operator Example Equivalent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
© Ms. Sandra & Ms. Anina | Python 27
Decision
Making
© Ms. Sandra & Ms. Anina | Python 28
Conditional
Statement
Python provides if statement to check some condition with different
syntaxes
Syntax 1 Syntax 2 Syntax 3
if condition: if condition: if condition:
statements statements statements
else: elif condition:
statements statements
else:
statements
Statements must be indented using four
spaces.
© Ms. Sandra & Ms. Anina | Python 29
Exampl
e
WAP1 to input a number and check it to be even
or odd.
© Ms. Sandra & Ms. Anina | Python 30
Example 2
WAP to input three numbers and show the
biggest one
© Ms. Sandra & Ms. Anina | Python 31
Example 3 : Using map()
function
WAP to input three numbers and show the
biggest one
© Ms. Sandra & Ms. Anina | Python 32
Assignme
nt 1input name and marks of PCM for a student, calculate
WAP to
average and show the grade of that student based on following
rules
● A+ for 80 and above
● A for 70 and above
● B+ for 60 and above
● B for 50 and above
● F for others
Output format is: Grade of <name> is <grade>
© Ms. Sandra & Ms. Anina | Python 33
Soluti
on
© Ms. Sandra & Ms. Anina | Python 34
Assignme WAP to input a character and check it to be an
alphabet, digit or special character
nt 2
© Ms. Sandra & Ms. Anina | Python 35
Assignme
nt 3
WAP to input a number and check it to be even or odd using bitwise
operation
© Ms. Sandra & Ms. Anina | Python 36
Using
Loops
37
3
© Ms. Sandra & Ms. Anina | Python 7
Looping
Statements
Python provides two kinds of looping
statements
● while loop
● for loop
© Ms. Sandra & Ms. Anina | Python 38
Using while
loop
Syntax
initialization
while
condition:
statement
s
updation
else:
statements
© Ms. Sandra & Ms. Anina | Python 39
Exampl WAP to input a number and print table of that
number in following format
e 1 19 x 1 =
19
19 x 2 =
38
…
19 x 10 =
190
© Ms. Sandra & Ms. Anina | Python 40
Exampl WAP to print the
following
e2
100 90 80 … . 10
© Ms. Sandra & Ms. Anina | Python 41
Assignments on
while
● WAP toloop
input a number and print sum of its
digits
● WAP to input a number and reverse print it
● WAP to input a number and check it to be
palindrome
© Ms. Sandra & Ms. Anina | Python 42
Using break
statement
The statement used to come out of loop.
Example
WAP to input a number and check it to be prime
number.
© Ms. Sandra & Ms. Anina | Python 43
Assignment on break
statement
● WAP to input two numbers and print all prime numbers
in range
44
© Ms. Sandra & Ms. Anina | Python
Infinite
loop
A loop which cannot terminate itself is called as infinite loop. Use
break to come out of such loops.
Syntax
while
True:
statement
s if
condition:
break
45
© Ms. Sandra & Ms. Anina | Python
Example on infinite loop
WAP to input as many numbers as user wants till -999 get pressed
and show sum of all given values.
46
© Ms. Sandra & Ms. Anina | Python
String
Handling
● Strings are enclosed in single quote, double quote or triple
quote
○ s1='Hello'
○ s2="Hello"
○ s3='''Hello'''
○ s4="""Hello"""
● Every string is an object of str class
● Use dir() function to see list of all possible functions on
strings
○ dir(str)
○ dir(s1)
● Use help() function to see syntax and usage of given
function
© Ms. Sandra & Ms. Anina | Python 47
○ help([Link])
How string
manages
● Every string isdata?
made of certain characters
● Each character has an index number from 0 from
front-side
● Each character has an index number from -1 from
back-side
● Use len() function to get length of the string
© Ms. Sandra & Ms. Anina | Python 48
Exam WAP to input a string and show the count of
alphabets, digits and special characters using while
ple loop
49
© Ms. Sandra & Ms. Anina | Python 4
5
Using for
loop
It works with collections to take one value at a time and perform
some action
without knowing size of collection and without using indexing.
Syntax
for variable in collectionname:
statements
© Ms. Sandra & Ms. Anina | Python 50
Exam WAP to input a string and show the count of
alphabets, digits and special characters using for
ple loop.
© Ms. Sandra & Ms. Anina | Python 51
Exam WAP to input a number and table of that number
using for
ple loop
© Ms. Sandra & Ms. Anina | Python 52
String
Handling
© Ms. Sandra & Ms. Anina | Python 53
Basic string
functions
● upper()
● lower()
convert to upper
case convert to
● title() lower case
● capitalize() convert first letter to
caps of each word to
caps case
● swapcase() toggle
returns True if
● isalpha() alphabet returns
● isdigit() True if digit
● isupper() returns True if upper case
● islower() string returns True if lower
● istitle() case string returns True if
● strip() string in title case remove
● split() blank space from both sides
© Ms. ● join()
Sandra & Ms. Aninabreak the string into list of
| Python 54
Exam
ple
Show usage of the
basic string
functions
© Ms. Sandra & Ms. Anina | Python 55
Exam WAP to input a string and show the count of
alphabets, digits and special characters using for loop
ple and string functions.
© Ms. Sandra & Ms. Anina | Python 56
More string
functions
● startswith() returns True if string starts with given
● endswith() string returns True if string ends with
● find() given string returns index of search
● rfind() string from left side returns index of
● replace() search string from right side replace
● count() the search string with given string
returns count of occurrences of given
string
© Ms. Sandra & Ms. Anina | Python 57
Exam
ple
Input an email id and validate it.
● Email ID must have only one @
● At least one dot (.)
● Minimum size 5 and Maximum
size 50
● Should not start with @ or dot (.)
● Should not end with @ or dot (.)
© Ms. Sandra & Ms. Anina | Python 58
Soluti
on
© Ms. Sandra & Ms. Anina | Python 59
Using membership
operators
The operators used to check where some data is available inside
the given collection and returns True or False.
● in
● not in
© Ms. Sandra & Ms. Anina | Python 60
Example
WAP to input name of a person. It the name contains Sharma then
replace it with Verma.
© Ms. Sandra & Ms. Anina | Python 61
What is
slicing?
● When we extract some information from a collection is called as
slicing.
● String being a collection of characters also provides the feature
of slicing.
Syntax
string[lowerbound:upperbound:step]
● Upper bound is not included
● If lower bound not given, takes 0
● If upper bound not given, takes length of the string
● Step value is 1 by default 62
© Ms. Sandra & Ms. Anina | Python
Examples of
slicing
63
© Ms. Sandra & Ms. Anina | Python 63
Assignm
ent
WAP to input a string and check it to be
palindrome
64
64
© Ms. Sandra & Ms. Anina | Python
Collectio
ns
65
65
© Ms. Sandra & Ms. Anina | Python
Working with
collections
Collections are special types which are used to store
multiple values.
Python provides four types of collections
● Tuple
● List
● Set
● Dictionary
66
66
© Ms. Sandra & Ms. Anina | Python
Creating and
using
● Tuple is tuples
a collection which is ordered and unchangeable
● Tuple do not allow to add, update or delete an item
● Tuples are created using rounded brackets ()
● Use len() to get length of items in tuple
● Use index number to fetch specific item from tuple very similar
to strings
● Use slicing to read group of items very similar to strings
● Use count() function to count number of occurrences of an item
67
67
© Ms. Sandra & Ms. Anina | Python
Exam
ple
Using
Tuple
68
68
© Ms. Sandra & Ms. Anina | Python
Creating and
using
● List is a list
collection having ordered data which is
changeable
● We can add, update and delete items from list
● Use square brackets [] to create a list
● Use len() function to get length of list
● Use index number to fetch specific item
● Use slicing to get range of items
● Use del statement to delete an item
69
69
© Ms. Sandra & Ms. Anina | Python
Example 1: List
with data
70
70
© Ms. Sandra & Ms. Anina | Python
Example 2: Dynamic List
WAP to input 5 numbers from user and show sum of given
numbers.
71
71
© Ms. Sandra & Ms. Anina | Python
Creating and
using set
● A collection which contains unique data only
● It is unordered and unindexed
● Use curly braces {} to create a set
● Methods
○ add()
○ update() -- use a list to update items in set
○ remove() -- raises an exception is item not found
○ discard() -- does not raise any exception if item not
found
● Use del keyword to delete a set
● Use list() function to convert set into list
● Use set() function to convert a list or tuple into set and remove
duplicates
72
72
© Ms. Sandra & Ms. Anina | Python
Examples
on set
73
73
© Ms. Sandra & Ms. Anina | Python
Creating and using
dictionary
● A collection used to manage data in key:value pairs
● It is unordered, changeable and indexed using the key
● Use curly braces {} to create a dictionary with key:value
combination
● Functions
○ items()
○ keys()
○ values()
● Use del keyword to delete and item
74
74
© Ms. Sandra & Ms. Anina | Python
Example of
Dictionary
75
75
© Ms. Sandra & Ms. Anina | Python
Dynamic
Dictionary
76
76
© Ms. Sandra & Ms. Anina | Python
Functio
ns
77
77
© Ms. Sandra & Ms. Anina | Python
Types of library
functions
Library functions are again of three types
● Built-in functions
● Object functions
● Module functions
Built-in functions are ready to use functions available by default
e.g. print()
Object functions are associated with some type of data e.g.
[Link]()
Module function are provided in some re-usable python files
called as modules to classify them from other functions. Python 78
78
© Ms. Sandra & Ms. Anina | Python
How to use functions
from a any
Before using module?
function of a module we need to import that
module in our program using import keyword.
e.g.
● import math
● import sys
● import os
Now we can see list of possible functions inside the module using
dir() built-in function
79
79
© Ms. Sandra & Ms. Anina | Python
Using math
module
It provides all required mathematical functions and
values.
Some of them are
● factorial( returns factorial of given
n) number returns square root of
● sqrt(n) given number returns n to the
● pow(n,p) power p
● sin(n) Return the sine of x (measured in
● cos() radians) Return the cosine of x
● tan() (measured in radians) Return the
● pi tangent of x (measured in radians)
Returns value of pi
80
80
© Ms. Sandra & Ms. Anina | Python
Examples of math
functions
81
81
© Ms. Sandra & Ms. Anina | Python
How to use the module functions
without module name?
We can also use the module functions without using module name
again and again.
Here we need to import the one, more or all the functions of
that module using from and import keyword combination.
Using * to import all the functions of a module.
● from math import factorial
● from math import factorial,sqrt
● from math import *
82
82
© Ms. Sandra & Ms. Anina | Python
Example of math module with
from keyword
83
83
© Ms. Sandra & Ms. Anina | Python
How to give an alias name
tocanthe
We module?
also create an alias or shortname to the module using as
keyword along with import keyword
e.g.
84
84
© Ms. Sandra & Ms. Anina | Python
Using datetime
module
● Use datetime class from datetime module to work on current
date or user defined dates
● Use now() function to get current date and time
● Use strftime() to format the date using format specifiers
85
85
© Ms. Sandra & Ms. Anina | Python
Do we have all the Python
module
● No, not all installed?
modules are always available in your machine.
● Few required modules are installed by default but advanced
and third party modules are installed on demand.
● Such modules are managed by Python team at
[Link] as package
● Some of required packages for Data Science and Machine
Learning are
○ numpy
○ pandas
○ matplotlib
86
86
© Ms. Sandra & Ms. Anina | Python
How to install a
package?
● If some module is not available then we need to install its
package using
conda or pip or pip3 commands
● Suppose you want to use MongoDb database with Python, use
need pymongo module. Now you need to install pymongo
package
○ condathen you can import
install pymongo module
for Anaconda
pymongo for Simple
○ pip install pymongo Python for
○ pip3 install Simple Python
pymongo
87
87
© Ms. Sandra & Ms. Anina | Python
How to create user
defined functions?
Python provides
functions.
def keyword to define the user defined
Syntax
def
functioname(argumentl
ist): statements
If you want to return some
value then use return
statement
Syntax
def
88
88
© functioname(argumentl
Ms. Sandra & Ms. Anina | Python
Example 1: without using
return statement
Create a function factorial which takes a number and prints
factorial of given number
89
89
© Ms. Sandra & Ms. Anina | Python
Example 2: using return
statement
Create a function factorial which takes a number and returns
factorial of given number
90
90
© Ms. Sandra & Ms. Anina | Python
How we can pass default values to
the arguments?
We can also pass some default value to the arguments. If no value
is pass for such arguments then default value is used.
Example
Create a function are which length and width and prints area of
rectangle. Define default length as 5 and default width as 6.
91
91
© Ms. Sandra & Ms. Anina | Python
How to we can optional
arguments?
We can also create optional arguments. We can work take the
decision based on given arguments using argument names.
Use the special value called None with such arguments.
92
92
© Ms. Sandra & Ms. Anina | Python
Example:
Create a function area() which can take four arguments as side,
length,width and radius. If side is given show area of square. If length
and width are given show area of rectangle. If radius is given show area
of circle.
93
93
© Ms. Sandra & Ms. Anina | Python
How to pass variable number
of can
We arguments?
also create the functions which can take variable number
of arguments and perform given action using * with the argument
name.
Example: Create a function sum() which takes few numbers and
returns sum of all given numbers.
94
94
© Ms. Sandra & Ms. Anina | Python
Passing variable number of
arguments
We with
can also pass variable names
number of arguments along with their
names using
* * with the argument name.
Here we can read the argument name and value.
95
95
© Ms. Sandra & Ms. Anina | Python
Another
example
Create a function area() which can take any number of arguments
with their names. If side is given show area of square. If radius is
given show area of circle. If length and width is given show area of
rectangle.
96
96
© Ms. Sandra & Ms. Anina | Python
Returning multiple values
fromfunctions
Python a function
allow to return multiple values with return
statement
Example: Create a function multiresult() which takes a number and
returns square and cube of that number.
97
97
© Ms. Sandra & Ms. Anina | Python
Creating recursive
functions
● When a process repeats itself, it is called as recursive
function.
● The functions which implement such processes are called as
recursive functions
● Such functions use the stack to hold the intermediate values
Examples
● Factorial of a number
○ n!=n*(n-1)!
● Fibonacci series
○ 0 1 1 2 3 5 8 ……
98
98
© Ms. Sandra & Ms. Anina | Python
Factorial of a number:
Recursive function
99
99
© Ms. Sandra & Ms. Anina | Python
Fibonacci Series:
Recursive function
10
100
© Ms. Sandra & Ms. Anina | Python 0
Using pass
statement
Sometimes we need to create a function but do not want to
write the statements for it just now, then we can use the
pass statement
Syntax
def functioname(argumentlist):
pass
10
101
© Ms. Sandra & Ms. Anina | Python 1
Lambda
Functions
10
102
© Ms. Sandra & Ms. Anina | Python 2
Creating and using
Lambda Functions
● Lambda functions are anonymous functions
● Can take one or more arguments and return only
one result
● Do not require return keyword
● Use lambda keyword to create the lambda functions
Syntax
lambda arguments:expression
10
103
© Ms. Sandra & Ms. Anina | Python 3
Using lambda function
within functions
10
104
© Ms. Sandra & Ms. Anina | Python 4
Filtering data using
lambda
Use filter() function to filter some data from a list based on
True/False
Example: Show only even numbers from given numbers in
some list
10
105
© Ms. Sandra & Ms. Anina | Python 5
Exception
Handling
10
106
© Ms. Sandra & Ms. Anina | Python 6
What is
exception?
● An exception is a runtime error which can occur due to data
wrong data input, unavailability of resource during execution
of some program
● Python provides four keywords to handle runtime errors
○ try
○ except
○ finally
○ raise
● Here try-except is used to execute some code block and trap the
errors
● The finally is used to always execute some code irrespective of
©
error
Ms. Sandra & Ms. Anina | Python
10
107
7
Example of
exception
10
108
© Ms. Sandra & Ms. Anina | Python 8
Handling
Exception
10
109
© Ms. Sandra & Ms. Anina | Python 9
Raising an
exception
11
110
© Ms. Sandra & Ms. Anina | Python 0