0% found this document useful (0 votes)
6 views

PythonProgramming 2 114

Uploaded by

Akansha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

PythonProgramming 2 114

Uploaded by

Akansha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

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
© Prof. (Dr.) B P Sharma | Python Programming
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.9.4
● Downloadable from https://python.org

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

Cell to write program code

Press Shift+Enter to Execute the code

9
© Prof. (Dr.) B P Sharma | Python Programming
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
© 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

● Single variable - Single value


● Single Variable - Multiple values
● Multiple variables - Same value
● Multiple variables - Different values

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

● Using comma operator


● Using format specifiers e.g. %d, %f, %s
● Using placeholders {} with format() object function of str class
● Use f to format output using variable names

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

● int() convert to integer data


● float() convert to floating data
● str() convert to string data
● bool() convert a number to boolean

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

Note: Some more operators to be discussed later

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

Compares two values and returns True or False only

24
© Prof. (Dr.) B P Sharma | Python Programming
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

25
© Prof. (Dr.) B P Sharma | Python Programming
Bitwise Operators
Truth table of & Truth table of | Truth table of ^

00=0 00=0 00=0


01=0 01=1 01=1
● & Bitwise And 10=0 10=1 10=1
11=1 11=1 11=0
● | Bitwise Or
● ^ Bitwise XOR
● ~ Bitwise Not
● << Left Shift
● >> Right Shift
Note:
Use bin() function to convert a
number from decimal to binary

26
© Prof. (Dr.) B P Sharma | Python Programming
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

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

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.

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

● 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>

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

WAP to input a number and check it to be prime number.

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

for variable in collectionname:


statements

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

● startswith() returns True if string starts with given string


● endswith() returns True if string ends with given string
● find() returns index of search string from left side
● rfind() returns index of search string from right
side
● replace() replace the search string with given string
● count() returns count of occurrences of given string

57
© Prof. (Dr.) B P Sharma | Python Programming
Example
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 (.)

58
© Prof. (Dr.) B P Sharma | Python Programming
Solution

© Prof. (Dr.) B P Sharma | Python Programming 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

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]

● 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
© 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.

Python provides four types of collections

● 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()

Module function are provided in some re-usable python files called as


modules to classify them from other functions. Python provides many such
modules e.g. math, os, sys etc.
78
© Prof. (Dr.) B P Sharma | Python Programming
How to use functions from a module?
Before using any 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
© Prof. (Dr.) B P Sharma | Python Programming
Using math module
It provides all required mathematical functions and values.

Some of them are

● factorial(n) returns factorial of given number


● sqrt(n) returns square root of given number
● pow(n,p) returns n to the power p
● sin(n) Return the sine of x (measured in radians)
● cos() Return the cosine of x (measured in radians)
● tan() Return the tangent of x (measured in radians)
● pi Returns value of pi

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.

● from math import factorial


● from math import factorial,sqrt
● from math import *

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

If you want to return some value then use return statement

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.

Use the special value called None with such arguments.

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.

Here we can read the argument name and value.

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

Example: Create a function multiresult() which takes a number and returns


square and cube of that number.

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

○ Student(rollno, name, course)

○ Alumni (rollno, name, course, organization, designation)

113
114

You might also like