Python Functions

Chapter 7 · Tamil Nadu State Board

  • 14 min read
  • 6-question quiz

Every key point below shows the sentence from your textbook it comes from. Book back answers are solved and checked against the book; answers we could not prove are left out. How we check content

In short

This lesson explains how Python functions group code for specific tasks, helping programs avoid repetition and become easier to manage. It teaches how to define and call functions, pass different kinds of arguments, and use return statements. It also covers variable scope, built-in and lambda functions, composition, and recursion. Understanding these ideas helps students write and reuse code and follow how functions work.

Written by AI from this lesson. How we check it

Key points

  • Functions are named code groups for specific jobs, and reusing them reduces repeated code.
    From your textbook
    “Functions are named blocks of code that are designed to do specific job.”
  • A function definition starts with def and uses parentheses, a colon, and an indented code block.
    From your textbook
    “Function blocks begin with the keyword “def” followed by function name and parenthesis ()”
  • Parameters belong to the function definition, while arguments are the values supplied when calling it.
    From your textbook
    “Parameters are the variables used in the function definition whereas arguments are the values we pass to the function parameters”
  • Function arguments include required, keyword, default, and variable-length types.
    From your textbook
    “Required arguments, Keyword arguments, Default arguments and Variable-length arguments.”
  • A local variable is usable only within its function, while a global variable can be used throughout the program.
    From your textbook
    “A variable, with global scope can be used anywhere in the program.”
  • Recursion happens when a function calls itself, and a base condition is needed to stop continued calls.
    From your textbook
    “A base condition is must in every recursive function otherwise it will continue to execute like an infinite loop.”
Test yourself: 6 questions

Formulas in this chapter

  • User-defined function syntaxdef <function_name ([parameter1, parameter2…] )> : <Block of Statements> return <expression / None>Explained here
  • Lambda function syntaxlambda [argument(s)] :expressionExplained here
  • return syntaxreturn [expression list ]Explained here

Python Functions and Their Types

Definition

Function
A function is a named group of related code statements that performs a specific task.

Call a function by using its name when you need its task performed. You can call it again instead of writing the same code repeatedly. Functions make programs easier to write, read, test, and fix.

Types of Python Functions

  • User-defined functions are defined by users.
  • Built-in functions are provided within Python.
  • Lambda functions are anonymous, or unnamed, functions.
  • Recursion functions call themselves.

Remember: Functions reduce repeated code and help divide a program into manageable modules.

Defining and Calling a Function

Start a function definition with def, followed by the function name and parentheses. Put any parameters inside the parentheses. Add a colon, then write the function's code as an indented block. Do not use a Python keyword as a function name.

User-defined function syntax

def <function_name ([parameter1, parameter2…] )> : <Block of Statements> return <expression / None>

function_name is the function's name; parameter1 and parameter2 are optional inputs. The indented statements are the function body. return sends an expression back, or returns None if there is no argument.

Definition

Block
A block is one or more lines of code grouped to run as a sequence, with every statement at the same indentation level.

Definition

Nested block
A nested block is a block placed inside another block.

The square brackets in the syntax mark optional text. To run a function, call it by writing its name followed by parentheses. A function can display output and return a value.

Worked example

Define and call a function that displays hello - Python.

Try it first, then show the solution
  1. Define the function with def hello():
  2. Put print (“hello - Python”) inside its indented block.
  3. Call it with hello().

Answer: The function displays hello - Python.

If you place a function call with no returned value inside print(), None is displayed as the last output.

Worked example

What is displayed by print (hello()) when hello() prints “hello - Python” and has no return argument?

Try it first, then show the solution
  1. Calling hello() displays hello - Python.
  2. The function has no return argument, so its returned value is None.
  3. The outer print() displays that returned value.

Answer: hello – Python None

Advantages of User-defined Functions

  • They divide a program into modules and make code easier to manage.
  • They allow code reuse by letting you call the function again.
  • They make it easier to change functionality, and different programmers can work on different functions.

Parameters, Arguments, and Function Arguments

Parameters and Arguments

ParametersArguments
Variables written in a function definition.Values passed to the function's parameters when calling it.

Worked example

