Python

Python Functions and Variable Scope, CBSE Class 11 Complete Guide

Complete guide to Python functions for CBSE Class 11 CS. Covers function definition, arguments, return values, default args, local/global scope with examples.

Functions are one of the most important topics in CBSE Class 11 Python programming. They help you organize code into reusable blocks, making programs easier to write, read, and maintain. This guide covers everything about functions and variable scope for your exam.

What is a Function?

A function is a named block of organized, reusable code that performs a specific task. Functions allow you to break your program into smaller, manageable pieces.

Advantages of Functions

  1. Code reusability - Write once, use many times
  2. Modularity - Break large programs into smaller parts
  3. Easy maintenance - Fix bugs in one place
  4. Readability - Code is easier to understand
  5. Avoid repetition - Follow the DRY (Don't Repeat Yourself) principle

Types of Functions

Type Description Examples
Built-in Functions Pre-defined in Python print(), len(), input(), type()
Module Functions Defined in Python modules math.sqrt(), random.randint()
User-defined Functions Created by the programmer Functions you write

Common Built-in Functions

# Type conversion
print(int("25"))       # 25
print(float("3.14"))   # 3.14
print(str(100))        # "100"

# Math functions
print(abs(-15))        # 15
print(max(10, 20, 5))  # 20
print(min(10, 20, 5))  # 5
print(round(3.67))     # 4
print(round(3.14159, 2))  # 3.14
print(pow(2, 5))       # 32

# String functions
print(len("Hello"))    # 5

# Type checking
print(type(42))        # <class 'int'>
print(type("Hi"))      # <class 'str'>
25
3.14
100
15
20
5
4
3.14
32
5
<class 'int'>
<class 'str'>

Defining a Function

Syntax

def function_name(parameters):
    """docstring (optional)"""
    # function body
    return value  # optional

Parts of a Function

Part Purpose
def Keyword to define a function
function_name Name of the function (follows naming rules)
parameters Input values the function accepts (optional)
docstring Documentation string describing the function (optional)
function body Statements that execute when function is called
return Sends a value back to the caller (optional)

Simple Function Example

def greet():
    print("Hello, welcome to Python!")

# Calling the function
greet()
greet()
Hello, welcome to Python!
Hello, welcome to Python!

Function Arguments (Parameters)

Parameters vs Arguments

  • Parameters are the variables listed in the function definition
  • Arguments are the actual values passed when calling the function
def add(a, b):    # a, b are parameters
    return a + b

result = add(5, 3)  # 5, 3 are arguments
print(result)
8

Types of Arguments

1. Positional Arguments

Arguments are matched to parameters by their position:

def introduce(name, age, city):
    print(f"I am {name}, {age} years old, from {city}")

introduce("Aman", 16, "Delhi")
introduce("Priya", 15, "Mumbai")
I am Aman, 16 years old, from Delhi
I am Priya, 15 years old, from Mumbai

Order matters! If you swap the arguments, the output will be wrong.

2. Default Arguments

Parameters can have default values. If no argument is provided, the default is used:

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Aman")                  # Uses default greeting
greet("Priya", "Good morning") # Overrides default
Hello, Aman!
Good morning, Priya!

Important rule: Default arguments must come AFTER non-default arguments.

# CORRECT
def func(a, b, c=10):
    pass

# WRONG - SyntaxError
# def func(a, b=5, c):
#     pass

3. Keyword Arguments

Arguments are passed with the parameter name, so order does not matter:

def student_info(name, class_name, roll_no):
    print(f"Name: {name}, Class: {class_name}, Roll: {roll_no}")

# Using keyword arguments (order doesn't matter)
student_info(roll_no=15, name="Aman", class_name="11A")
Name: Aman, Class: 11A, Roll: 15

4. Variable-Length Arguments (*args)

When you don't know how many arguments will be passed:

def total(*numbers):
    result = 0
    for num in numbers:
        result += num
    return result

print(total(1, 2, 3))
print(total(10, 20, 30, 40, 50))
6
150

The Return Statement

The return statement sends a value back to the caller and ends the function.

Returning a Single Value

def square(n):
    return n * n

result = square(7)
print("Square:", result)
Square: 49

Returning Multiple Values

Python functions can return multiple values as a tuple:

def calculate(a, b):
    add = a + b
    sub = a - b
    mul = a * b
    return add, sub, mul

s, d, p = calculate(10, 3)
print("Sum:", s)
print("Difference:", d)
print("Product:", p)
Sum: 13
Difference: 7
Product: 30

Function Without Return

If a function does not have a return statement, it returns None:

def say_hello(name):
    print(f"Hello, {name}!")

result = say_hello("Aman")
print("Returned:", result)
Hello, Aman!
Returned: None

Variable Scope

Scope determines where a variable can be accessed in the program.

Local Variables

A local variable is created inside a function and can only be used inside that function:

def my_function():
    x = 10  # local variable
    print("Inside function:", x)

my_function()
# print(x)  # This would cause an ERROR - x is not defined outside
Inside function: 10

Global Variables

A global variable is created outside all functions and can be accessed everywhere:

x = 50  # global variable

def my_function():
    print("Inside function:", x)  # Can read global variable

my_function()
print("Outside function:", x)
Inside function: 50
Outside function: 50

The global Keyword

To modify a global variable inside a function, use the global keyword:

count = 0  # global variable

def increment():
    global count
    count = count + 1
    print("Count inside:", count)

increment()
increment()
increment()
print("Count outside:", count)
Count inside: 1
Count inside: 2
Count inside: 3
Count outside: 3

Without the global keyword, Python would create a new local variable instead of modifying the global one:

count = 0

def increment():
    count = count + 1  # ERROR! UnboundLocalError
    print(count)

# increment()  # This would cause an error

Name Resolution (LEGB Rule)

When Python encounters a variable name, it searches in this order:

Level Name Description
L Local Inside the current function
E Enclosing Inside enclosing functions (nested functions)
G Global At the module level
B Built-in Python's built-in names
x = "global"

def outer():
    x = "enclosing"

    def inner():
        x = "local"
        print(x)  # Prints "local"

    inner()
    print(x)  # Prints "enclosing"

outer()
print(x)  # Prints "global"
local
enclosing
global

Practical Function Examples

Example 1: Check if a number is prime

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

num = int(input("Enter a number: "))
if is_prime(num):
    print(num, "is prime")
else:
    print(num, "is not prime")
Enter a number: 29
29 is prime

Example 2: Calculate factorial using recursion

def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

print("5! =", factorial(5))
print("7! =", factorial(7))
5! = 120
7! = 5040

Example 3: Fibonacci series

def fibonacci(n):
    a, b = 0, 1
    series = []
    for i in range(n):
        series.append(a)
        a, b = b, a + b
    return series

result = fibonacci(10)
print("Fibonacci:", result)
Fibonacci: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Example 4: Count vowels in a string

def count_vowels(text):
    vowels = "aeiouAEIOU"
    count = 0
    for char in text:
        if char in vowels:
            count += 1
    return count

sentence = "Hello World, Welcome to Python"
print("Vowels:", count_vowels(sentence))
Vowels: 9

Example 5: Function with multiple return values

def analyze_list(numbers):
    total = sum(numbers)
    average = total / len(numbers)
    maximum = max(numbers)
    minimum = min(numbers)
    return total, average, maximum, minimum

marks = [85, 92, 78, 95, 88, 70, 83]
s, avg, mx, mn = analyze_list(marks)
print(f"Total: {s}")
print(f"Average: {avg:.2f}")
print(f"Highest: {mx}")
print(f"Lowest: {mn}")
Total: 591
Average: 84.43
Highest: 95
Lowest: 70

Important Questions

Q1. What is the difference between parameters and arguments?

Parameters are the variables listed in the function definition that act as placeholders. Arguments are the actual values passed to the function when it is called. For example, in def add(a, b), a and b are parameters. In add(5, 3), 5 and 3 are arguments.

Q2. Explain local and global variables with an example.

A local variable is defined inside a function and can only be accessed within that function. A global variable is defined outside all functions and can be accessed anywhere in the program. To modify a global variable inside a function, you must use the global keyword.

Q3. What is the difference between return and print in a function?

return sends a value back to the caller and can be stored in a variable for further use. print simply displays output on the screen but does not send any value back. A function with return can be used in expressions like result = add(5, 3), while a function with only print always returns None.

Q4. What are default arguments? Give an example.

Default arguments have pre-defined values in the function definition. If no argument is provided for that parameter when calling the function, the default value is used. Default arguments must be placed after non-default arguments. Example: def greet(name, msg="Hello") - calling greet("Aman") uses the default message "Hello".

Quick Revision

  • def keyword defines a function
  • Parameters = in definition; Arguments = in function call, Types of arguments: Positional, Default, Keyword, Variable-length (*args)
  • return sends value back; without it, function returns None
  • Local variable = inside function; Global variable = outside function, Use global keyword to modify a global variable inside a function
  • LEGB rule: Local > Enclosing > Global > Built-in, Default arguments must come AFTER non-default arguments, Functions can return multiple values as a tuple

Want to learn more?

Explore free chapter-wise notes with quizzes and code playground

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube