Translate

Friday 16 February 2024

Function Calling Another Function in Python

Function Calling Another Function in Python

To have one function call another, just place the function call within the body of the first function. Here's a simple illustration:


Python

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

def introduce():
    name = input("Enter your name: ")
    greet(name)  # introduce() calls greet()

introduce()  # Start the program execution

Explanation

  1. greet(): Takes a name and prints a greeting.

  2. introduce(): Gets the user's name and calls greet() to display the greeting.

  3. Program flow: You call introduce(), which in turn calls greet().

Key Benefits

  • Modularity: Break your code into smaller, self-contained units, making it easier to manage and debug.

  • Reusability: Write functions that can be called from multiple places in your code, avoiding duplication.

  • Abstraction: Focus on the high-level logic of what a function needs to do instead of getting buried in implementation details in every part of your program.

Example: Factorial calculation


Python

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1# Recursive call

result = factorial(5)
print(result)  # Output: 120

Important Considerations

  • Return Values: A function can return a value, and this returned value can be used by the calling function:
    Python
    def add(x, y):
        return x + y

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

  • Recursion: A function can call itself (recursion), elegantly solving problems like calculating factorials or the Fibonacci sequence.



.

Example 1: Area Calculator


Python

def calculate_rectangle_area(length, width):
    return length * width

def calculate_triangle_area(base, height):
    return 0.5 * base * height

def get_shape_area():
    shape = input("Enter shape (rectangle or triangle): ")

    if shape == "rectangle":
        length = float(input("Enter length: "))
        width = float(input("Enter width: "))
        area = calculate_rectangle_area(length, width)
    elif shape == "triangle":
        base = float(input("Enter base: "))
        height = float(input("Enter height: "))
        area = calculate_triangle_area(base, height)
    else:
        print("Invalid shape")
        return

    print("The area is:", area)

get_shape_area()

Example 2: User Authentication


Python

def get_username_password():
    username = input("Enter username: ")
    password = input("Enter password: ")
    return username, password

def check_credentials(username, password):
    # Replace with your actual authentication logic
    if username == "admin" and password == "secret":
        return True
    else:
        return False

def login():
    username, password = get_username_password()
    if check_credentials(username, password):
        print("Login successful!")
    else:
        print("Invalid credentials.")

login()

Example 3: Recursive Fibonacci Sequence


Python

def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

nterms = int(input("Enter number of terms in Fibonacci sequence: "))

if nterms <= 0:
    print("Please enter a positive integer.")
else:
    print("Fibonacci sequence:")
    for i in range(nterms):
        print(fibonacci(i))



11 Function Calling Another Function and Recursion in Python -11 Data Analyst training Telugu

No comments:

Post a Comment

Note: only a member of this blog may post a comment.