Open In App

Python def Keyword

Last Updated : 02 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Python def Keyword

Python def Syntax

def function_name:

function definition statements…

Use of def keyword

  • In 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.

How to Use def in Python?

Below are the ways and examples by which we can use def in Python:

  • Create a def function with No Arguments
  • Create def function to find the subtraction of two Numbers
  • Create def function with the first 10 prime numbers
  • Create a function to find the factorial of a Number
  • Python def keyword example with *args
  • Python def keyword example with **kwargs
  • Passing Function as an Argument
  • Python def keyword example with the class

Create a def function with No Arguments

In this example, we have created a user-defined function using the def keyword. The Function simply prints the Hello as output.

Python
def python_def_keyword():
    print("Hello")
python_def_keyword()

Output
Hello

Create def function to find the subtraction of two Numbers

In this example, we have created a user-defined function using the def keyword. The Function name is python_def_subNumbers(). It calculates the differences between two numbers.

Python
# Python3 code to demonstrate
# def keyword

# function for subtraction of 2 numbers.
def python_def_subNumbers(x, y):
    return (x-y)

# main code
a = 90
b = 50

# finding subtraction
result = python_def_subNumbers(a, b)

# print statement
print("subtraction of ", a, " and ", b, " is = ", result)

Output
subtraction of  90  and  50  is =  40

Create def function with the first 10 prime numbers

In this example, we have created a user-defined function using the def keyword. The program defines a function called python_def_prime() 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 python_def_prime(n):
    x = 2
    count = 0
    while count < n:
        for d in range(2, x, 1):
            if x % d == 0:
                x += 1
        else:
            print(x)
            x += 1
            count += 1

# Driver Code
n = 10

# print statement
print("First 10 prime numbers are:  ")
python_def_prime(n)

Output
First 10 prime numbers are:  
2
3
5
7
11
13
17
19
23
27

Create a function to find the factorial of a Number

In this example, we have created a user-defined function using the def keyword. The program defines a function called python_def_factorial() using the def keyword. The function takes a single parameter n, which represents the number whose factorial is to be calculated.

Python
# Python program to find the
# factorial of a number

# Function name factorial is defined
def python_def_factorial(n):
    if n == 1:
        return n
    else:
        return n*python_def_factorial(n-1)

# Main code
num = 6

# check is the number is negative
if num < 0:
    print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
    print("The factorial of 0 is 1")
else:
    print("The factorial of", num, "is", python_def_factorial(num))

Output
The factorial of 6 is 720

Python def keyword example with *args

This is a Python program that defines a function called python_def_keyword() using the def keyword. The function uses the special parameter *args ,which allows the function to accept an arbitrary number of arguments. Inside the function, a for loop is used to iterate over the arguments passed to the function. The loop iterates over the variable arg, which represents each argument in turn, and prints it to the console using the print() function.

Python
def python_def_keyword(*args):
    for arg in args:
        print(arg)
python_def_keyword(1, 2, 3)
python_def_keyword('apple', 'banana', 'cherry', 'date')
python_def_keyword(True, False, True, False, True)

Output
1
2
3
apple
banana
cherry
date
True
False
True
False
True

Python def keyword example with **kwargs

This is a Python program that defines a function called python_def_keyword() using the def keyword. The function uses the special parameter **kwargs, which allows the function to accept an arbitrary number of keyword arguments.

Inside the function, a for loop is used to iterate over the key-value pairs passed to the function. The loop iterates over the kwargs dictionary using the items() method, which returns a sequence of (key, value) tuples. For each tuple, the loop unpacks the key and value variables and prints them to the console using the print() function and string formatting.

