0% found this document useful (0 votes)
5 views48 pages

Python Programming U2

This document provides an overview of Python functions, including their declaration, parameters, return values, and types of arguments such as default, keyword, positional, and arbitrary arguments. It also covers concepts like recursion, anonymous functions, and the distinction between pass by reference and pass by value. Examples are provided throughout to illustrate the various functionalities and syntax of defining and using functions in Python.

Uploaded by

chetanpatil21444
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views48 pages

Python Programming U2

This document provides an overview of Python functions, including their declaration, parameters, return values, and types of arguments such as default, keyword, positional, and arbitrary arguments. It also covers concepts like recursion, anonymous functions, and the distinction between pass by reference and pass by value. Examples are provided throughout to illustrate the various functionalities and syntax of defining and using functions in Python.

Uploaded by

chetanpatil21444
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 48

Unit -2

Python Functions
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.

Python Function Declaration


The syntax to declare a function is:

Syntax of Python Function Declaration


Creating a Function
In Python a function is defined using the def keyword:

Example:

def my_function():

print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:

def my_function():
print("Hello from a function")

my_function()

Hello from a function

User-Defined Function
We will define a function that returns the argument number's square when
called.

​ # Example Python Code for User-Defined function


​ def square( num ):
​ """
​ This function computes the square of the number.
​ """
​ return num**2
​ object_ = square(6)
​ print( "The square of the given number is: ", object_ )
Output:

The square of the given number is: 36

​ # Example Python Code for calling a function


​ # Defining a function
​ def a_function( string ):
​ "This prints the value of length of string"
​ return len(string)

​ # Calling the function we defined
​ print( "Length of the string Functions is: ", a_function( "Functions" ) )
​ print( "Length of the string Python is: ", a_function( "Python" ) )
Output:

Length of the string Functions is: 9


Length of the string Python is: 6

1. Function Variables in Python

Function variables refer to the variables that are defined inside a function. These are local
variables and exist only during the execution of the function.

Example:

name and message are function variables. They are only accessible within the greet function.
g = "global"
def display():
print("Global variable inside the Function :", g)
display()
Python Function with Parameters

If you have experience in C/C++ or Java then you must be thinking about the
return type of the function and data type of arguments. That is possible in
Python as well (specifically for Python 3.5 and above).

Python Function Syntax with Parameters


def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression

def add(num1: int, num2: int) -> int:


"""Add two numbers"""
num3 = num1 + num2

return num3

# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")

Output:
The addition of 5 and 15 results 20.

def add(num1, num2):


"""Add two numbers"""
num3 = num1 + num2
return num3

# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")

# Prime functions
def is_prime(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r=3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(78), is_prime(79))

Output:
False True

Default Parameter Value


The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:


I am from Sweden
I am from India
I am from Norway
I am from Brazil

Arguments
Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:

Example

def my_function(city):
print(city + " is a great place!")

my_function("New York")
my_function("Tokyo")
my_function("Paris")

Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.

def my_function(city, country):


print(city + ", " + country)

my_function("New York", "USA")


my_function("Tokyo", "Japan")
my_function("Paris", "France")

Error:
def my_function(fname, lname):
print(fname + " " + lname)

my_function("Emil")

Traceback (most recent call last):
File "demo_function_args_error.py", line 4, in <module>
my_function("Emil")
TypeError: my_function() missing 1 required positional argument:
'lname'

# A simple Python function to check


# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


evenOdd(2)
evenOdd(3)

Types of Python Function Arguments

Python supports various types of arguments that can be passed at the time
of the function call. In Python, we have the following function argument
types in Python:

●​ Default argument

●​ Keyword arguments (named arguments)

●​ Positional arguments

●​ Arbitrary arguments (variable-length arguments *args and

**kwargs)

Default Arguments

A default argument is a parameter that assumes a default value if a value is


not provided in the function call for that argument. The following example
illustrates Default arguments to write functions in Python.

# Python program to demonstrate

# default arguments

def myFun(x, y=50):

print("x: ", x)

print("y: ", y)
# Driver code (We call myFun() with only

# argument)

myFun(10)

Code

​ # Python code to demonstrate the use of default arguments


​ # defining a function
​ def function( n1, n2 = 20 ):
​ print("number 1 is: ", n1)
​ print("number 2 is: ", n2)


​ # Calling the function and passing only one argument
​ print( "Passing only one argument" )
​ function(30)

