Functions and Recursion
Functions and Recursion
Functions:
A function is a block of code that performs a specific task. a function, which is a
reusable block of code designed to perform a single, related action. Functions allow you to
modularize your code and make it more organized and manageable.
Syntax
def function_name(parameters):
# function body
return value
Example 1:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
Output:
Hello, Alice!
Example 2:
def greet(name):
print ('Hello ', name)
greet('Steve') # calling function with argument
greet(123)
Output
Hello Steve
Hello 123
Example 3:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Output
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Example 4:
def greet(*names):
print ('Hello ', names[0], ', ', names[1], ', ', names[2])
greet('Dani', 'Josh', 'Raj')
Output
Hello Dani , Josh , Raj
Example 5:
num1 = int(input("Enter first Number: "))
num2 = int(input("Enter Second Number: "))
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ", sum)
add_numbers(num1, num2)
Output
Enter first Number: 78
Enter Second Number: 89
Sum: 167
Recursion
Recursion A recursive function is a function that calls itself with a failure condition. It means
that there will be one or more function calls within that function definition itself.
Example 1:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print('The Factorial of', factorial(6))
Output
The Factorial of 720
Example 2:
def fib(n):
if n<=1:
return n
else:
return fib(n-1) + fib(n-2)
count = int(input("Enter the limit: "))
if count<=0:
print("Enter a number greater than 0")
else:
for i in range(count):
print(fib(i),end=" ")
Output
Enter the limit: 9
0 1 1 2 3 5 8 13 21