Functions
WHAT IS FUNCTIONS ?
 A function is a block of code that performs a specific task whenever it is called.
 In bigger programs, where we have large amounts of code, it is advisable to
create or use existing functions that make the program flow organized and neat.
 There are two types of functions-
1. built-in functions
2. user-defined functions
## built-in functions:
these functions are defined and pre-coded in python. some examples of built-in
functions are as follows:
min(), max(), len(), sum(), type(), range(), dict(), list(), tuple(), set(),
print(), etc.
## user-defined functions:
we can create functions to perform specific tasks as per our needs. such
functions are called user-defined functions.
### syntax:
def function_name(parameters):
pass
# code and statements
```
• create a function using the def keyword, followed by a function name, followed by a
paranthesis (()) and a colon(:).
• any parameters and arguments should be placed within the parentheses.
• rules to naming function are similar to that of naming variables.
• any statements and other code within the function should be indented.
### calling a function:
• we call a function by giving the function name, followed by parameters (if any) in
the parenthesis.
Example:
```python
def name(fname, lname):
print("Hello,", fname, lname)
name("Sam", "Wilson")
```
Output:
```
Hello, Sam Wilson
FUNCTION ARGUMENTS
There Are Four Types Of Arguments That We Can Provide In A
Function:
 Default Arguments
 Keyword Arguments
 Variable Length Arguments
 Required Argument
DEFAULT ARGUMENTS
We can provide a default value while creating a function. this way the
function assumes a default value even if a value is not provided in the
function call for that argument.
example:
def name(fname, mname = "jhon", lname = "whatson"):
print("hello,", fname, mname, lname)
name("amy")
• output:
• hello, amy jhon whatson
KEYWORD ARGUMENTS
 we can provide arguments with key = value, this way the interpreter
recognizes the arguments by the parameter name.
 Hence, the the order in which the arguments are passed does not matter.
example:
def name(fname, mname, lname):
print("hello,", fname, mname, lname)
name(mname = "peter", lname = "wesker", fname = "jade")
output:
hello, jade peter wesker
REQUIRED ARGUMENTS
• In case we don’t pass the arguments with a key = value syntax, then it is necessary to pass the arguments in
the correct positional order and the number of arguments passed should match with actual function
definition.
example 1: when number of arguments passed does not match to the actual function definition.
def name(fname, mname, lname):
print("hello,", fname, mname, lname)
name("peter", "quill")
• output:
name("peter", "quill")
typeerror: name() missing 1 required positional argument: 'lname'
• example 2: when number of arguments passed matches to the actual function definition.
• ```python
• def name(fname, mname, lname):
• print("hello,", fname, mname, lname)
•
name("peter", "ego", "quill")
• ```
• output:
• ```
• hello, peter ego quill
VARIABLE-LENGTH ARGUMENTS:
sometimes we may need to pass more arguments than those defined in the actual function.
this can be done using variable-length arguments.
there are two ways to achieve this:
1- arbitrary arguments:
• while creating a function, pass a * before the parameter name while defining the function. the
function accesses the arguments by processing them in the form of tuple.
example:
• def name(*name):
• print("hello,", name[0], name[1], name[2])
• name("james", "buchanan", "barnes") #output: hello, james buchanan barnes
#### 2- keyword arbitrary arguments:
• while creating a function, pass * * before the parameter name while defining the function. the
function accesses the arguments by processing them in the form of dictionary.
example:
def name(**name):
print("hello,", name["fname"], name["mname"], name["lname"])
name(mname = "buchanan", lname = "barnes", fname = "james")
• output: hello, james
RETURN STATEMENT
• The return statement is used to return the value of the expression back to the calling function.
example:
• def name(fname, mname, lname):
return "hello, " + fname + " " + mname + " " + lname
print(name("james", "buchanan", "barnes"))
output:
hello, james buchanan barnes
# WHAT ARE STRINGS?
• IN PYTHON, ANYTHING THAT YOU ENCLOSE BETWEEN SINGLE OR DOUBLE QUOTATION MARKS IS
CONSIDERED A STRING. A STRING IS ESSENTIALLY A SEQUENCE OR ARRAY OF TEXTUAL DATA.
STRINGS ARE USED WHEN WORKING WITH UNICODE CHARACTERS.
## EXAMPLE
• NAME = “PAWAN"
• PRINT("HELLO, " + NAME)
• ## OUTPUT
• HELLO, PAWAN
• NOTE: IT DOES NOT MATTER WHETHER YOU ENCLOSE YOUR STRINGS IN SINGLE OR DOUBLE
QUOTES, THE OUTPUT REMAINS THE SAME.
## MULTILINE STRINGS
• IF OUR STRING HAS MULTIPLE LINES, WE CAN CREATE THEM LIKE THIS:
EX-
A = """LOREM IPSUM DOLOR SIT AMET,
CONSECTETUR ADIPISCING ELIT,
SED DO EIUSMOD TEMPOR INCIDIDUNT
UT LABORE ET DOLORE MAGNA ALIQUA."""
PRINT(A)
## ACCESSING CHARACTERS OF A STRING
• IN PYTHON, STRING IS LIKE AN ARRAY OF CHARACTERS. WE CAN ACCESS
PARTS OF STRING BY USING ITS INDEX WHICH STARTS FROM 0.
• SQUARE BRACKETS CAN BE USED TO ACCESS ELEMENTS OF THE STRING.
EX-
NAME = “PAWAN”
PRINT(NAME[0])
PRINT(NAME[1])
• O/P
P
A
## LOOPING THROUGH THE STRING
• WE CAN LOOP THROUGH STRINGS USING A FOR LOOP LIKE THIS:
EX-
name = “pawan
for character in name:
print(character)
Above code prints all the characters in the string name one
by one!
# STRING SLICING & OPERATIONS ON
STRING
# LENGTH OF A STRING
WE CAN FIND THE LENGTH OF A STRING USING LEN() FUNCTION.
## EXAMPLE:
• fruit = "mango"
• len1 = len(fruit)
• print("mango is a", len1, "letter word.")
• ## output:
• mango is a 5 letter word.
# STRING AS AN ARRAY
• A STRING IS ESSENTIALLY A SEQUENCE OF CHARACTERS ALSO CALLED AN ARRAY. THUS WE CAN
ACCESS THE ELEMENTS OF THIS ARRAY.
## example:
pie = "applepie"
print(pie[:5])
print(pie[6]) #returns character at specified index
## output:
```
apple
## SLICING EXAMPLE:
• NOTE: THIS METHOD OF SPECIFYING THE START AND END INDEX TO SPECIFY A PART OF A STRING IS
CALLED SLICING.
• pie = "applepie"
• print(pie[:5]) #slicing from start
• print(pie[5:]) #slicing till end
• print(pie[2:6]) #slicing in between
• print(pie[-8:]) #slicing using negative index
• ## output:
• apple
• pie
• plep
• applepie
# STRING METHODS