python chapter 2.pdf
python chapter 2.pdf
Chapter 2
FUNCTIONS
▪ Function is a group of statements and perform a specific task
▪ When a function is written inside a class, it becomes a method, A method can
be called using object / class name
– The def keyword, along with the function name is used to define the
function.
– The identifier rule must follow the function name.
– A function accepts the parameter (argument), and they can be optional.
– The function block is started with the colon (:), and block statements must
be at the same indentation.
– The return statement is used to return the value. A function can have only
one return
Example
def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())
Types of function:
Functions are three types, There are:
➢ Built-in function
➢ Module
➢ User-defined function.
➢ Built-in Functions:
▪ Built-in functions are the functions that are built into Python and can be
accessed by programmer any time without importing any module.
▪ These functions are also called as standard functions.
▪ These functions are available in all versions of Python.
Example,
X= abs(-34)
➢ Module:
▪ A module is a file that contains a collection of related functions and other
definitions.
▪ Modules are extensions that can be imported into Python programs.
▪ Modules are user-defined modules or built in module.
Built in module:
Python has a math module that includes a number of specialized
mathematical tools. To include math module into your program by importing it.
Example:
File name : module1.py
def sum1(a,b):
c = a+b
return c
def mul1(a,b):
c = a*b
return c
Filename: Test_module1.py
import module1
x = 12
y = 34
print("Sum is ", module1.sum1(x,y))
print("Multiple is ", module1.mul1(x,y))
➢ User-Defined Functions:
A user defined function represents a function which is named and provided by
user to produce the desired and certain output.
Syntax:
def function-Name(argument-list) : #Function header
St-1 St-2
: # Function body
St-n return()
Example:
def printname(str):
print str
return
printname("Python")
----------------------------------------------------------------------------------------
Types of Parameters or Formal Arguments:
The user defined functions can be call by using the following types of formal
arguments.
➢ Required arguments
➢ Keyword arguments
➢ Default arguments
➢ Variable –length arguments
Required Arguments:
▪ Required arguments are the arguments passed to a function in correct
positional order.
▪ The number of arguments in the function call should match exactly with the
function definition.
Example:
def printinfo(name,sem):
print name
print sem
return
printinfo(“aaa”,6)
In the above example, we have passed two arguments. The function definition
contains two arguments to receive those values.
Keyword Arguments:
▪ Keyword arguments are the arguments with assigned values passed in the function
call statement, i.e., when you use keyword argument in a function call, the caller
identifies the arguments by the parameter name.
▪ The Python interpreter is able to use the keywords provided to match the values
with parameters.
Example:
def printinfo(name,sem):
print name
print sem
return
printinfo(sem=6,name=“aaa”)
In the above example, we passed arguments with different order and then the caller
identifies the arguments by the parameter name.
Default Arguments:
▪ A default argument is an argument that assumes a default values if a value is not
provided in the function call for that argument.
▪ A parameter having default value in the function header is known as a default
parameter.
Example:
def printinfo(name=”bbb”,sem=6)
print name
print sem
return
printinfo()
printinfo(sem=6)
printinfo(name=“aaa”,sem=2)
In the above example, first call, we missing both the arguments and then function take
default values. In second time call, we missing one argument and then take name
values as the default value. In third time call, we r not missing any arguments and then
function takes both the arguments provided by the user.
Variable-length arguments:
➢ To process a function for more arguments than you specified while defining the
function. These arguments are called variable length arguments and are not named
in the function definition, unlike required and default arguments.
➢ A asterisk (*) is placed before the variable name that will hold the values of all non-
keyword variable arguments. This tuple remains empty if not additional arguments
are specified during the function call.
Example:
def printinfo(arg1, *vartuple)
print arg1
for k in vartuple :
print k
return
printinfo(10)
printinfo(1,2,3,4,5)
----------------------------------------------------------------------------------------------
Command line argument:
The arguments which are given in the command line or terminal in python
are called as command line arguments.
Example:
import sys
print(len(sys.argv));
print(“the command line arguments are : “)
for i in sys.argv:
print(i)
-----------------------------------------------------------------------------------------
Function Calling
To call a function, use the function's name followed by parentheses. If the
function expects arguments, include them within the parentheses.
Here,
- When the function greet() is called, the program's control transfers to the
function definition.
- All the code inside the function is executed.
- The control of the program jumps to the next statement after the function
call.
Return Statement
We return a value from the function using the return statement.
# function definition
def greet():
# declare local variable
print('Local', message)
greet()
print('Global', message)
This time we can access the message variable from outside of
the greet() function. This is because we have created the message variable as
the global variable.
----------------------------------------------------------------------------------------
RECURSION
A recursive function is one that invokes itself. Or A recursive function is a
function that calls itself in its definition.
Example:
def factorial(n):
if n == 0:
return( 1)
else:
return (n*factorial(n-1)) # Recursive call
String
String is a group of characters enclosed with in single quotes or double quotes
or triple quotes.
Example:
Str=”College”
print(str[0])
print(str[1:3])
print(str[2:5])
Operations on Strings:
➢ Concatenation
➢ Comparison
➢ Slicing
➢ Splitting
➢ Joining
➢ Traversing
Concatenation:
Combining two or more strings are called as concatenation.
There are 4 different techniques which are used to concatenation of strings.
1. Using + operator:
We can concat two or more strings using + operator
Str1=”abc”
Str2=”xyz”
Str3=Str1+Str2
print(Str3)
2. Using % operator:
We can concat two or more strings using + operator
Str1=”abc”
Str2=”xyz”
Str3=”%s%s”%(Str1,Str2)
print(Str3)
Comparison:
We can compare two strings by using is and is not operators.
➢ is operator: is operator used to check whether two strings are equal then it
returns true otherwise it return false.
➢ is not operator: is not operator used to check whether two strings are not
equal then it returns true otherwise it return false.
Str1=”abc”
Str2=”xyz”
if Str1 is Str2:
print(“two strings are equal”)
else:
print(“two strings are not equal”)
Slicing of a string:
Retrieving the substring from the main string is called slicing.
Syntax:
str_variable[start:stop:increment]
Example:
str=”welcome to python programming”
print(str([5:20:1])
output:
me to python pr
Splitting a string:
split() is a method used to split the string into words.
Syntax:
str_varsplit(‘ ‘)
Example:
Str1=”welcome to python”
Str2=Str1.Split()
print(Str2)
Joining a string:
join() method is also used to combine two or more strings.
Str1=”abc”
Str2=”xyz”
Str3=” “.join([Str1,Str2])
print(Str1)
String Traversing:
Visiting all the characters exactly once in a string is called traversing of a string.
String slicing is the best example for visiting all the character of a string.
Syntax: Str_varible[start:stop:increment]
Str=”welcome to python”
print(str[5:10:1]
String functions
1. Extract specified character from the string.
Get the character at position 1 (remember that the first character has the
position 0):
a= "Hello,Python!"
print(a[6]) # it display : P
2. Substring:
Extract number of character from the specified position. Get the characters from
position 2 to position 5 (not included):
b= "Hello,Python!"
print(b[6:8]) # it display : Ph
3. strip():
The strip() method removes any whitespace from the beginning or the end
of the given string.
a= " Hello,Python! "
print(a.strip()) # it display : "Hello,Python!"
4. len():
The len() method returns the length of a given string
a= " Python"
print(len(a)) # it display : 6
5. lower():
The lower() method returns the given string in lower case.
a= " PYTHON"
print(a.lower()) # it display : python
6. upper():
The upper() method returns the given string in upper case.
a= " python"
print(a.upper()) # it display : PYTHON
7. replace():
The replace() method replaces a given string with another string
a= "FOR"
8. split():
The split() method splits the string into substrings if it finds instances of the
separator
a= "Hello,Python!"
print(a.split(‘,’)) # it display :[‘Hello’,‘Python’]
9. capitalize():
It is used to capitalize letter the 1 st character of a string.
txt="welcome"
x=txt.capitalize()
print(x) # it display : Welcome
10. count():
This function searches the substring in the given string and returns how many
times the substring is present in it.
string = "Python is awesome, isn't it?"
substring = "is"
count = string.count(substring)
print(count) # it display : 2
11. isalpha():
It returns true, when all the characters in the string and alphabet otherwise
false.
str1="welcome"
print(str1.isalpha()) # it display : True
13. isdigit():
It returns true when all character in the string is digit otherwise false.
s = "28212"
print(s.isdigit()) # it display : True
14. islower():
It returns true when all the character are lower case otherwise false of a string.
str1="welcome";
print(str1.islower()) # it display : True
str2="ABC"
print(str2.islower()) # it display : False
15. isupper():
It return true when all the character of a string are in uppercase otherwise false.
str1="welcome";
print(str1. isupper()) # it display : False
str2="ABC"
print(str2. isupper()) # it display : True
Format Specifiers
Format specifiers are used to display the values in a given format using
format() function.
Example:
a=10.23456
print(“a=”,format(a,”2.f”))
output: a=10.23
Raw string
Raw string is useful when you deal with strings that have many backslash.
For example, regular expressions are directory oaths on windows.
In python, when you prefix a string with the letter r or R, such as r’…’ and
R’…’, that string becomes a raw string. Unlike a regular string, a new string
treats the backslashes(/) as literal characters.
Example:
S=’lang\tver\npython\+c’
Print(S)