Skip to content

How is a function declared in Python? | Basics

  • by

There 2 ways you can declare the function in Python. The first way is using the def keyword and another way is using the keyword lambda.

def functionname(parameters):
   
   return [expression]

But They are also known as lambda functions. These functions are special functions that are used when we need to pass a function itself as an argument.

lambda arguments : expression

To call a function in Python, you simply use the function name followed by a set of parentheses enclosing any arguments you want to pass to the function.

Example How is a function declared in Python

Simple examples.

Using def function_name():

In Python a function is defined using the def keyword:

def my_function():
    print("Hello from a function")


my_function()

Output:

How is a function declared in Python

Define Anonymous functions

Lambda functions can take any number of arguments:

x = lambda a, b: a * b

print(x(5, 6))

Output: 30

More example

sum = add_numbers(3, 5)
print(sum)  # Output: 8

greet("Alice")  # Output: Hello, Alice!
greet("Bob", "Hi")  # Output: Hi, Bob!

Do comment if you have any doubts or suggestions on this Python basic topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading