Introduction to Function in Python

 

Functions

Functions are reusable blocks of code that perform a specific task. They help in organizing and managing the code efficiently.

 

Defining Functions

Use the def keyword to define a function.

 

Code:

def greet(name):

    return f"Hello, {name}!"

 

print(greet("Alice"))

 


Function Arguments

Functions can accept arguments to customize their behavior.

 

Code:

def add(a, b):

    return a + b

 

print(add(3, 5))



Default Arguments

You can provide default values for function arguments.

 Code:

def greet(name="Guest"):

    return f"Hello, {name}!"

 

print(greet())

print(greet("Alice"))


Variable-Length Arguments

Functions can accept a variable number of arguments using *args and **kwargs.

 

Code:

def print_numbers(*args):

    for number in args:

        print(number)

 

print_numbers(1, 2, 3, 4)

 

def print_info(**kwargs):

    for key, value in kwargs.items():

        print(f"{key}: {value}")

 

print_info(name="Alice", age=25, city="New York")

 


No comments:

Post a Comment

MS Excel Logical Functions

Logical functions in Excel are powerful tools that help you make decisions based on conditions. Whether you're comparing values or testi...

Post Count

Loading...