Find the output of area(3,5) when area(w,h) returns w * h.

Try it first, then show the solution
  1. The call passes 3 to w and 5 to h.
  2. The function returns w * h.
  3. Calculate 3 * 5.

Answer: 15

Four Types of Function Arguments

  • Required arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments

Definition

Required arguments
Required arguments are passed in the correct positional order, and the number of arguments in the call must exactly match the function definition.

A function with a required parameter must receive a value for it. Calling printstring() without a value for str causes a TypeError. Calling printstring (“Welcome”) passes the needed value.

Worked example

What happens when printstring(str) is called as printstring()?

Try it first, then show the solution
  1. The function definition requires the positional argument str.
  2. The call provides no argument.

Answer: Python raises a TypeError because the required positional argument 'str' is missing.

Worked example

What is displayed by printstring (“Welcome”) if the function prints “Example - Required arguments ” and then prints str?

Try it first, then show the solution
  1. The call passes “Welcome” as the value of str.
  2. The function prints its message and then the value of str.

Answer: Example - Required arguments Welcome

Remember: For required arguments, provide the correct number of values in the correct positional order.

Keyword Arguments

A keyword argument matches a value to a parameter by using the parameter’s name. You can write keyword arguments in a different order from the parameters in the function definition, as long as the names match.

Worked example

Call printdata with the parameter name set to “Gshan”.

Try it first, then show the solution
  1. The function parameter is named name.
  2. Call the function with printdata(name = “Gshan”).

Answer: The function prints Name :Gshan.

Correct and incorrect keyword names

CallResult
printdata(name = “Gshan”)The value matches the name parameter.
printdata(name1 = “Gshan”)TypeError: printdata() got an unexpected keyword argument 'name1'

Worked example

Call printdata(name, age) with the arguments in a different order.

Try it first, then show the solution
  1. The parameters are name and age.
  2. Call printdata (age=25, name="Gshan").
  3. Python matches each value to its parameter name.

Answer: The function prints Name : Gshan and Age : 25.

Default and Variable-Length Arguments

Definition

Default argument
An argument with a default value uses that value when the function call does not provide one.

Worked example

What does printinfo(“Mani”) print when salary has the default value 3500?

Try it first, then show the solution
  1. The call provides a value for name but not for salary.
  2. The function uses the default salary value.

Answer: Name: Mani; Salary: 3500.

If a call supplies a value for an argument with a default, the supplied value is used instead. For example, printinfo(“Ram”,2000) prints Name: Ram and Salary: 2000. The default value 3500 is ignored for that call.

Definition

Variable-length arguments
Variable-length arguments let a function receive more arguments than are specified as individual parameters in its definition.

An asterisk (*) marks variable-length arguments in a function definition. For example, def printnos (*nos): lets the function process the values in nos one by one. Variable-length arguments can be non-keyword or keyword arguments.

Two ways to pass arguments

TypeWhat to know
Non-keyword variable argumentsThese are called tuples.
Keyword variable argumentsThese are beyond the scope of this book.

Worked example

What happens when sum(x,y,z) is called as sum(5,10,15,20,25)?

Try it first, then show the solution
  1. The function definition has three parameters: x, y and z.
  2. The call provides five arguments.

Answer: TypeError: sum() takes 3 positional arguments but 5 were given.

Remember: Use *args-style syntax when a function needs to accept a variable number of non-keyword arguments.

Anonymous Functions and Lambda

Definition

Anonymous function
An anonymous function is a function defined without a name, using the lambda keyword.

Lambda functions are mainly used for small, one-time functions. They are also used with filter(), map() and reduce(). A lambda function can take any number of arguments, but it must return one value as an expression.

Lambda function syntax

lambda [argument(s)] :expression

The arguments provide values for the expression, which produces the function’s value.

Worked example

Find the outputs of sum(30,40) and sum(-30,40) when sum = lambda arg1, arg2: arg1 + arg2.

Try it first, then show the solution
  1. For sum(30,40), add 30 and 40.
  2. For sum(-30,40), add -30 and 40.

Answer: The outputs are 70 and 10.

The return Statement and Variable Scope

Definition