​ # Now giving two arguments to the function
​ print( "Passing two arguments" )
​ function(50,30)
Output:

Passing only one argument

number 1 is: 30

number 2 is: 20

Passing two arguments

number 1 is: 50

number 2 is: 30
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so
that the caller does not need to remember the order of parameters.

You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

The youngest child is Linus

# Python program to demonstrate Keyword Arguments


def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
Output:
Geeks Practice
Geeks Practice
Positional Arguments

We used the Position argument during the function call so that the first
argument (or value) is assigned to name and the second argument (or value)
is assigned to age. By changing the position, or if you forget the order of the
positions, the values can be used in the wrong places, as shown in the
Case-2 example below, where 27 is assigned to the name and Suraj is
assigned to the age.

Output:
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj

Arbitrary Keyword Arguments

In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a


variable number of arguments to a function using special symbols. There
are two special symbols:

●​ *args in Python (Non-Keyword Arguments)

●​ **kwargs in Python (Keyword Arguments)

1. *args (Non-Keyword Arguments)

●​ Allows a function to accept any number of positional arguments.

●​ *args collects the extra positional arguments passed to the

function into a tuple.


Output:

●​ *args captures "Alice", "Bob", and "Charlie" into a tuple.

●​ The loop iterates over the tuple to print greetings.

2. **kwargs (Keyword Arguments)

●​ Allows a function to accept any number of keyword arguments.

●​ **kwargs collects the extra keyword arguments passed to the

function into a dictionary.

Example:
●​ **kwargs captures name, age, and city as a dictionary.

●​ The loop iterates over the dictionary to print key-value pairs.

Using *args and **kwargs Together

You can use both in a function to accept both positional and keyword

arguments.
Output:

Example 1: Variable length non-keywords argument


Output:
Hello
Welcome
to
GeeksforGeeks

Example 2: Variable length keyword arguments


1
# Python program to illustrate
2
# *kwargs for variable number of keyword arguments
3

4

5
def myFun(**kwargs):
6
for key, value in kwargs.items():
7
print("%s == %s" % (key, value))
8

9

10
# Driver code
11
myFun(first='Geeks', mid='for', last='Geeks')
Output:
first == Geeks
mid == for
last == Geeks

Docstring
The first string after the function is called the Document string or
Docstring in short. This is used to describe the functionality of the
function. The use of docstring in functions is optional but it is considered a
good practice.

The below syntax can be used to print out the docstring of a function.
Syntax: print(function_name.__doc__)

Example: Adding Docstring to the function


1
# A simple Python function to check
2
# whether x is even or odd
3

4

5
def evenOdd(x):
6
"""Function to check if the number is even or odd"""
7

8
if (x % 2 == 0):
9
print("even")
10
else:
11
print("odd")
12

13

14
# Driver code to call the function
15
print(evenOdd.__doc__)
Output:
Function to check if the number is even or odd

Python Function within Functions


A function that is defined inside another function is known as the inner
function or nested function. Nested functions can access variables of the
enclosing scope. Inner functions are used so that they can be protected from
everything happening outside the function.
1
# Python program to
2
# demonstrate accessing of
3
# variables of nested functions
4

5
def f1():
6
s = 'I love GeeksforGeeks'
7

8
def f2():
9
print(s)
10

11
f2()
12

13
# Driver's code
14
f1()
Output:
I love GeeksforGeeks
Anonymous Functions in Python
In Python, an anonymous function means that a function is without a name.
As we already know the def keyword is used to define the normal functions
and the lambda keyword is used to create anonymous functions.
1
# Python code to illustrate the cube of a number
2
# using lambda function
3
def cube(x): return x*x*x
4

5
cube_v2 = lambda x : x*x*x
6

7
print(cube(7))
8
print(cube_v2(7))
Output:
343
343

2. Variable Arguments in Python

Python functions can accept a variable number of arguments using *args for non-keyword
arguments and **kwargs for keyword arguments.

●​ *args: Allows passing a variable number of positional arguments (non-keyword


arguments).
●​ **kwargs: Allows passing a variable number of keyword arguments (named
arguments).

Example with *args:


Example with **kwargs:

You can combine both *args and **kwargs in a function, but *args should appear before
**kwargs:
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your function,
add a * before the parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access the
items accordingly:

Example

If the number of arguments is unknown, add a * before the parameter name:

The youngest child is Linus

The youngest child is Linus


The youngest child is Linu

Arbitrary Keyword Arguments, **kwargs


If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function
definition.
This way the function will receive a dictionary of arguments, and can access the
items accordingly:

Example

If the number of keyword arguments is unknown, add a double ** before the


parameter name:

def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

His last name is Refsnes

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the
function:

def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

apple
banana
cherry
Return Values
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))

15​
25​
45

Recursion
Python also accepts function recursion, which means a defined function can call
itself.

Recursion is a common mathematical and programming concept. It means that


a function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.

Recursion Example Results:
1
3
6
10
15
21
Pass by Reference and Pass by Value
One important thing to note is, in Python every variable name is a reference.
When we pass a variable to a function Python, a new reference to the object
is created. Parameter passing in Python is the same as reference passing in
Java.
1
# Here x is a new reference to same list lst
2
def myFun(x):
3
x[0] = 20
4

5

6
# Driver Code (Note that lst is modified
7
# after function call.
8
lst = [10, 11, 12, 13, 14, 15]
9
myFun(lst)
10
print(lst)
Output:
[20, 11, 12, 13, 14, 15]

When we pass a reference and change the received reference to something


else, the connection between the passed and received parameters is broken.
For example, consider the below program as follows:
1
def myFun(x):
2

3
# After below line link of x with previous
4
# object gets broken. A new object is assigned
5
# to x.
6
x = [20, 30, 40]
7

8

9
# Driver Code (Note that lst is not modified
10
# after function call.
11
lst = [10, 11, 12, 13, 14, 15]
12
myFun(lst)
13
print(lst)
Output:
[10, 11, 12, 13, 14, 15]
Another example demonstrates that the reference link is broken if we assign
a new value (inside the function).
1
def myFun(x):
2

3
# After below line link of x with previous
4
# object gets broken. A new object is assigned
5
# to x.
6
x = 20
7

8

9
# Driver Code (Note that x is not modified
10
# after function call.
11
x = 10
12
myFun(x)
13
print(x)
Output:
10

Exercise: Try to guess the output of the following code.


1
def swap(x, y):
2
temp = x
3
x = y
4
y = temp
5

6
# Driver code
7
x = 2
8
y = 3
9
swap(x, y)
10
print(x)
11
print(y)
Output:
2
3

3. Scope of a Function in Python

In Python, scope refers to the region of the program where a variable is accessible.

●​ Local Scope: Variables defined within a function are only accessible inside that function
(local scope).
●​ Global Scope: Variables defined outside of all functions are accessible throughout the
code (global scope).
●​ Enclosing Scope: This refers to variables in the scope of an enclosing function (when
you have nested functions).
●​ Built-in Scope: The scope that contains all the built-in functions and exceptions (e.g.,
print, len, etc.).

Example:
x is global, y is in the enclosing scope, and z is local to inner_function.

4. Function Documentation in Python

Function documentation is typically provided using docstrings, which are string literals enclosed
in triple quotes (""" """) right after the function definition. This documentation describes what
the function does, its parameters, and its return value.

Example:
To access the documentation of a function, you can use the help() function:

Python Lambda
A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have
one expression.

It can take any number of arguments but can only have one expression. It is
generally used for short-lived, simple operations.

Syntax
lambda arguments : expression

The expression is executed and the result is returned:


x = lambda a: a + 10
print(x(5))

15

Lambda functions can take any number of arguments:

Example

Multiply argument a with argument b and return the result:

x = lambda a, b: a * b
print(x(5, 6))

30

Example
Summarize argument a, b, and c and return the result:

x = lambda a, b, c: a + b + c
print(x(5, 6, 2))

13
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous
function inside another function.

Say you have a function definition that takes one argument, and that argument
will be multiplied with an unknown number:

def myfunc(n):

return lambda a : a * n

Use that function definition to make a function that always doubles the number
you send in:

def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))

22

def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11))
print(mytripler(11))

22
33

Map Function

The map() function applies a given function to all items in an


iterable (like a list, tuple, etc.) and returns a map object (which
is an iterator). You can use map() with lambda functions to apply
operations to each element of the iterable.

Syntax:

map(function, iterable)

Debugging : Syntax Errors, Runtime Errors, Semantic


Errors, Experimental Debugging,
Debugging in Python refers to the process of identifying and fixing errors in your code.
There are three common types of errors:

