Python def Keyword Last Updated : 27 Dec, 2024 Comments Improve Suggest changes Like Article Like Report Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In Python, a function is a logical unit of code containing a sequence of statements indented under a name given using the “def” keyword. In Python def keyword is the most used keyword.Example: Python # defining function def func(): print("Hello") # calling function func() OutputHello Let's explore python def keyword in detail:Table of ContentPython def SyntaxPassing Function as an ArgumentPython def keyword example with *argsPython def keyword example with **kwargsPython def keyword example with the classPython def Syntaxdef function_name: function definition statements...Use of def keywordIn the case of classes, the def keyword is used for defining the methods of a class.def keyword is also required to define the special member function of a class like __init__().The possible practical application is that it provides the feature of code reusability rather than writing the piece of code again and again we can define a function and write the code inside the function with the help of the def keyword. It will be more clear in the illustrated example given below. There can possibly be many applications of def depending upon the use cases.Example 1: Create function to find the subtraction of two NumbersIn this example, we have created a user-defined function using the def keyword. Function name is subNumbers() which calculates the differences between two numbers. Python # Python3 code to demonstrate # def keyword # function for subtraction of 2 numbers. def subNumbers(x, y): return (x-y) # main code a = 90 b = 50 # finding subtraction res = subNumbers(a, b) # print statement print("subtraction of ", a, " and ", b, " is ", res) Outputsubtraction of 90 and 50 is 40 Example 2: Create function with the first 10 prime numbersIn this example, we have created a user-defined function using the def keyword. The program defines a function called fun() using the def keyword. The function takes a single parameter n, which specifies the number of prime numbers to be printed. Python # Python program to print first 10 prime numbers # A function name prime is defined # using def def fun(n): x = 2 count = 0 while count < n: for d in range(2, int(x ** 0.5) + 1): # check divisibility only up to sqrt(x) if x % d == 0: break # if divisible, it's not prime, so break the loop else: print(x) # prime number count += 1 x += 1 # Driver Code n = 10 fun(n) Output2 3 5 7 11 13 17 19 23 29 Passing Function as an ArgumentIn Python, we can pass functions as arguments to other functions. We can pass a function by simply referencing its name without parentheses. The passed function can then be called inside the receiving function.Example: Python # A function that takes another function as an argument def fun(func, arg): return func(arg) def square(x): return x ** 2 # Calling fun and passing square function as an argument res = fun(square, 5) print(res) Output25 Explanation:This function takes two parameters: func (a function) and x (a value). It applies the function func to the value x and returns the result.We call fun and pass the square function (without parentheses) and the number 5. The square function is applied to 5, and the result is printed.Python def keyword example with *argsIn Python, *args is used to pass a variable number of arguments to a function. The * allows a function to accept any number of positional arguments. This is useful when we are not sure how many arguments will be passed to the function.Example: Python def fun(*args): for arg in args: print(arg) # Calling the function with multiple arguments fun(1, 2, 3, 4, 5) Output1 2 3 4 5 Python def keyword example with **kwargsIn Python, **kwargs is used to pass a variable number of keyword arguments to a function. The ** syntax collects the keyword arguments into a dictionary, where the keys are the argument names and the values are the corresponding argument values. This allows the function to accept any number of named (keyword) arguments. Python def fun(**kwargs): for k, val in kwargs.items(): print(f"{k}: {val}") # Calling the function with keyword arguments fun(name="Alice", age=30, city="New York") Outputname: Alice age: 30 city: New York Explanation:**kwargs collects the keyword arguments passed to example_function into a dictionary kwargs.Inside the function, you can iterate over the dictionary and print the key-value pairs.Python def keyword example with the classIn Python, the def keyword is used to define functions and it can also be used to define methods inside a class. A method is a function that is associated with an object and is called using the instance of the class.When using def inside a class, we can define methods that can access and modify the attributes of the class and its instances. Python class Person: # Constructor to initialize the person's name and age def __init__(self, name, age): self.name = name # Set the name attribute self.age = age # Set the age attribute # Method to print a greeting message def greet(self): print(f"Name - {self.name} and Age - {self.age}.") # Create an instance of the Person class p1 = Person("Alice", 30) # Call the greet method to display the greeting message p1.greet() OutputName - Alice and Age - 30. Comment More infoAdvertise with us Next Article Difference between Method and Function in Python A amitgupta700 Follow Improve Article Tags : Python Python-Functions python-basics Practice Tags : pythonpython-functions Similar Reads Python Functions Python Functions is a block of statements that does a specific task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over an 9 min read Python def Keyword Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In Python, a function is a logical unit of code containing a sequence of statements indented under a name given using the âdefâ keyword. In Python def 6 min read Difference between Method and Function in Python Here, key differences between Method and Function in Python are explained. Java is also an OOP language, but there is no concept of Function in it. But Python has both concept of Method and Function. Python Method Method is called by its name, but it is associated to an object (dependent).A method d 3 min read First Class functions in Python First-class function is a concept where functions are treated as first-class citizens. By treating functions as first-class citizens, Python allows you to write more abstract, reusable, and modular code. This means that functions in such languages are treated like any other variable. They can be pas 2 min read Assign Function to a Variable in Python In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability.Example:Python# defining a function def a(): print( 3 min read User-Defined FunctionsPython User Defined FunctionsA User-Defined Function (UDF) is a function created by the user to perform specific tasks in a program. Unlike built-in functions provided by a programming language, UDFs allow for customization and code reusability, improving program structure and efficiency.Example:Python# function defination def 6 min read Python User Defined FunctionsA User-Defined Function (UDF) is a function created by the user to perform specific tasks in a program. Unlike built-in functions provided by a programming language, UDFs allow for customization and code reusability, improving program structure and efficiency.Example:Python# function defination def 6 min read Python | How to get function name ?One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to 3 min read Python | How to get function name ?One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to 3 min read Defining a Python Function at RuntimeOne amazing feature of Python is that it lets us create functions while our program is running, instead of just defining them beforehand. This makes our code more flexible and easier to manage. Itâs especially useful for things like metaprogramming, event-driven systems and running code dynamically 3 min read Call a function by a String name - PythonIn this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let's say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between 3 min read Explicitly define datatype in a Python functionUnlike other programming languages such as Java and C++, Python is a strongly, dynamically-typed language. This means that we do not have to explicitly specify the data type of function arguments or return values. Python associates types with values rather than variable names. However, if we want to 4 min read Built-in and Special FunctionsPython Built in FunctionsPython is the most popular programming language created by Guido van Rossum in 1991. It is used for system scripting, software development, and web development (server-side). Web applications can be developed on a server using Python. Workflows can be made with Python and other technologies. Databas 6 min read Python Lambda FunctionsPython Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. In the example, we defined a lambda function(u 6 min read filter() in pythonThe filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Let's see a simple example of filter() function in python:Example Usage of filter()Python# Function to check if a number is even def even(n): return n % 2 == 0 a = [1 3 min read Python map() functionThe map() function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a map object (which is an iterator). Let's start with a simple example of using map() to convert a list of strings into a list of integers.Pythons = ['1', '2', '3', '4'] res = map( 4 min read reduce() in PythonThe reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. This function is defined in "functools" module.Basic Example:Letâs start with a simple example where we sum up all numbers in a list.Pythonfr 4 min read Global and Local VariablesGlobal keyword in PythonThe global keyword in Python allows a function to modify variables that are defined outside its scope, making them accessible globally. Without it, variables inside a function are treated as local by default. It's commonly used when we need to update the value of a global variable within a function, 4 min read Python Scope of VariablesIn Python, variables are the containers for storing data values. Unlike other languages like C/C++/JAVA, Python is not âstatically typedâ. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. Python Scope variabl 5 min read Accessing Python Function Variable Outside the FunctionIn Python, function variables have local scope and cannot be accessed directly from outside. However, their values can still be retrieved indirectly. For example, if a function defines var = 42, it remains inaccessible externally unless retrieved indirectly.Returning the VariableThe most efficient w 4 min read Parameters and ArgumentsPython Function Parameters and ArgumentsParameters are variables defined in a function declaration. This act as placeholders for the values (arguments) that will be passed to the function. Arguments are the actual values that you pass to the function when you call it. These values replace the parameters defined in the function. Although t 3 min read Keyword and Positional Argument in PythonPython provides different ways of passing the arguments during the function call from which we will explore keyword-only argument means passing the argument by using the parameter names during the function call.Types of argumentsKeyword-only argumentPositional-only argumentDifference between the Key 4 min read How to find the number of arguments in a Python function?Finding the number of arguments in a Python function means checking how many inputs a function takes. For example, in def my_function(a, b, c=10): pass, the total number of arguments is 3. Some methods also count special arguments like *args and **kwargs, while others only count fixed ones.Using ins 4 min read Default arguments in PythonPython allows function arguments to have default values. If the function is called without the argument, the argument gets its default value.Default Arguments: Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argum 7 min read Passing function as an argument in PythonIn Python, functions are first-class objects meaning they can be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, decorators and lambda expressions. By passing a function as an argument, we can modify a functionâs behavior dynamically 5 min read How to get list of parameters name from a function in Python?The task of getting a list of parameter names from a function in Python involves extracting the function's arguments using different techniques. These methods allow retrieving parameter names efficiently, whether from bytecode, introspection or source code analysis. For example, if a function fun(a, 4 min read How to Pass Optional Parameters to a Function in PythonIn Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primar 5 min read Return StatementsHow to Pass Optional Parameters to a Function in PythonIn Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primar 5 min read Returning Multiple Values in PythonIn Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. Python # A Python program to return multiple # values from a meth 4 min read Python None KeywordNone is used to define a null value or Null object in Python. It is not the same as an empty string, a False, or a zero. It is a data type of the class NoneType object. None in Python Python None is the function returns when there are no return statements. Python3 def check_return(): pass print(che 2 min read Returning a function from a function - PythonIn Python, functions are first-class objects, allowing them to be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, closures and dynamic behavior.Example:Pythondef fun1(name): def fun2(): return f"Hello, {name}!" return fun2 # Get the 5 min read Like