return statement
A return statement ends a function’s work and sends a value back to the caller.

A function can contain more than one return statement, but only one is executed during a particular run. The expression after return is evaluated and its value is sent back. If return has no expression, or the function has no return statement, the function returns the None object.

return syntax

return [expression list ]

The optional expression list provides the value sent back to the caller.

Worked example

What does usr_abs return for 25 and -25?

Try it first, then show the solution
  1. If n>=0, usr_abs returns n.
  2. Otherwise, usr_abs returns –n.

Answer: usr_abs returns 25 for both 25 and -25.

Definition

Scope of a variable
The scope of a variable is the part of a program where the variable can be used.

Types of scope introduced

  • Local scope
  • Global scope

Local Scope in Python

Definition

Local variable
A variable declared inside a function body is local to that function.

Rules for local variables

  • A local variable can be accessed only inside the function where it is created.
  • It exists only while that function is executing.
  • Formal parameters are also local to a function.

In loc(), y is created inside the function, so print(y) inside loc() displays 0. If you call loc() and then try print(y) outside it, Python gives NameError: name 'y' is not defined. The variable y is not available in the global scope.

Remember: A local variable stays within its function and cannot be accessed from outside it.

Global Scope and the global Keyword

Definition

Global variable
A variable defined outside all functions has global scope and can be used anywhere in the program.

Rules for global variables

  • A variable defined outside a function is global by default.
  • A function can access a global variable without using the global keyword.
  • Use the global keyword inside a function when you want to modify a global variable.
  • Using global outside a function has no effect.

If c = 1 is defined outside add(), print(c) inside add() displays 1. But assigning c = c + 2 inside the function without declaring it global causes UnboundLocal Error: local variable 'c' referenced before assignment.

If x = 0 is defined outside add() and the function uses global x, the function can change x to 5. The value is 5 both inside add() and after the function call.

Remember: Use global inside a function to change a global variable; access alone does not require it.

Built-in Python Functions

Common built-in functions

FunctionWhat it does
abs(x)Returns the absolute value of a number.
ord(c)Returns the ASCII value for a given Unicode character.
chr(i)Returns the Unicode character for a given ASCII value.
bin(i)Returns a binary string with the prefix “0b”.
type(object)Returns the type of a single object.
id(object)Returns the identity of an object, described as its address in memory.
min(list)Returns the smallest value in a list.
max(list)Returns the largest value in a list.
sum(list)Returns the total of the values in a list.
format(value [, format_spec])Formats a value, including as binary, octal, or fixed-point.

For example, abs(-23.2) returns 23.2, and bin(15) returns 0b1111. format(25,'o') gives 31, while format(25,'f') gives 25.000000. round(17.9) gives 18, and pow(5,2) gives 25.

Mathematical Functions from the math Module

Import the math module before using its mathematical functions. Write the function name with math. before it, such as math.floor(x).

math functions

FunctionWhat it returns
math.floor(x)The largest integer less than or equal to x.
math.ceil(x)The smallest integer greater than or equal to x.
math.sqrt(x)The square root of x. x must be greater than 0 (zero).

For positive and negative values, floor and ceil move to different nearby integers. For example, math.floor(-26.7) returns -27, while math.ceil(-26.7) returns -26. math.sqrt(49) returns 7.0.

Remember: Import math before calling math.floor(), math.ceil(), or math.sqrt().

Composition in Python functions

Definition

Composition
Composition is using the value returned by one function as an argument for another function.

Functions can be nested this way. For example, input() gets a value as a string, and eval() evaluates that value as a number or expression.

Worked example

Get a number and an arithmetic expression from the user using input() and eval().

Try it first, then show the solution
  1. n1 = eval(input("Enter a number: "))
  2. If the user enters 234, n1 is 234.
  3. n2 = eval(input("Enter an arithmetic expression: "))
  4. If the user enters 12.0+13.0 * 2, n2 is 38.0.

Answer: The return value of input() is passed to eval() for evaluation.

Recursive functions and base conditions

Definition

Recursion
Recursion happens when a function calls itself.

Definition

Base condition
A base condition is the condition that stops a recursive function from calling itself further.

