0% found this document useful (0 votes)
40 views56 pages

Unit 3

Functions allow programmers to organize code into reusable blocks. Functions can take parameters as input and return values. Variables defined inside functions are local in scope and only exist while the function is executing. Strings are immutable in Python, so concatenation or other operations result in new string objects rather than modifying existing ones. Common string methods include strip(), lower(), upper(), replace(), split(), and format().

Uploaded by

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

Unit 3

Functions allow programmers to organize code into reusable blocks. Functions can take parameters as input and return values. Variables defined inside functions are local in scope and only exist while the function is executing. Strings are immutable in Python, so concatenation or other operations result in new string objects rather than modifying existing ones. Common string methods include strip(), lower(), upper(), replace(), split(), and format().

Uploaded by

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

UNIT 3

FUNCTIONS AND STRINGS


Need for functions
• We use functions in programming to bundle a
set of instructions that we want to use
repeatedly
• Or because of their complexity, are better self-
contained in a sub-program and called when
needed.
Types of functions in Python
Function Definition
• A function is a block of code which only runs
when it is called.

• You can pass data, known as parameters, into


a function.

• A function can return data as a result.


Defining Functions
• In Python a function is defined using the def
keyword

def my_function():
print("Hello from a function")
Function Call
• To call a function, use the function name
followed by parenthesis

my_function()
Parameters & Arguments
Function – return statement
• To let a function return a value, use the return
statement

def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))
Function Return Type
Function that does not return any value

def fn():
print('Hello World!')

print(type(fn()))

Answer: <class 'NoneType'>


Function Variable Scope and Lifetime
• Not all variables are accessible from all parts
of our program
• And not all variables exist for the same
amount of time.
• Where a variable is accessible and how long it
exists depend on how it is defined.
• We call the part of a program where a variable
is accessible its scope, and the duration for
which the variable exists its lifetime.
Function Variable Scope and Lifetime
• A variable which is defined in the main body
of a file is called a global variable. It will be
visible throughout the file, and also inside any
file which imports that file.

• Global variables can have unintended


consequences because of their wide-ranging
effects – that is why we should almost never
use them.
Function Variable Scope and Lifetime
• Only objects which are intended to be used
globally, like functions and classes, should be
put in the global namespace.
Function Variable Scope and Lifetime
• A variable which is defined inside a function is
local to that function.

• It is accessible from the point at which it is


defined until the end of the function

• It exists for as long as the function is


executing.
Function Variable Scope and Lifetime
• The parameter names in the function
definition behave like local variables

• They contain the values that we pass into the


function when we call it.

• When we use the assignment operator (=)


inside a function, its default behaviour is to
create a new local variable
Function Parameters
• Information can be passed to functions as
parameter.

• Parameters are specified after the function


name, inside the parentheses. You can add as
many parameters as you want, just separate
them with a comma.
Default Parameter Value
• The following example shows how to use a
default parameter value.

• If we call the function without parameter, it


uses the default value
Default Parameter Value
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Empty function in C/C++/Java
// An empty function in C/C++/Java
void fun()
{
}
Empty function in Python
# Incorrect empty function in Python
def fun():

IndentationError: expected an indented block


Empty function in Python
# Correct way of writing empty function
# in Python
def fun():
pass
Function call
Difference between call by value
and call by reference
No. Call by value Call by reference

1 A copy of the value is passed into the function An address of value is passed into the
function

2 Changes made inside the function is limited to Changes made inside the function validate
the function only. The values of the actual outside of the function also. The values of
parameters do not change by changing the the actual parameters do change by
formal parameters. changing the formal parameters.

3 Actual and formal arguments are created at the Actual and formal arguments are created
different memory location at the same memory location
Concatenation of Strings
• Concatenation = Gluing together

• Concatenating With the + Operator


– The + operator is overloaded
– 'a' + 'b' + 'c‘ = 'abc‘
String Joining Methods
• There is no concat() method in Python which
Java has

• Python has join() method that works with


collections like List
Python variables are immutable
• In Python, immutable objects are those whose value
cannot be changed in place after assignment or
initialization.

• They allocate new memory whenever their value is


changed.

• Examples of immutable data types or objects or


variables in Python are numbers ( integers , floats ),
strings and Tuples .
Python Strings are immutable
• Strings in Python are immutable i.e. can not
be changed
– If you concatenate or repeat a string stored in a
variable, you will have to assign the new string to
another variable in order to keep it.
Python String Appending
• Add a new string to the existing string
• a=10
• a=a+20
• The new value of a will be 30.
• This is called as appending of the variable ‘a’
• But in Python ‘a’ is not appended but it points
to new memory location with value 30
• So it is not possible to append a python string
Python String Appending
• We will see Python string appending when we
see the List
String Multiplication
• S1=“Hello, World”
• S1=S1+“Hello, World”

• S1=“Hello, World”
• S1=S1 * 2
Substring = String slicing

• Substring. Get the characters from position 2


to position 5:
Both 2 (inclusive) and 5 (exclusive)

Note the rectangular bracket as strings are arrays in Python


String Format

• As we learned in the Python Variables chapter,


we cannot combine strings and numbers like
this:
String Format

• Use format() method to insert number into


Strings
String Format
• We can combine strings and numbers by using
the format() method!
• The format() method takes the passed
arguments, formats them, and places them in
the string where the placeholders {} are:
String Format

• The number of arguments in the format


method
– The format() method takes unlimited number of
arguments, and are placed into the respective
placeholders:
String Format

• Index numbers for arguments in format method


• You can use index numbers {0} to be sure the
arguments are placed in the correct
placeholders:
The strip() method

• The strip() method removes any whitespace


from the beginning or the end:
The len() method

• The len() method returns the length of a


string:
The lower() method

• The lower() method returns the string in lower


case:
The upper() method

• The upper() method returns the string in


upper case:
The replace() method

• The replace() method replaces a string with


another string:

replace(‘A’) or replace(“B”)
Single Quote or Double Quote
All occurrences are replaced.
The split() method

• The split() method splits the string into


substrings if it finds instances of the separator:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy