Python Functions
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Python Functions

Kishore V

Python Functions

A function is a reusable block of code that performs a specific task. A function runs only when it is called, making programs more organized, readable, and efficient.

Functions help you:

  • Avoid repeating the same code
  • Break large programs into smaller parts
  • Make code easier to maintain and debug

Creating a Function

In Python, functions are created using the def keyword, followed by a function name and parentheses.

Syntax:

Example: Simple Function

# No output until the function is called

This defines a function named show_message. The code inside the function is indented to indicate it belongs to the function.

Calling a Function

A function does nothing until it is called. To call a function, write its name followed by parentheses.

Welcome to Python functions

Calling a Function Multiple Times

Hello, user! Hello, user! Hello, user!

Function Naming Rules

  • Must start with a letter or an underscore (_)
  • Can include letters, numbers, and underscores
  • Are case-sensitive
  • Should be descriptive and meaningful

Examples of Valid Function Names:
calculate_total()
_display_result()
checkStatus1()

Why Use Functions?

Without functions, repeating the same logic leads to messy and inefficient code.

Example: Without Using Functions

118.0 295.0 94.4

Using Functions for Reusability

118.0 295.0 94.4

Return Values in Functions

Functions can send data back using the return statement. Once return is executed, the function stops running.

Example: Function Returning a Value

Task completed

Using Returned Values Directly

36

Functions Without a Return Statement

If a function does not explicitly return a value, Python returns None by default.

This function has no return None

The pass Statement in Functions

A function definition cannot be empty. If you want to define a function but implement it later, use the pass statement.

# No output, but does not raise a SyntaxError

Function Arguments in Python

Arguments are values that you pass to a function so it can work with data. They are written inside the parentheses when calling a function. A function can accept one or more arguments, separated by commas.

Function with a Single Argument

Hello Aarav Hello Meera Hello Karan

Parameters vs Arguments

  • Parameter → The variable listed in the function definition
  • Argument → The actual value passed when calling the function
Welcome Ananya

Required Number of Arguments

By default, the number of arguments passed must match the number of parameters.

Correct Usage

Ravi Sharma

Incorrect Usage (Error)

TypeError: display_fullname() missing 1 required positional argument: 'last'

Default Parameter Values

You can assign default values to parameters. If no argument is provided, the default value is used.

Hello Neha Hello Guest
I live in Japan I live in India I live in Canada

Keyword Arguments

With keyword arguments, you specify the parameter name along with the value. This makes the order irrelevant.

Pet: cat Name: Luna

Positional Arguments

Arguments passed without keywords are called positional arguments. Their order matters.

Pet: dog Name: Rocky

Mixing Positional and Keyword Arguments

You can combine both types, but positional arguments must come first.

Buddy is a 4 year old dog

Passing Different Data Types as Arguments

milk bread eggs
Name: Amit City: Pune

Returning Values from Functions

20

Returning Different Data Types

['red', 'green', 'blue']
Width: 1920 Height: 1080

Positional-Only Arguments

You can restrict parameters to accept only positional arguments using /.

Hello Rahul

Keyword-Only Arguments

To allow only keyword arguments, use * before parameters.

Hello Rahul

Combining Positional-Only and Keyword-Only Arguments

50

Python *args and **kwargs

Python uses *args for variable positional arguments and **kwargs for variable keyword arguments.

Arbitrary Positional Arguments (*args)

All students: ('Arjun', 'Neha', 'Rohan') First student: Arjun
Data type: <class 'tuple'> 10 20 30 40

Using *args with Regular Parameters

Welcome Aman Welcome Kriti Welcome Sahil

Practical Uses of *args

12 100
19

Arbitrary Keyword Arguments (**kwargs)

When you prefix a parameter with **, the function can accept any number of keyword arguments (stored as a dictionary).

Profile data: {'name': 'Riya', 'age': 22, 'city': 'Jaipur'}
Type: <class 'dict'> Name: Kunal Country: India

Using **kwargs with Regular Parameters

Username: user_101 Other details: email = user@mail.com status = active

Combining *args and **kwargs

Title: Employee Info Positional data: ('Rahul', 'IT') Keyword data: {'age': 28, 'city': 'Noida'}

Unpacking Arguments

24
Welcome Amit Verma

Variable Scope in Python

In Python, a variable’s scope determines where that variable can be accessed in a program. Understanding scope helps prevent unexpected errors and makes your code easier to manage.

Local Scope

150

Accessing Local Variables in Nested Functions

Hello from outer function

Global Scope

100 100

Local vs Global Variables with Same Name

Inside function: 300 Outside function: 500

The global Keyword

Active
75

The nonlocal Keyword

Admin

The LEGB Rule

Inner: Local value Outer: Enclosing value Global: Global value

Python Decorators

A decorator allows you to add extra behavior to a function without modifying the function’s original code.

Basic Decorator Concept

GOOD MORNING
WELCOME USER SYSTEM READY

Decorating Functions with Arguments

HELLO AARAV
HELLO MEERA

Decorators with Their Own Arguments

hello python

Using Multiple Decorators

HI ROHAN

Preserving Function Metadata

wrapper
greet Returns a greeting message

Lambda Functions in Python

A lambda function is a small, unnamed function created using the lambda keyword.

15
28 18

Returning a Lambda from a Function

20 30

Lambda with Built-in Functions

[4, 16, 36, 64]
[12, 18, 25]
[{'name': 'Ben', 'score': 75}, {'name': 'Alex', 'score': 82}, {'name': 'Chris', 'score': 90}]
['java', 'python', 'go', 'csharp']

Recursion in Python

Recursion is a programming technique where a function calls itself to solve a problem by breaking it into smaller subproblems.

6 5 4 3 2 1 Finished!

Example: Factorial Using Recursion

720

Fibonacci Sequence Using Recursion

21

Using Recursion with Lists

20
21

Recursion Depth Limit in Python

1000
1500

Generators in Python

Generators are special functions that produce values one at a time and pause their execution between each value.

10 20 30
5 4 3 2 1
0 1 2

Using next() with Generators

Alice Bob Charlie
1 2

Generator Expressions

[0, 1, 4, 9] <generator object <genexpr> at 0x...> [0, 1, 4, 9]
385

Fibonacci Sequence Using a Generator

0 1 1 2 3 5 8 13 21 34

Advanced Generator Methods

Message received: Hi Message received: Python
Start Generator has stopped
Our website uses cookies to enhance your experience. Learn More
Accept !