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

Function, String

1. Functions are subprograms that perform specific tasks and are used to break large programs into smaller, reusable parts. 2. There are two types of functions: built-in functions that are pre-defined in Python, and user-defined functions that are created by programmers. 3. Functions make programs easier to debug, test, and maintain by separating code into logical blocks. Functions also promote code reusability.

Uploaded by

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

Function, String

1. Functions are subprograms that perform specific tasks and are used to break large programs into smaller, reusable parts. 2. There are two types of functions: built-in functions that are pre-defined in Python, and user-defined functions that are created by programmers. 3. Functions make programs easier to debug, test, and maintain by separating code into logical blocks. Functions also promote code reusability.

Uploaded by

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

FUNCTIONS:

➢ Function is a sub program which consists of set of instructions used to perform a specific task.
A large program is divided into basic building blocks called function.

Need For Function:


• When the program is too complex and large they are divided into parts. Each part is separately
coded and combined into single program. Each subprogram is called as function.
• Debugging, Testing and maintenance becomes easy when the program is divided into
subprograms.
• Functions are used to avoid rewriting same code again and again in a program.
• Function provides code re-usability
• The length of the program is reduced.

Types of function:
Functions can be classified into two categories:
i) user defined function
ii) Built in function
i) Built in functions
• Built in functions are the functions that are already created and stored inpython.
• These built in functions are always available for usage and accessed by a programmer. It cannot be
modified.
Built in function Description

>>>max(3,4) 4 # returns largest element

>>>min(3,4) 3 # returns smallest element

>>>len("hello") 5 #returns length of an object

>>>range(2,8,1) [2, #returns range of given values


3, 4, 5, 6, 7]
>>>round(7.8) 8.0 #returns rounded integer of the given number

>>>chr(5) #returns a character (a string) from an integer


\x05'
>>>float(5) #returns float number from string or integer
5.0
>>>int(5.0) 5 # returns integer from string or float

>>>pow(3,5) 243 #returns power of given number

>>>type( 5.6) #returns data type of object to which it belongs


<type 'float'>
>>>t=tuple([4,6.0,7]) # to create tuple of items from list
(4, 6.0, 7)
>>>print("good morning") # displays the given object
Good morning
>>>input("enter name:") # reads and returns the given string
enter name : George

ii) User Defined Functions:


• User defined functions are the functions that programmers create for their requirement anduse.
• These functions can then be combined to form module which can be used in other programs by
importing them.
• Advantages of user defined functions:
• Programmers working on large project can divide the workload by making different functions.
• If repeated code occurs in a program, function can be used to include those codes and execute
when needed by calling that function.

Function definition: (Sub program)


• def keyword is used to define a function.
• Give the function name after def keyword followed by parentheses in which arguments are given.
• End with colon (:)
• Inside the function add the program statements to be executed
• End with or without return statement
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n): statement1
statement2…
statement n return[expression]

Example:
def my_add(a,b):
c=a+b
return c

Function Calling: (Main Function)


➢ Once we have defined a function, we can call it from another function, program or even the
Pythonprompt.
➢ To call a function we simply type the function name with appropriate arguments.
Example:
x=5
y=4
my_add(x,y)

Flow of Execution:

• The order in which statements are executed is called the flow of execution
• Execution always begins at the first statement of the program.
• Statements are executed one at a time, in order, from top to bottom.
• Function definitions do not alter the flow of execution of the program, but remember that statements
inside the function are not executed until the function is called.
• Function calls are like a bypass in the flow of execution. Instead of going to the next statement, the
flow jumps to the first line of the called function, executes all the statements there, and then comes
back to pick up where it left off.
Note: When you read a program, don‟t read from top to bottom. Instead, follow the flow of execution. This
means that you will read the def statements as you are scanning from top to bottom, but you should skip the
statements of the function definition until you reach a point where that function is called.

Function Prototypes:

i. Function without arguments and without return type


ii. Function with arguments and without return type
iii. Function without arguments and with return type
iv. Function with arguments and with return type
i) Function without arguments and without return type
o In this type no argument is passed through the function call and no output is return to main
function
o The sub function will read the input values perform the operation and print the result in the
same block
ii) Function with arguments and without return type
o Arguments are passed through the function call but output is not return to the main function
iii) Function without arguments and with return type
o In this type no argument is passed through the function call but output is return to the main
function.
iv) Function with arguments and with return type
o In this type arguments are passed through the function call and output is return to the main
function
Without Return Type
Without argument With argument

def add(): def add(a,b):


a=int(input("enter a")) c=a+b
b=int(input("enter b")) print(c)
c=a+b a=int(input("enter a"))
print(c) b=int(input("enter b"))
add() add(a,b)

OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15

With return type


Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enterb")) return c
a=int(input("enter a"))
c=a+b
b=int(input("enter b"))
return c
c=add(a,b)
c=add()
print(c)
print(c)

OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15
Fruitful Function

• Fruitful function
• Void function
• Return values
• Parameters
• Local and global scope
• Function composition
• Recursion

Fruitful function:

A function that returns a value is called fruitful function.

Example:
Root=sqrt(25)

Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)

Void Function

A function that perform action but don’t return any value.

Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()

Return values:
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2 variables
return a,b,c– return 3 variables
return a+b– return expression
return 8– return value

PARAMETERS / ARGUMENTS:

❖ Parameters are the variables which used in the function definition. Parameters are
inputs to functions. Parameter receives the input from the function call.
❖ It is possible to define more than one parameter in the function definition.

Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters

Required/ Positional Parameter:


The number of parameter in the function definition should match exactly with number of
arguments in the function call.
Example
def student( name, roll ):
print(name,roll)
student(“George”,98)

Output:
George 98

Keyword parameter:

When we call a function with some values, these values get assigned to the parameter according to
their position. When we call functions in keyword parameter, the order of the arguments can be
changed.

Example
def student(name,roll,mark):
print(name,roll,mark)
student(90,102,"bala")

Output:
90 102 bala

Default parameter:

Python allows function parameter to have default values; if the function is called without the
argument, the argument gets its default value in function definition.
Example
def student( name, age=17):
print (name, age)
student( “kumar”):
student( “ajay”):

Output:
Kumar 17
Ajay 17

Variable length parameter

❖ Sometimes, we do not know in advance the number of arguments that will be passed
into a function.

❖ Python allows us to handle this kind of situation through function calls with number of
arguments.

❖ In the function definition we use an asterisk (*) before the parameter name to denote
this is variable length of parameter.

Example
def student( name,*mark):
print(name,mark)
student (“bala”,102,90)

Output:
bala ( 102 ,90)
Local and Global Scope

Global Scope
❖ The scope of a variable refers to the places that you can see or access a variable.
❖ A variable with global scope can be used anywhere in the program.
❖ It can be created by defining a variable outside the function.

Local Scope A variable with local scope can be used only within the function .

Function Composition:

❖ Function Composition is the ability to call one function from within another function
❖ It is a way of combining functions such that the result of each function is passed as the
argument of the next function.
❖ In other words the output of one function is given as the input of another function is
known as function composition.
Example:
math.sqrt(math.log(10))
def add(a,b):
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)

Output:
900

find sum and average using function composition


def sum(a,b):
sum=a+b
return sum
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b)
avg=avg(sum)
print("the avg is",avg)

output
enter a:4
enter b:8
the avg is 6.0
Recursion

A function calling itself till it reaches the base value - stop point of function call. Example:
factorial of a given number using recursion

Factorial of n
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
n=eval(input("enter no. to find
fact:"))
fact=fact(n)
print("Fact is",fact)

Output
enter no. to find fact:5
Fact is 120

Explanation
Strings:

Strings

String slices

Immutability

String functions and methods

String module

Strings:

String is defined as sequence of characters represented in quotation marks(either single
quotes ( ‘ ) or double quotes ( “ ).

An individual character in a string is accessed using a index.

The index should always be an integer (positive or negative).

A index starts from 0 to n-1.

Strings are immutable i.e. the contents of the string cannot be changed after it is created.

Python will get the input at run time by default as a string.

Python does not support character data type. A string of size 1 can be treated as characters.

1. single quotes (' ')


2. double quotes (" ")
3. triple quotes(“”” “”””)

Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
String slices:
A part of a string is called string slices.
The process of extracting a sub string from a string is called slicing.

Immutability:
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
string built in functions and methods:
A method is a function that “belongs to” an object.

Syntax to access the method


Stringname.method()
a=”happy birthday”
here, a is the string name.
String modules:

A module is a file containing Python definitions, functions, statements.

Standard library of Python is extended as modules.

To use these modules in a program, programmer needs to import the module.

Once we import a module, we can reference or use to any of its functions or variables in our
code.

There is large number of standard modules also available in python.

Standard modules can be imported the same way as we import our user-defined modules.

Syntax:
import module_name

Example
import string
print(string.punctuation)
print(string.digits)
print(string.printable)
print(string.capwords("happy birthday"))
print(string.hexdigits)
print(string.octdigits)
output
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
0123456789
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
./:;<=>?@[\]^_`{|}~
Happy Birthday
0123456789abcdefABCDEF
01234567

Escape sequences in string

You might also like