1.​ Syntax Errors: These occur when the Python interpreter can't parse your code
because it doesn't follow proper syntax.
2.​ Runtime Errors: These occur during the execution of the program when
something goes wrong.
3.​ Semantic Errors: These occur when your code runs without crashing, but the
logic or behavior doesn't match what you intended.
4.​ Experimental Debugging: This involves using tools or methods (like print()
statements, debuggers, or logging) to investigate what's happening during
execution.

Let's go through each type of error with example code and how to debug them.

1. Syntax Errors

A syntax error occurs when the code doesn't follow Python's syntax rules. These errors
prevent the program from running.

Example:

Debugging:

The error message will indicate a syntax error, and in this case, it will tell you that the
closing parenthesis is missing. Fixing it is simple:
2. Runtime Errors

A runtime error occurs when the program starts but encounters an issue during
execution, such as dividing by zero or trying to access a variable that doesn't exist.

Example:

Debugging:

The runtime error occurs because division by zero is not allowed. The error message
would look like ZeroDivisionError: division by zero. To fix it, you can add a
check to avoid division by zero:
3. Semantic Errors

A semantic error occurs when the code runs without crashing, but it doesn't do what
you expect. The logic is wrong, even though the syntax is correct.

Example:

Debugging:

In the example above, the function calculates the circumference of a circle instead of
the area. The logic is incorrect. To fix it, you should return the area formula (π *
radius^2):
Strings:
A string is a sequence of characters that can be a combination of letters,
numbers, and special characters.
It can be declared in python by using single quotes, double quotes, or even
triple quotes.
These quotes are not a part of a string, they define only starting and
ending of the string.
Strings are immutable, i.e., they cannot be changed. Each element of the
string can be accessed using indexing or slicing operations.

Strings in python are surrounded by either single quotation marks, or


double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example

print("Hi")

print('Hi')

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed
by an equal sign and the string:

Example
a = "Hello"

print(a)

Multiline Strings
You can assign a multiline string to a variable by using three quotes:

Example

You can use three double quotes:

a = """Lorem ipsum dolor sit amet,

consectetur adipiscing elit,

sed do eiusmod tempor incididunt

ut labore et dolore magna aliqua."""

print(a)

Or three single quotes:

Example
a = '''Lorem ipsum dolor sit amet,

consectetur adipiscing elit,

sed do eiusmod tempor incididunt

ut labore et dolore magna aliqua.'''

print(a)

String Length
To get the length of a string, use the len() function.

Example

The len() function returns the length of a string:

a = "Hello, World!"

print(len(a))

Check String
To check if a certain phrase or character is present in a string, we can
use the keyword in.

Example
Check if "free" is present in the following text:

txt = "The best things in life are free!"

print("free" in txt)

Use it in an if statement:

Example

Print only if "free" is present:

txt = "The best things in life are free!"

if "free" in txt:

print("Yes, 'free' is present.")

Check if NOT
To check if a certain phrase or character is NOT present in a string, we
can use the keyword not in.

Example

Check if "expensive" is NOT present in the following text:

txt = "The best things in life are free!"


print("expensive" not in txt)

Use it in an if statement:

Example

print only if "expensive" is NOT present:

txt = "The best things in life are free!"

if "expensive" not in txt:

print("No, 'expensive' is NOT present.")

A String Is a Sequence,
Indexing:

●​ Each character in a string has an index. Indexing starts at 0


for the first character, 1 for the second, and so on. Negative
indexing starts from -1 for the last character, -2 for the
second last, etc.
Tuple

In Python, a tuple is an immutable, ordered


collection of items. It is similar to a list,
but unlike lists, the elements of a tuple
cannot be changed (immutable). Tuples are
typically used to group related data and are
defined using parentheses ().

Key Features of Tuples

1.​ Immutable: Once a tuple is created, you


cannot modify its elements.
2.​ Ordered: The elements in a tuple maintain
their order, and you can access them using
indices.
3.​ Allows Duplicates: Tuples can contain
duplicate values.
4.​ Heterogeneous: A tuple can store elements
of different data types.

Creating a Tuple
You can create a tuple using parentheses () or
without them (comma-separated values).

Accessing Elements

You can access elements in a tuple using


indexing and slicing.
Tuple Operations

1.​ Concatenation:

Repetition:

You might also like