0% found this document useful (0 votes)
2 views12 pages

python chapter 2.pdf

Chapter 2 of the Python Programming document covers functions, including their definition, types (built-in, module, user-defined), and how to create and call them. It also discusses parameters, command line arguments, recursion, and string manipulation techniques such as concatenation, slicing, and various string methods. The chapter provides examples and syntax for each concept to aid understanding.

Uploaded by

ys5263791
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

python chapter 2.pdf

Chapter 2 of the Python Programming document covers functions, including their definition, types (built-in, module, user-defined), and how to create and call them. It also discusses parameters, command line arguments, recursion, and string manipulation techniques such as concatenation, slicing, and various string methods. The chapter provides examples and syntax for each concept to aid understanding.

Uploaded by

ys5263791
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

PYTHON PROGRAMMING Chapter 2

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

Creating a Function / Defining Functions


Python provides the def keyword to define the function.

The syntax of the define function is given below.


def my_function(parameters):
function_block
return expression

– 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)

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 1


PYTHON PROGRAMMING Chapter 2

Y=min (5, 2,7,19)


Z=max(2,20,4,33,21)
print (range(1,5))

➢ 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.

WAP to illustrate math module


import math
print "Absolute value of -34.45 is ",math.fabs(-34.45)
print "Absolute value of 56.34 is ",math.fabs(56.34)
print "ceil of 100.12 is ",math.ceil(100.12)
print "ceil of 100.67 is ",math.ceil(100.67)
print "floor of 50.34 is ",math.floor(50.34)
print "floor of 50.89 is ",math.floor(50.89)
print "E rise to 2 is ",math.exp(1)
print "squre root of 25 is ",math.sqrt(25)

Create your own Module / Construct the user defined module:


▪ Module contain set of user defined function and regular expressions.
▪ In order to create user defined module, first create module description/user
defined functions and save with the module name along with extension py.
▪ We can those modules using other python programs my importing those
module name.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 2


PYTHON PROGRAMMING Chapter 2

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.

Simple rules to defined user defined function are:


▪ A function blocks begins with the keyword def followed by function name
followed by parenthesized parameter list and the colon
▪ Any input parameters or arguments should be placed within these
parentheses.
▪ The body of the function followed by colon and is indented.
▪ The return statement exits a function. The return statement contain zero or
with an argument.
▪ Calling / invoking a function by its function-name.

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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 3


PYTHON PROGRAMMING Chapter 2

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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 4


PYTHON PROGRAMMING Chapter 2

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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 5


PYTHON PROGRAMMING Chapter 2

Return Statement
We return a value from the function using the return statement.
# function definition

In the above example, we have created a function named find_square().


The function accepts a number and returns the square of the number.

Scope and lifetime of the variables in function


In Python, we can declare variables in three different scopes: local scope,
global.
Based on the scope, we can classify Python variables into three types:
➢ Local Variables
➢ Global Variables

Python Local Variables


When we declare variables inside a function, these variables will have a
local scope (within the function). We cannot access them outside the function.
These types of variables are called local variables. For example,
def greet():
# local variable
message = 'Hello'
print('Local', message)
greet()
# try to access message variable
# outside greet() function
print(message)
Here, the message variable is local to the greet() function, so it can only
be accessed within the function.

Python Global Variables


In Python, a variable declared outside of the function or in global scope is
known as a global variable. This means that a global variable can be accessed
inside or outside of the function.
Let's see an example of how a global variable is created in Python:
# declare global variable
message = 'Hello'

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 6


PYTHON PROGRAMMING Chapter 2

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.

Any recursive function can be divided into two parts.


First, there must be one or more base cases, to solve the simplest case,
which is referred to as the base case or the stopping condition
Next, recursive cases, here function is called with different arguments,
which are referred to as a recursive call. These are values that are handled by
“reducing” the problem to a “simpler” problem of the same form.

Example:
def factorial(n):
if n == 0:
return( 1)
else:
return (n*factorial(n-1)) # Recursive call

n=int(input("Enter a nonnegative integer: "))


print("Factorial of", n, "is", factorial(n))
-----------------------------------------------------------------------------------

String
String is a group of characters enclosed with in single quotes or double quotes
or triple quotes.

Accessing & Storing String:


Strings are stored in the arrays with index values starting from 0.
String Representation

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 7


PYTHON PROGRAMMING Chapter 2

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)

3. Using join() method:


join() method is also used to combine two or more strings.
Str1=”abc”
Str2=”xyz”
Str3=” “.join([Str1,Str2])
print(Str3)

4. Using format() method:


format() method is also used to combine two or more strings.
Str1=”abc”
Str2=”xyz”
Str3=”{}{}”.format([Str1,Str2])
print(str3)

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 8


PYTHON PROGRAMMING Chapter 2

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)

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 9


PYTHON PROGRAMMING Chapter 2

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"

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 10


PYTHON PROGRAMMING Chapter 2

print(a.replace(“O”, “A”)) # it display : FAR

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

str2="python version 3.4.2"


print(str2.isalpha()) # it display : False

13. isdigit():
It returns true when all character in the string is digit otherwise false.
s = "28212"
print(s.isdigit()) # it display : True

s = "Welcome abc 1"


print(s.isdigit()) # it display : False

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 11


PYTHON PROGRAMMING Chapter 2

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)

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 12

You might also like