Ticker

6/recent/ticker-posts

Functions in Python

Functions in Python

Introduction to Functions:
Functions are blocks of organized, reusable code designed to perform a specific task. They help break down complex programs into smaller, manageable chunks, improving code readability and reusability.

Defining a Function:
In Python, functions are defined using the def keyword, followed by the function name and parentheses containing optional parameters.

Example:

python
def greet(name):
return f"Hello, {name}!"

Explanation:

  • The function greet is defined with one parameter name.
  • It returns a string that greets the input name.

Calling a Function:
To execute a function and obtain its result, you call it with the required arguments.

Example:

python
message = greet("John")
print(message)

:

  • The function greet is called with the argument "John".
  • The function returns the string "Hello, John!", which is stored in the variable message.
  • The print function displays the value of message.

Default Parameters:
Functions can have default parameter values, which are used when an argument is not provided during the function call.

Example:

python
def greet_default(name="Guest"):
return f"Hello, {name}!"

Explanation:

  • The function greet_default has a default parameter name set to "Guest".
  • If no argument is provided, it will greet the guest; otherwise, it will greet the provided name.

Returning Values:
Functions can return values using the return statement. They can return one or multiple values.

Example:

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

Explanation:

  • The function add takes two arguments a and b.
  • It returns their sum.

Scope of Variables:
Variables defined inside a function have local scope and are accessible only within the function. Variables defined outside the function have global scope.

Example:

python
def multiply(a, b):
result = a * b
return result

total = multiply(3, 5)
print(total)

Explanation:

  • The multiply function takes two arguments a and b.
  • It calculates their product and returns the result.
  • The total variable, defined outside the function, stores the result of the multiply function call, and then it's printed.

Lambda Functions:
Lambda functions, also known as anonymous functions, are concise functions defined using the lambda keyword.

Example:

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

Explanation:

  • The lambda function square takes an argument x.
  • It returns the square of x.
  • The result of the square function is printed, which is 25 for the input 5.

These are the fundamental aspects of Python functions that will help you write modular and efficient code.

Post a Comment

0 Comments