Skip to main content

Functions in Python with multiple examples and call function from multiple function

 Functions in Python are blocks of organized, reusable code designed to perform a specific task. They help modularize code, improve readability, and make it easier to manage and reuse code. Here are some examples of defining functions and calling functions from other functions:

1. Simple function:

A basic function that takes two parameters and returns their sum.

```python
def add_numbers(a, b):
    result = a + b
    return result

# Calling the function
sum_result = add_numbers(5, 3)
print(sum_result)  # Output: 8
```

2. Function with default parameter:

A function with a default parameter value. If the second parameter is not provided, it will use the default value.

```python
def greet(name, greeting="Hello"):
    message = f"{greeting}, {name}!"
    return message

# Calling the function without the second parameter
greeting_message = greet("John")
print(greeting_message)  # Output: Hello, John!

# Calling the function with the second parameter
greeting_message = greet("Alice", "Hi")
print(greeting_message)  # Output: Hi, Alice!
```

3. Function with multiple return values:

A function that returns multiple values using tuple packing and unpacking.

```python
def get_name_and_age():
    name = "John"
    age = 30
    return name, age

# Calling the function and unpacking the returned values
person_name, person_age = get_name_and_age()
print(person_name)  # Output: John
print(person_age)   # Output: 30
```

4. Function calling another function:

A function can call another function within its block.

```python
def multiply_numbers(a, b):
    return a * b

def perform_calculation(x, y):
    result = add_numbers(x, y)
    result *= multiply_numbers(x, y)
    return result

# Calling the perform_calculation function
calc_result = perform_calculation(3, 4)
print(calc_result)  # Output: 84 (3 + 4) * (3 * 4)
```

5. Recursive function:

A function that calls itself to perform a repetitive task.

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

# Calling the factorial function
result = factorial(5)
print(result)  # Output: 120 (5! = 5 * 4 * 3 * 2 * 1)
```

6. Function as an argument to another function:

Functions can also be passed as arguments to other functions.

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

def subtract(a, b):
    return a - b

def calculate(operation, x, y):
    return operation(x, y)

# Calling the calculate function with add and subtract functions as arguments
result1 = calculate(add, 5, 3)
result2 = calculate(subtract, 5, 3)

print(result1)  # Output: 8 (addition)
print(result2)  # Output: 2 (subtraction)
```

These examples demonstrate various aspects of functions in Python, including defining functions, using default parameters, returning values, calling functions from other functions, recursion, and using functions as arguments to other functions. Functions are a powerful feature in Python that helps to structure and organize code for efficient and reusable programming.

Comments

Popular posts from this blog

Web Programming: HTML, DHTML, XML, Scripting, Java, Servlets, Applets

 Web programming encompasses various technologies and concepts used to develop web applications. Let's explore each of them in detail: 1. HTML (Hypertext Markup Language): HTML is the standard markup language used to create the structure and content of web pages. It uses tags to define elements like headings, paragraphs, images, links, forms, etc. Example: ```html <!DOCTYPE html> <html> <head>     <title>My Web Page</title> </head> <body>     <h1>Hello, World!</h1>     <p>This is a paragraph.</p>     <img src="image.jpg" alt="Image">     <a href="https://www.example.com">Visit Example</a> </body> </html> ``` 2. DHTML (Dynamic HTML): DHTML is a combination of HTML, CSS, and JavaScript that allows web pages to become more dynamic and interactive. Example (DHTML with JavaScript): ```html <!DOCTYPE html> <htm...

Tokens, Identifiers, Data Types, Sequence Control, Subprogram Control, Arrays, Structures, Union, String, Pointers, Functions, File Handling, Command Line Argumaents, Preprocessors in C with example

 Let's discuss each concept briefly and provide examples for better understanding: 1. Tokens: Tokens are the smallest building blocks in C programming. They include keywords, identifiers, constants, strings, operators, and punctuators. Example: ```c #include <stdio.h> int main() {     int num = 42;  // 'int', 'main', 'return', '42', '=', ';' are tokens     printf("Hello, World!");  // 'printf', '(', ')', 'Hello, World!', ';', are tokens     return 0;  // 'return', '0', ';' are tokens } ``` 2. Identifiers: Identifiers are names used to identify variables, functions, or other user-defined entities. Example: ```c int age = 30;  // 'age' is an identifier (variable name) void displayMessage() {  // 'displayMessage' is an identifier (function name)     // function body } ``` 3. Data Types: Data types define the type of data that can be stored in ...

Place holder and control character in c language

 In the C programming language, placeholders and control characters are used to format and control the output of text in console-based programs. They are special characters or sequences of characters that have specific meanings. Here are the placeholders and control characters commonly used in C: 1. Placeholders:    - %d: Used to display signed integers.      Example: printf("The value is %d", 10);    - %u: Used to display unsigned integers.      Example: printf("The value is %u", 10);    - %f: Used to display floating-point numbers.      Example: printf("The value is %f", 3.14);    - %c: Used to display characters.      Example: printf("The character is %c", 'A');    - %s: Used to display strings (sequence of characters).      Example: printf("The string is %s", "Hello");    - %p: Used to display memory addresses (pointers)...