Python
def python_def_keyword(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
python_def_keyword(name='Alice', 
                   age=25, city='New York')
python_def_keyword(country='Canada', 
                   language='French', population=38000000)
python_def_keyword(color='blue', 
                   shape='square', size='large', material='wood')

Output
name: Alice
age: 25
city: New York
country: Canada
language: French
population: 38000000
color: blue
shape: square
size: large
material: wood

Passing Function as an Argument

This is a Python program that defines a function called apply_function() using the def keyword. The function takes two parameters: func, which is a function, and arg, which is an argument to be passed to func. The function then returns the result of calling func with arg. The program also defines another function called square using the def keyword. This function takes a single parameter x and returns the square of x.

After defining these functions, the program calls the apply_function function with square as the func argument and 5 as the arg argument. This means that the square function will be called with 5 as its argument, and its result will be returned by apply_function().

Python
def apply_function(func, arg):
    return func(arg)
def square(x):
    return x ** 2
result = apply_function(square, 5)
print(result)

Output
25

Python def keyword example with the class

In this example, we define a python_def_keyword class with an __init__() method that takes in two arguments (name and age) and initializes two instance variables (self. name and self. age). We then define a say_hello() method that prints out a greeting with the person’s name and age.We create an instance of the python_def_keyword class called python_def_keyword1 with the name “John” and age 30. We then call the say_hello() method on the python_def_keyword1 instance.

Python
class python_def_keyword:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def say_hello(self):
        print(f"Hello, my name is {self.name} " +
              f"and I am {self.age} years old.")
python_def_keyword1 = python_def_keyword("John", 30)
python_def_keyword1.say_hello()  

Output
Hello, my name is John and I am 30 years old.

Frequently Asked Questions (FQAs)

How to use def in Python?

The def keyword in Python is used to define functions. We start with def, followed by the function name and any parameters in parentheses. The function body, indented below, contains the code to be executed. Optionally, we can use the return statement to send a value back when the function is called. This structure allows us to create reusable and organized code blocks.

What is the purpose of the def keyword in Python?

The def keyword in Python is used to define functions. It allows you to create reusable blocks of code with a specific name, making your code modular, organized, and easier to maintain.

Can a Python function have multiple return statements?

Yes, a Python function can have multiple return statements. However, once a return statement is executed, the function exits, and subsequent code is not executed. Each return statement can provide different outcomes based on conditions within the function.

What is def __init__(self) in Python?

def __init__(self) is the constructor method in Python, used in classes. It initializes the object’s attributes when an instance of the class is created.

Example:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

person = Person("Alice", 30)
print(person.name) # Output: Alice
print(person.age) # Output: 30

In this example, __init__ initializes the name and age attributes of the Person class.



Similar Reads

Difference between Normal def defined function and Lambda
In this article, we will discuss the difference between normal def defined function and lambda in Python. Def keyword​​​​​​​In python, def defined functions are commonly used because of their simplicity. The def defined functions do not return anything if not explicitly returned whereas the lambda function does return an object. The def functions m
2 min read
Python | Passing dictionary as keyword arguments
Many times while working with Python dictionaries, due to advent of OOP Paradigm, Modularity is focussed in different facets of programming. Hence there can be many use cases in which we require to pass a dictionary as argument to a function. But this required the unpacking of dictionary keys as arguments and it's values as argument values. Let's d
3 min read
Python assert keyword
Python Assertions in any programming language are the debugging tools that help in the smooth flow of code. Assertions are mainly assumptions that a programmer knows or always wants to be true and hence puts them in code so that failure of these doesn't allow the code to execute further. Assert Keyword in PythonIn simpler terms, we can say that ass
7 min read
finally keyword in Python
Prerequisites: Exception Handling, try and except in Python In programming, there may be some situation in which the current method ends up while handling some exceptions. But the method may require some additional steps before its termination, like closing a file or a network and so on. So, in order to handle these situations, Python provides a ke
3 min read
Keyword Module in Python
Python provides an in-built module keyword that allows you to know about the reserved keywords of python. The keyword module allows you the functionality to know about the reserved words or keywords of Python and to check whether the value of a variable is a reserved word or not. In case you are unaware of all the keywords of Python you can use thi
2 min read
Use of nonlocal vs use of global keyword in Python
Prerequisites: Global and Local Variables in PythonBefore moving to nonlocal and global in Python. Let us consider some basic scenarios in nested functions. C/C++ Code def fun(): var1 = 10 def gun(): print(var1) var2 = var1 + 1 print(var2) gun() fun() Output: 10 11 The variable var1 has scope across entire fun(). It will be accessible from nested f
3 min read
is keyword in Python
In programming, a keyword is a “reserved word” by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. Python language also reserves some of the keywords that convey special meaning. In Python, keywords are case-sensitive. Python is Keywo
2 min read
Python IMDbPY - Searching keyword
In this article we will see how we can search a keyword in the IMDb database.Keyword : It is a word (or group of connected words) attached to a title (movie / TV series / TV episode) to describe any notable object, concept, style or action that takes place during a title. The main purpose of keywords is to allow visitors to easily search and discov
1 min read
Python IMDbPY – Searching movies matching with keyword
In this article we will see how we can find movies that have similar keyword. Keyword is a word (or group of connected words) attached to a title (movie / TV series / TV episode) to describe any notable object, concept, style or action that takes place during a title. The main purpose of keywords is to allow visitors to easily search and discover t
1 min read
Python None Keyword
None 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. C/C++ Code def check_return(): pass print(check_return()) Output: NoneNull Vs None in Python
2 min read
Python as Keyword
In this article, we are going to see 'as' Keyword. The keyword 'as' is used to create an alias in python. Advantages with 'as' keyword: It is useful where we cannot use the assignment operator such as in the import module.It makes code more understandable to humans.The keyword as is used to make alias with programmer selected name, It decreases the
2 min read
Python nonlocal Keyword
Python nonlocal keyword is used to reference a variable in the nearest scope. Python nonlocal Keyword Example In this example, we demonstrate the working of the nonlocal keyword. C/C++ Code def foo(): name = &quot;geek&quot; # Our local variable def bar(): nonlocal name # Reference name in the upper scope name = 'GeeksForGeeks' # Overwrite this var
3 min read
Python or Keyword
Python OR is a logical operator keyword. The OR operator returns True if at least one of the operands becomes to be True. Note: In Python or operator does not return True or False. The or operator in Python returns the first operand if it is True else the second operand.Python OR Keyword Truth TableInput 1Input2OutputTrueTrueTrueTrueFalseTrueFalseT
2 min read
Python False Keyword
A boolean expression results in two values(True, False) similar to this a boolean variable can also be assigned either (True, False). Here False keyword represents an expression that will result in not true. Example 1 : In this example first, we will give one boolean expression which will result in False (10 &lt; 6). Next, we assigned the False key
2 min read
How to Fix: SyntaxError: positional argument follows keyword argument in Python
In this article, we will discuss how to fix the syntax error that is positional argument follows keyword argument in Python An argument is a value provided to a function when you call that function. For example, look at the below program - Python Code # function def calculate_square(num): return num * num # call the function result = calculate_squa
3 min read
Python in Keyword
In programming, a keyword is a "reserved word" by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. Python language also reserves some of the keywords that convey special meaning. In Python, keywords are case-sensitive. Python in Keywo
2 min read
Python Raise Keyword
In this article, we will learn how the Python Raise keyword works with the help of examples and its advantages. Python Raise KeywordPython raise Keyword is used to raise exceptions or errors. The raise keyword raises an error and stops the control flow of the program. It is used to bring up the current exception in an exception handler so that it c
3 min read
How to check if a string is a valid keyword in Python?
In programming, a keyword is a "reserved word" by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. What is Keywords in PythonPython also reserves some keywords that convey special meaning. Knowledge of these is a necessary part of lea
2 min read
Python | yield Keyword
In this article, we will cover the yield keyword in Python. Before starting, let's understand the yield keyword definition. Syntax of the Yield Keyword in Python def gen_func(x): for i in range(x): yield iWhat does the Yield Keyword do?yield keyword is used to create a generator function. A type of function that is memory efficient and can be used
6 min read
How to fix Python Multiple Inheritance generates "TypeError: got multiple values for keyword argument".
Multiple inheritance in Python allows a class to inherit from more than one parent class. This feature provides flexibility but can sometimes lead to complications, such as the error: "TypeError: got multiple values for keyword argument". This error occurs when the method resolution order (MRO) leads to ambiguous function calls, especially with key
5 min read
Keyword and Positional Argument in Python
Python 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 Keyword and Positional ArgumentKeyword-Only Argument
4 min read
The yield Keyword in Ruby
We can send a block to our method and it can call that block multiple times. This can be done by sending a proc/lambda, but is easier and faster with yield. During a method invocation The yield keyword in corporation with a block allows to pass a set of additional instructions. When yield is called in side a method then method requires a block with
2 min read
Scala this keyword
Keywords are the words in a language that are used to represent some predefined actions or some internal process. We use the this keyword when we want to introduce the current object for a class. Then using the dot operator (.), we can refer to instance variables, methods and constructors by using this keyword. this keyword is also used with auxili
2 min read
Scala | yield Keyword
yield keyword will returns a result after completing of loop iterations. The for loop used buffer internally to store iterated result and when finishing all iterations it yields the ultimate result from that buffer. It doesn't work like imperative loop. The type of the collection that is returned is the same type that we tend to were iterating over
2 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
Practice Tags :