Functions in Python

 A function is a block of reusable code that performs a specific task.

Functions help to avoid repetition and make programs organized and modular.

In Python, functions are created using the def keyword.

Advantages of using functions:

  • Code reusability

  • Easy debugging

  • Better readability

  • Reduces code length

  • Improves program structure

Defining a Function

A function is defined using the def keyword followed by function name and parentheses.

Syntax:

def function_name():
statements

Example:

def greet():
print("Hello World")

greet()

Function with Parameters

Parameters are values passed to a function.

Syntax:

def function_name(parameter):
statements

Example:

def greet(name):
print("Hello", name)

greet("Kumar")

Function with Return Value

The return statement sends a value back to the caller.

Syntax:

def function_name():
return value

Example:

def add(a, b):
return a + b

result = add(10, 5)
print(result)

Types of Arguments in Python

Python supports different types of arguments:

  1. Positional Arguments

  2. Keyword Arguments

  3. Default Arguments

  4. Variable-length Arguments

Positional Arguments

Values are passed in the correct order.

def student(name, age):
print(name, age)

student("Arun", 20)

Keyword Arguments

Values are passed using parameter names.

def student(name, age):
print(name, age)

student(age=20, name="Arun")

Default Arguments

A default value is assigned to a parameter.

def greet(name="Guest"):
print("Hello", name)

greet()
greet("Ravi")

Variable-Length Arguments (*args)

Used when the number of arguments is unknown.

def total(*numbers):
print(sum(numbers))

total(10, 20, 30)

Lambda Function

A lambda function is a small anonymous function.

Syntax:

lambda arguments: expression

Example:

square = lambda x: x * x
print(square(5))

Recursive Function

A function that calls itself is called recursion.

Example:

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

print(factorial(5))

Scope of Variables

Variable scope determines where a variable can be accessed.

Types:

  • Local Variable

  • Global Variable

Example:

x = 10 # Global

def show():
y = 5 # Local
print(x)
print(y)

show()

Built-in Functions

Python provides many built-in functions such as:

  • print()

  • len()

  • type()

  • sum()

  • max()

  • min()

Example:

numbers = [10, 20, 30]
print(len(numbers))
print(max(numbers))

Conclusion

Functions are very important in Python programming. They:

✔ Improve code reusability
✔ Make programs modular
✔ Reduce repetition
✔ Increase readability

Without functions, programs become lengthy and difficult to manage.

Comments

Popular posts from this blog

Tkinter -Python

Python – Database Connection