![]() |
VOOZH | about |
The def keyword is used to define user-defined functions. Functions help organize code into reusable blocks, making programs easier to read, maintain, and reuse. They can accept input values through parameters, perform specific tasks and optionally return results.
Example:
Hello
Explanation:
The below diagram shows the basic structure of a Python function, including its name, parameters, body, and optional return value.
👁 Python def Keyworddef function_name(parameters):
# Code to execute
return value # Optional
Note: Defining a function using def does not execute it immediately. The function runs only when it is called using its name followed by parentheses.
Example 1: In this example, we create a function sub() using the def keyword, which calculates the difference between two numbers.
subtraction of 90 and 50 is 40
Explanation:
Example 2: In this example, we define a user-defined function fun() using the def keyword. The function takes a parameter n and prints the first n prime numbers.
2 3 5 7 11 13 17 19 23 29
Explanation:
Default arguments allow a function parameter to have a predefined value. If no argument is provided during the function call, the default value is used automatically.
Hello Guest Hello Alice
Explanation:
In Python, functions are first-class objects, which means you can pass functions as arguments to other functions, allowing you to call it inside that function.
25
Explanation:
*args allows a function to accept a variable number of positional arguments, which are collected into a tuple, making the function flexible to handle multiple inputs.
1 2 3 4 5
Explanation:
**kwargs lets a function accept any number of keyword arguments. These arguments are collected into a dictionary, with keys as argument names and values as their corresponding values.
name: Olivia age: 30 city: New York
Explanation:
Inside a class, functions are called methods. You define them using def just like regular functions, but they usually take self as the first parameter to access the object’s attributes and other methods.
Name - Harry and Age - 30.
Explanation: