Python Subprograms: Functions and Subroutines
What is a Subprogram?
A subprogram is a small, separate piece of code inside a bigger program. It performs a specific task. In Python,
functions are used as subprograms.
Why Use Functions?
- Avoid repeating the same code
- Break problems into small parts
- Reuse code
- Make programs easier to fix and update
How to Define a Function
Syntax:
def function_name(parameters):
# code block
return result
Example:
def greet():
print("Hello! Welcome to Python.")
greet()
Function with Parameters
def greet(name):
print("Hello,", name)
greet("Asmitha")
Function with Return Value
def add(a, b):
return a + b
result = add(10, 5)
print("Sum is:", result)
Types of Functions
- No parameters, no return: def show(): print("Hi")
- Parameters, no return: def display(x): print(x)
Python Subprograms: Functions and Subroutines
- Parameters, with return: def square(x): return x*x
- No parameters, with return: def get_pi(): return 3.14
Default Arguments
def greet(name="Student"):
print("Hello,", name)
greet()
greet("John")
Keyword Arguments
def student_info(name, age):
print(name, "is", age, "years old")
student_info(age=16, name="Priya")
Variable-Length Arguments
*args:
def total(*numbers):
print("Sum:", sum(numbers))
total(1, 2, 3, 4)
**kwargs:
def show_info(**info):
for key, value in info.items():
print(key, ":", value)
show_info(name="Ravi", age=17)
Local vs Global Variables
x = 10 # Global
def show():
x = 5 # Local
print("Inside:", x)
show()
print("Outside:", x)
Python Subprograms: Functions and Subroutines
Recursive Function (Function Calling Itself)
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
Anonymous Function (Lambda)
square = lambda x: x * x
print(square(6))
Practice Exercises
1. Area of a Circle:
def area_circle(radius):
pi = 3.1416
return pi * radius * radius
2. Prime Checker:
def is_prime(n):
if n < 2: return False
for i in range(2, n):
if n % i == 0: return False
return True
3. Max of Variable Inputs:
def find_max(*nums):
return max(nums)
4. Fibonacci using Recursion:
def fibonacci(n):
if n <= 1: return n
return fibonacci(n-1) + fibonacci(n-2)
for i in range(6):
print(fibonacci(i), end=" ")
Summary Chart
Concept | Keyword/Method | Example
------------------|------------------|---------------------------
Python Subprograms: Functions and Subroutines
Function def | def | def hello():
Return value | return | return x + y
Call function | function name | hello()
Optional input | default args | name="guest"
Unlimited input | *args, **kwargs | *nums, **info
One-line function | lambda | lambda x: x*x
Repeated call | recursion | factorial(n-1)