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
greet(): Takes a name and prints a greeting.
introduce(): Gets the user's name and calls greet() to display the greeting.
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: 8Recursion: 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))
Function Calling Another Function in Python¶
def greet(name):
print("Hello,", name + "!")
def introduce():
name = input("Enter your name: ")
greet(name) # introduce() calls greet()
introduce()
Enter your name: venkat Hello, venkat!
def Introduce():
name = input('enter name')
greet(name)
def greet(customer):
print("hi ",customer, ' welcome to Vlrtraining' )
Introduce()
enter namemohan hi mohan welcome to Vlrtraining
enter namevenkat hi venkat welcome to Vlrtraining
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1) # Recursive call
value = int(input('enter Number'))
result = factorial(value)
print(result) # Output: 120
enter Number6 720
def fact(n):
if n==0:
return 1
else:
return n * fact(n-1)
value = int(input('enter Number'))
result = fact(value)
print(result) # Output: 120
enter Number3 6
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()
Enter shape (rectangle or triangle): ere Invalid shape
a,b=10,30
a
10
b
30
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("Invali
d credentials.")
login()
Enter username: venkat Enter password: vlr Invalid credentials.
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))
Enter number of terms in Fibonacci sequence: 4 Fibonacci sequence: 0 1 1 2
No comments:
Post a Comment
Note: only a member of this blog may post a comment.