Recursion can work like a loop. A recursive function must have a base condition. Without one, it can keep running like an infinite loop.

How a recursive function works

  • Some external code calls the recursive function.
  • If the base condition is met, the function gives an output and exits.
  • Otherwise, the function processes the task and calls itself again.

Worked example

Use a recursive function to calculate factorial.

Try it first, then show the solution
  1. Define fact(n).
  2. If n == 0, return 1.
  3. Otherwise, return n * fact(n-1).
  4. print(fact (0)) gives 1.
  5. print(fact (5)) gives 120.

Answer: The function calculates factorial by calling itself with n-1 until n == 0.

print(fact (2000)) gives a Recursion Error after the maximum recursion depth is exceeded in comparison. Python stops calling a recursive function after 1000 calls by default. The limit can be changed using sys.setrecursionlimit (limit_value).

Worked example

Set the recursion limit to 3000 before calculating fact (2000).

Try it first, then show the solution
  1. Use import sys.
  2. Set sys.setrecursionlimit(3000).
  3. Define fact(n) with the base condition n == 0 and the recursive return n * fact(n-1).
  4. Call print(fact (2000)).

Answer: The code sets the recursion limit to 3000 and then calls the factorial function.

Remember: Every recursive function needs a base condition so it can stop.

Key ideas about Python functions

Function basics

  • A function is a named block of code designed to do one specific job.
  • Function types include User defined, Built-in, lambda and recursion.
  • A function block begins with the keyword def, followed by the function name and parentheses ().
  • Python statements in a block begin with indentation. A block inside another block is a nested block.
  • A return with no arguments is the same as return None. The return statement is optional.

Types of function arguments

Argument typeHow it works
Required argumentsPassed in the correct positional order.
Keyword argumentsThe function uses parameter names to identify the arguments.
Default argumentsUse default values given for parameters in the function definition.
Variable-length argumentsAre not specified in the function definition; an asterisk (*) is used to define them.

Definition

Anonymous Function
An anonymous function is a function defined without a name.

Definition

Scope of a variable
The scope of a variable is the part of a program where that variable can be used.

Questions students ask

Short, direct answers to what students search for in this chapter.

What is a function in Python?

A function in Python is a named group of related code statements that performs a specific task. You run its code by calling the function's name. Reusing a function avoids writing the same task repeatedly and helps make programs easier to write, read, test, and fix.

What are the four types of Python functions?

The four types are user-defined functions, built-in functions, lambda functions, and recursion functions. Users define user-defined functions. Python provides built-in functions. Lambda functions are anonymous, or unnamed. Recursion functions call themselves.

What is the difference between parameters and arguments in Python?

Parameters are the variables written inside a function definition. Arguments are the values supplied to those parameters when the function is called. For example, in area(w,h), w and h are parameters; in area(3,5), 3 and 5 are arguments.

What are required arguments in Python?

Required arguments must be passed in the correct positional order when calling a function. The number of arguments in the call must match the function definition. If a required parameter is missing, the call raises a TypeError, as when printstring() is called without a value for str.

What is a keyword argument in Python?

A keyword argument gives a value using a parameter’s name, such as name = “Gshan”. Python matches the value to the named parameter. This means keyword arguments can be written in a different order, but the name used must match a parameter.

What is a default argument in Python?

A default argument has a value already assigned in the function definition. If a function call does not provide a value for that argument, the default is used. If the call provides a value, that value is used instead of the default.

Show 13 more questions

How do variable-length arguments work in Python?

Variable-length arguments allow a function to receive a changing number of arguments. An asterisk (*) is used in the function definition, as in def printnos (*nos):. The function can then process the received values one by one.

What is a lambda function in Python?

A lambda function is an anonymous function, which means it is defined without a name. It uses the lambda keyword and is mainly used for small, one-time functions. It can take any number of arguments and must return one value as an expression.

What happens if a Python function has no return statement?

If a function has no return statement, it returns the None object. The same happens when a return statement is present but has no expression. When a function has multiple return statements, only one of them is executed during a particular run.

What is a local variable in Python?

A local variable is declared inside a function body. It can be accessed only within the function where it is created, and it exists only while that function is executing. Formal parameters are also local to a function.

