Skip to main content

Python Defining and Calling Functions

Defining Functions

A function in Python is defined using the def keyword, followed by the function name, parentheses, and a colon. The code block within every function starts with an indentation and contains the function body.

Basic Function Definition

def function_name(parameters):
    """Docstring explaining the function."""
    # Function body
    return value


  • function_name: The name of the function.
  • parameters: Optional. Parameters that the function takes. They are also called arguments.
  • Docstring: Optional. A string that describes what the function does.
  • Function body: The block of code that performs the function’s task.
  • return: Optional. Specifies what the function returns. If not specified, the function returns None by default.

Example of Defining a Function

def greet(name):
    """This function greets the person whose name is passed as an argument."""
    print(f"Hello, {name}!")


Calling Functions

A function is called by using its name followed by parentheses. If the function takes parameters, you pass the arguments inside the parentheses.

Basic Function Call

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

Examples of Defining and Calling Functions

Function with No Parameters

def say_hello():
    """This function prints a hello message."""
    print("Hello, world!")

# Calling the function
say_hello()  # Output: Hello, world!

Function with Parameters

def add(a, b):
    """This function returns the sum of two numbers."""
    return a + b

# Calling the function
result = add(3, 5)
print(result)  # Output: 8

Function with Default Parameters

def greet(name="Guest"):
    """This function greets the person whose name is passed as an argument, or 'Guest' if no name is provided."""
    print(f"Hello, {name}!")

# Calling the function
greet("Alice")  # Output: Hello, Alice!
greet()         # Output: Hello, Guest!


Function with Variable-Length Arguments

Sometimes, you might want to pass a variable number of arguments to a function. This can be achieved using *args for non-keyword arguments and **kwargs for keyword arguments.

def print_numbers(*args): """This function prints all the numbers passed to it.""" for num in args: print(num) # Calling the function print_numbers(1, 2, 3, 4) # Output: # 1 # 2 # 3 # 4

def print_info(**kwargs):
 """This function prints the keyword arguments passed to it."""
        for key, value in kwargs.items():
            print(f"{key}: {value}")
# Calling the function
print_info(name="Alice", age=30, city="New York")  
# Output:
# name: Alice
# age: 30
# city: New York


Return Statement

A function can return a value using the return statement. If a return statement is not used, the function returns None.

Function with a Return Value

def multiply(a, b):
    """This function returns the product of two numbers."""
    return a * b

# Calling the function
result = multiply(4, 5)
print(result)  # Output: 20


Lambda Functions

For simple, small functions, you can use lambda functions (also known as anonymous functions).

Lambda Function Example

# A lambda function that adds two numbers
add = lambda x, y: x + y

# Calling the lambda function
result = add(3, 5)
print(result)  # Output: 8


Functions in Python are a fundamental part of the language, allowing for reusable and organized code. By understanding how to define and call functions, you can write more efficient and maintainable code.















Comments

Popular posts from this blog

Performance Optimization

Performance optimization in SQL is crucial for ensuring that your database queries run efficiently, especially as the size and complexity of your data grow. Here are several strategies and techniques to optimize SQL performance: Indexing Create Indexes : Primary Key and Unique Indexes : These are automatically indexed. Ensure that your tables have primary keys and unique constraints where applicable. Foreign Keys : Index foreign key columns to speed up join operations. Composite Indexes : Use these when queries filter on multiple columns. The order of columns in the index should match the order in the query conditions. Avoid Over-Indexing:  Too many indexes can slow down write operations (INSERT, UPDATE, DELETE). Only index columns that are frequently used in WHERE clauses, JOIN conditions, and as sorting keys. Query Optimization Use SELECT Statements Efficiently : SELECT Only Necessary Columns : Avoid using SELECT * ; specify only ...

DAX UPPER Function

The DAX UPPER function in Power BI is used to convert all characters in a text string to uppercase. This function is useful for standardizing text data, ensuring consistency in text values, and performing case-insensitive comparisons. Syntax: UPPER(<text>) <text>: The text string that you want to convert to uppercase. Purpose: The UPPER function helps ensure that text data is consistently formatted in uppercase. This can be essential for tasks like data cleaning, preparing text for comparisons, and ensuring uniformity in text-based fields. E xample: Suppose you have a table named "Customers" with a column "Name" that contains names in mixed case. You want to create a new column that shows all names in uppercase. UppercaseName = UPPER(Customers[Name]) Example Scenario: Assume you have the following "Customers" table: You can use the UPPER function as follows: Using the UPPER function, you can convert all names to uppercase: UppercaseName = ...

TechUplift: Elevating Your Expertise in Every Click

  Unlock the potential of data with SQL Fundamental: Master querying, managing, and manipulating databases effortlessly. Empower your database mastery with PL/SQL: Unleash the full potential of Oracle databases through advanced programming and optimization. Unlock the Potential of Programming for Innovation and Efficiency.  Transform raw data into actionable insights effortlessly. Empower Your Data Strategy with Power Dataware: Unleash the Potential of Data for Strategic Insights and Decision Making.