PythonProgramming 2 114
PythonProgramming 2 114
3
© Prof. (Dr.) B P Sharma | Python Programming
4
© Prof. (Dr.) B P Sharma | Python Programming
Using Anaconda IDE
● Anaconda is an open source IDE for Windows, Linux, Mac OS X
● It is used for Data Science and Machine Learning using Python/R/Julia etc.
● Download and install it from https://www.anaconda.com/
● It provides online notebook called Jupyter Notebook to write the
program code and prepare notes simultaneously
5
© Prof. (Dr.) B P Sharma | Python Programming
6
© Prof. (Dr.) B P Sharma | Python Programming
Click
Here
7
© Prof. (Dr.) B P Sharma | Python Programming
Click Here
to New
NoteBook
8
© Prof. (Dr.) B P Sharma | Python Programming
Rename to
Notebook
name
9
© Prof. (Dr.) B P Sharma | Python Programming
How to start Python Programming?
Every program is divided in three parts
● Input
● Process
● Output
10
© Prof. (Dr.) B P Sharma | Python Programming
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
balance=567.89
11
© Prof. (Dr.) B P Sharma | Python Programming
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
© Prof. (Dr.) B P Sharma | Python Programming
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
© Prof. (Dr.) B P Sharma | Python Programming
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
14
© Prof. (Dr.) B P Sharma | Python Programming
Assigning values to the variables
Python allows different ways to assign values to the variables
15
© Prof. (Dr.) B P Sharma | Python Programming
© Prof. (Dr.) B P Sharma | Python Programming 16
Formatting Output Data in Python
Python provides print() function with different formats to format the data
17
© Prof. (Dr.) B P Sharma | Python Programming
How to perform type conversion?
Python provides type conversion from one type of data to another type of
data using conversion functions
18
© Prof. (Dr.) B P Sharma | Python Programming
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")
19
© Prof. (Dr.) B P Sharma | Python Programming
Example using Syntax 1
Problem: WAP to input a number and show square of it
20
© Prof. (Dr.) B P Sharma | Python Programming
Example using Syntax 2
Problem: WAP to input a number and show square of it
21
© Prof. (Dr.) B P Sharma | Python Programming
Operators in Python
● Arithmetic Operators
● Relational Operators
● Logical Operators
● Bitwise Operators
● Assignment Operators
22
© Prof. (Dr.) B P Sharma | Python Programming
Arithmetic Operators
● + addition
● - subtraction
● * multiplication
● / division (floating)
● // division (integer)
● % remainder or modulus
● ** power
23
© Prof. (Dr.) B P Sharma | Python Programming
Relational Operators
● == Equals to
● != Not equals to
● > Greater than
● >= Greater than or equals to
● < Less than
● <= Less than or equals to
24
© Prof. (Dr.) B P Sharma | Python Programming
Logical Operators
● and
● or
● not
Note: A year divisible by 4 and not divisible by 100 or divisible by 400 is called as leap
year
25
© Prof. (Dr.) B P Sharma | Python Programming
Bitwise Operators
Truth table of & Truth table of | Truth table of ^
26
© Prof. (Dr.) B P Sharma | Python Programming
Assignment Operators
Used to assign value to the variables
= 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
27
© Prof. (Dr.) B P Sharma | Python Programming
Decision Making
28
© Prof. (Dr.) B P Sharma | Python Programming
Conditional Statement
Python provides if statement to check some condition with different syntaxes
29
© Prof. (Dr.) B P Sharma | Python Programming
Example 1
WAP to input a number and check it to be even or odd.
30
© Prof. (Dr.) B P Sharma | Python Programming
Example 2
WAP to input three numbers and show the biggest one
31
© Prof. (Dr.) B P Sharma | Python Programming
Example 3 : Using map() function
WAP to input three numbers and show the biggest one
32
© Prof. (Dr.) B P Sharma | Python Programming
Assignment 1
WAP to input name and marks of PCM for a student, calculate average and
show the grade of that student based on following rules
33
© Prof. (Dr.) B P Sharma | Python Programming
Solution
34
© Prof. (Dr.) B P Sharma | Python Programming
Assignment 2 WAP to input a character and check it to be an alphabet,
digit or special character
35
© Prof. (Dr.) B P Sharma | Python Programming
Assignment 3
WAP to input a number and check it to be even or odd using bitwise operation
36
© Prof. (Dr.) B P Sharma | Python Programming
Using Loops
37
Looping Statements
Python provides two kinds of looping statements
● while loop
● for loop
38
© Prof. (Dr.) B P Sharma | Python Programming
Using while loop
Syntax
initialization
while condition:
statements
updation
[else:
statements]
39
© Prof. (Dr.) B P Sharma | Python Programming
Example 1 WAP to input a number and print table of that number in
following format
19 x 1 = 19
19 x 2 = 38
…
19 x 10 = 190
40
© Prof. (Dr.) B P Sharma | Python Programming
Example 2 WAP to print the following
100 90 80 …. 10
41
© Prof. (Dr.) B P Sharma | Python Programming
Assignments on while loop
● WAP to 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
42
© Prof. (Dr.) B P Sharma | Python Programming
Using break statement
The statement used to come out of loop.
Example
43
© Prof. (Dr.) B P Sharma | Python Programming
Assignment on break statement
● WAP to input two numbers and print all prime numbers in range
44
© Prof. (Dr.) B P Sharma | Python Programming
Infinite loop
A loop which cannot terminate itself is called as infinite loop. Use break to
come out of such loops.
Syntax
while True:
statements
if condition:
break
45
© Prof. (Dr.) B P Sharma | Python Programming
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
© Prof. (Dr.) B P Sharma | Python Programming
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
○ help(str.upper)
47
© Prof. (Dr.) B P Sharma | Python Programming
How string manages data?
● Every string is 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
48
© Prof. (Dr.) B P Sharma | Python Programming
Example WAP to input a string and show the count of alphabets, digits
and special characters using while loop
45
© Prof. (Dr.) B P Sharma | Python Programming
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
50
© Prof. (Dr.) B P Sharma | Python Programming
Example WAP to input a string and show the count of alphabets, digits
and special characters using for loop.
51
© Prof. (Dr.) B P Sharma | Python Programming
Example WAP to input a number and table of that number using for
loop
52
© Prof. (Dr.) B P Sharma | Python Programming
String Handling
53
© Prof. (Dr.) B P Sharma | Python Programming
Basic string functions
● upper() convert to upper case
● lower() convert to lower case
● title() convert first letter of each word to caps
● capitalize() convert first letter to caps
● swapcase() toggle case
● isalpha() returns True if alphabet
● isdigit() returns True if digit
● isupper() returns True if upper case string
● islower() returns True if lower case string
● istitle() returns True if string in title case
● strip() remove blank space from both sides
● split() break the string into list of words
● join() join two strings with given separator
54
© Prof. (Dr.) B P Sharma | Python Programming
Example
Show usage of the basic
string functions
55
© Prof. (Dr.) B P Sharma | Python Programming
Example WAP to input a string and show the count of alphabets, digits
and special characters using for loop and string functions.
56
© Prof. (Dr.) B P Sharma | Python Programming
More string functions
57
© Prof. (Dr.) B P Sharma | Python Programming
Example
Input an email id and validate it.
58
© Prof. (Dr.) B P Sharma | Python Programming
Solution
● in
● not in
60
© Prof. (Dr.) B P Sharma | Python Programming
Example
WAP to input name of a person. It the name contains Sharma then replace it
with Verma.
61
© Prof. (Dr.) B P Sharma | Python Programming
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]
62
© Prof. (Dr.) B P Sharma | Python Programming
Examples of slicing
63
© Prof. (Dr.) B P Sharma | Python Programming
Assignment
WAP to input a string and check it to be palindrome
64
© Prof. (Dr.) B P Sharma | Python Programming
Collections
65
© Prof. (Dr.) B P Sharma | Python Programming
Working with collections
Collections are special types which are used to store multiple values.
● Tuple
● List
● Set
● Dictionary
66
© Prof. (Dr.) B P Sharma | Python Programming
Creating and using tuples
● Tuple is 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
© Prof. (Dr.) B P Sharma | Python Programming
Example
Using Tuple
68
© Prof. (Dr.) B P Sharma | Python Programming
Creating and using list
● List is a 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
© Prof. (Dr.) B P Sharma | Python Programming
Example 1: List with data
70
© Prof. (Dr.) B P Sharma | Python Programming
Example 2: Dynamic List
WAP to input 5 numbers from user and show sum of given numbers.
71
© Prof. (Dr.) B P Sharma | Python Programming
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
© Prof. (Dr.) B P Sharma | Python Programming
Examples on set
73
© Prof. (Dr.) B P Sharma | Python Programming
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
© Prof. (Dr.) B P Sharma | Python Programming
Example of Dictionary
75
© Prof. (Dr.) B P Sharma | Python Programming
Dynamic Dictionary
76
© Prof. (Dr.) B P Sharma | Python Programming
Functions
77
© Prof. (Dr.) B P Sharma | Python Programming
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. str.upper()
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
© Prof. (Dr.) B P Sharma | Python Programming
Using math module
It provides all required mathematical functions and values.
80
© Prof. (Dr.) B P Sharma | Python Programming
Examples of math functions
81
© Prof. (Dr.) B P Sharma | Python Programming
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.
82
© Prof. (Dr.) B P Sharma | Python Programming
Example of math module with from keyword
83
© Prof. (Dr.) B P Sharma | Python Programming
How to give an alias name to the module?
We can also create an alias or shortname to the module using as keyword
along with import keyword
e.g.
84
© Prof. (Dr.) B P Sharma | Python Programming
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
© Prof. (Dr.) B P Sharma | Python Programming
Do we have all the Python module installed?
● No, not all 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 http://pypi.org as
package
● Some of required packages for Data Science and Machine Learning are
○ numpy
○ pandas
○ matplotlib
86
© Prof. (Dr.) B P Sharma | Python Programming
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 then you
can import pymongo module
○ conda install pymongo for Anaconda
○ pip install pymongo for Simple Python
○ pip3 install pymongo for Simple Python
87
© Prof. (Dr.) B P Sharma | Python Programming
How to create user defined functions?
Python provides def keyword to define the user defined functions.
Syntax
def functioname(argumentlist):
statements
Syntax
def functioname(argumentlist):
statements
return value or variable
88
© Prof. (Dr.) B P Sharma | Python Programming
Example 1: without using return statement
Create a function factorial which takes a number and prints factorial of given
number
89
© Prof. (Dr.) B P Sharma | Python Programming
Example 2: using return statement
Create a function factorial which takes a number and returns factorial of given
number
90
© Prof. (Dr.) B P Sharma | Python Programming
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
© Prof. (Dr.) B P Sharma | Python Programming
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.
92
© Prof. (Dr.) B P Sharma | Python Programming
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
© Prof. (Dr.) B P Sharma | Python Programming
How to pass variable number of arguments?
We can 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
© Prof. (Dr.) B P Sharma | Python Programming
Passing variable number of arguments with names
We can also pass variable number of arguments along with their names using
** with the argument name.
95
© Prof. (Dr.) B P Sharma | Python Programming
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
© Prof. (Dr.) B P Sharma | Python Programming
Returning multiple values from a function
Python functions allow to return multiple values with return statement
97
© Prof. (Dr.) B P Sharma | Python Programming
Creating recursive functions
● When a process repeats itself, it is called as recursive process.
● 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
© Prof. (Dr.) B P Sharma | Python Programming
Factorial of a number: Recursive function
99
© Prof. (Dr.) B P Sharma | Python Programming
Fibonacci Series: Recursive function
100
© Prof. (Dr.) B P Sharma | Python Programming
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
101
© Prof. (Dr.) B P Sharma | Python Programming
Lambda Functions
102
© Prof. (Dr.) B P Sharma | Python Programming
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
103
© Prof. (Dr.) B P Sharma | Python Programming
Using lambda function within functions
104
© Prof. (Dr.) B P Sharma | Python Programming
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
105
© Prof. (Dr.) B P Sharma | Python Programming
Exception Handling
106
© Prof. (Dr.) B P Sharma | Python Programming
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
● The raise statement is used to raise an exception in some scenario
107
© Prof. (Dr.) B P Sharma | Python Programming
Example of exception
108
© Prof. (Dr.) B P Sharma | Python Programming
Handling Exception
109
© Prof. (Dr.) B P Sharma | Python Programming
Raising an exception
110
© Prof. (Dr.) B P Sharma | Python Programming
What is a class?
● A class is a template to create multiple objects of same type
● A class contains fields and methods
● Use class keyword to define a class
● Use dunder __init__() to define a constructor
● Use the dunder __str__() function to show some information when an
object get used without calling a method
111
Example
112
What is inheritance?
● A feature of Object Oriented Programming when we can use the classes
by inheriting one class into other class
● For example, Student can be parent class to an Alumni class
113
114