How do you modify a global variable inside a Python function?

Use the global keyword for that variable inside the function before modifying it. Without global, assigning to a name inside the function makes Python treat it as local, which can cause an UnboundLocal Error when its value is read first.

What does the Python function abs() do?

abs() returns the absolute value of a number. Its argument can be an integer or a floating point number. For example, abs(-23.2) returns 23.2, while abs(20) returns 20.

What is the difference between math.floor() and math.ceil()?

math.floor(x) returns the largest integer less than or equal to x. math.ceil(x) returns the smallest integer greater than or equal to x. For example, math.floor(-26.7) returns -27, and math.ceil(-26.7) returns -26.

How do you find the square root of a number in Python?

Import the math module, then call math.sqrt(x). The value of x must be greater than 0 (zero). For example, math.sqrt(49) returns 7.0.

What is composition in Python functions?

Composition is using the value returned by one function as an argument for another function. For example, input() can get a value from the user, and eval() can evaluate that returned value as a number or expression.

What is recursion in Python?

Recursion happens when a function calls itself. The function can do some processing and then call itself again. It needs a base condition to stop the repeated calls and return an output.

Why does a recursive function need a base condition?

A base condition tells a recursive function when to stop calling itself. Without this condition, the function can continue like an infinite loop. When the base condition is met, the function gives an output and exits.

How do you change the recursion limit in Python?

Use sys.setrecursionlimit (limit_value) to change the recursion limit. For example, import sys and use sys.setrecursionlimit(3000). Python stops calling a recursive function after 1000 calls by default.

What are the types of arguments in Python functions?

The four types are Required arguments, Keyword arguments, Default arguments and Variable-length arguments. Required arguments use the correct positional order. Keyword arguments use parameter names, Default arguments use values given in the definition, and Variable-length arguments use an asterisk (*).

Book back answers

24 textbook exercises, solved and checked against the book. Questions we could not prove are left out.

Choose the best answer: (1 Mark)

  1. A named blocks of code that are designed to do one specific job is called as

    • (a) Loop
    • (b) Branching
    • (c) Function
    • (d) Block
    Try it, then show the answer

    (c) Function

    Functions are named blocks of code designed to do a specific job.

    From the book: “Functions are named blocks of code that are designed to do specific job.”

  2. A Function which calls itself is called as

    • (a) Built-in
    • (b) Recursion
    • (c) Lambda
    • (d) return
    Try it, then show the answer

    (b) Recursion

    A function that calls itself is known as recursion.

    From the book: “When a function calls itself is known as recursion.”

  3. Which function is called anonymous un-named function

    • (a) Lambda
    • (b) Recursion
    • (c) Function
    • (d) define
    Try it, then show the answer

    (a) Lambda

    Anonymous functions are also called lambda functions.

    From the book: “Hence, anonymous functions are also called as lambda functions.”

  4. Which of the following keyword is used to begin the function block?

    • (a) define
    • (b) for
    • (c) finally
    • (d) def
    Try it, then show the answer

    (d) def

    A function block begins with the keyword def.

    From the book: “Function blocks begin with the keyword “def””

All 24 book back answers →

Practice

Question 1 of 6Score 0

What does a function help a program do?

Exam questions

Practice questions with model answers. These are not from an official paper.

What is a function, and give one advantage of using functions.2 marks

A function is a named block of code designed for a specific job. Functions avoid repetition and allow code to be reused.

Differentiate between a parameter and an argument.2 marks

A parameter is a variable in a function definition. An argument is a value passed to that parameter when the function is called.

Name the four types of function arguments described in this lesson.2 marks

Required arguments, keyword arguments, default arguments, and variable-length arguments.

What is recursion, and why does a recursive function need a base condition?2 marks

Recursion occurs when a function calls itself. A base condition is needed to stop the calls; without it, the function may continue like an infinite loop.

Watch out

  • Do not confuse parameters, which appear in the function definition, with arguments, which are passed in a function call.
  • Do not assume a global variable can be modified inside a function without using the global keyword.

Still stuck on this lesson?

Get an AI answer grounded in your actual textbook — with the exact page reference.

Ask AI about this topic →