Python Functions and Parameter Passing
Python Functions and Parameter Passing
Program Routines
• A program routine is a set of instructions designed to perform a specific task in a program.
• In Python, functions are the primary means to create program routines.
Advantages of Program Routines / Functions:
1. Reusability – Write once and reuse multiple times.
2. Modularity – Programs can be divided into smaller, logical parts.
3. Readability – Code becomes easier to understand.
4. Maintainability – Easier to debug, test, and update.
5. Abstraction – Hides the internal details; user interacts with input/output only.
Python Functions
Function Declaration
The syntax to declare a function is:
Defining a Function
We can define a function in Python, using the def keyword. We can add any type of functionalities and
properties to it as we require.
The def keyword stands for define. It is used to create a user-defined function. It marks the beginning of a
function block and allows you to group a set of statements so they can be reused when the function is called.
Explanation:
• def: Starts the function definition.
• function_name: Name of the function.
• parameters: Inputs passed to the function (inside ()), optional.
• Indented code: The function body that runs when called.
Built-in Functions
• Python provides a large number of pre-defined functions that can be used directly.
• Examples include: print(), len(), sum(), max(), min(), type(), range(), sorted(), etc.
Characteristics:
1. Already available in Python, no need to define.
2. Can be used by simply calling the function with required arguments.
3. Reduce coding effort and errors.
User-Defined Functions
• These are functions created by the programmer to perform a specific task.
• They allow reusability, modularity, and abstraction.
• Created using the def keyword.
Eg:
def add(a, b):
return a + b
result = add(10, 20)
print("Sum:", result)
output:
Sum: 30
Calling a function:
In Python, we use the name of the function to make a function call.
If the function requires any parameters, we need to pass them while calling it.
Syntax:
function_name(parameter_1, parameter_2,...)
Example:
def sample_function():
print('This is a user-defined function') sample_function()
Value-Returning Functions :
A value-returning function is a function that performs some task and then sends a value back
to the caller using the return statement. The returned value can be stored in a variable or used
in an expression.
Example
def add(a, b):
return a + b
result = add(5, 7)
print("Sum:", result)
Output
Sum: 12
Non-Value-Returning Functions:
Definition
A non-value-returning function is a function that performs a task (like printing or updating data) but
does not return any value using the return statement. If checked, its return value is None.
Example
def greet(name):
print("Hello,", name)
greet("Anita")
greet("Ravi")
Output
Hello, Anita
Hello, Ravi
Example
def addition(x, y):
result = x + y
print(f"Sum: {result}")
addition(2, 3)
Output:
Sum: 5
• Actual arguments provide the input values.
• Formal parameters act as placeholders for those values inside the function.
Mutable vs. Immutable Arguments
• When a function is called, the values of actual arguments are assigned to the corresponding formal
parameters.
• The behavior depends on whether the argument is mutable or immutable.
Immutable Arguments
• Immutable objects: int, float, string, tuple.
• Changes made inside the function do not affect the original object outside.
Example:
def change_value(x):
x = 50
a = 10
change_value(a)
print("Outside function:", a)
Output:
Outside function: 10
Mutable Arguments
• Mutable objects: list, dictionary, set.
• Changes made inside the function do affect the original object outside.
Example:
def modify_list(lst):
lst[0] = 100
numbers = [10, 20, 30]
modify_list(numbers)
print("Outside function:", numbers)
Output:
Outside function: [100, 20, 30]
Python function arguments
In Python, there are different ways to pass arguments to a function. They are as follows.
2. Default Arguments
➢ The default argument is an argument which is set with a default value in the function
definition.
➢ If the function is called with value then, the function executed with provided value,
otherwise, it executed with the default value given in the function definition.
Example:
3. Keyword Arguments
➢ The keyword argument is an argument passed as a value along with the parameter name
(parameter_name = value).
➢ When keyword arguments are used, we may ignore the order of arguments.
➢ We may pass the arguments in any order because the Python interpreter uses the
keyword provided to match with the respective parameter.
12
Example:
def student_info(rollNo, name, dept, year):
print(f'Roll Number : {rollNo}')
print(f'Student Name : {name}')
print(f'Department : {dept}')
print(f'Year of Study : {year}')
student_info(name='Rama', dept='CSE', rollNo=111, year=4)
Output:
Roll Number : 111
Student Name : Rama
Department : CSE
YearofStudy:4
Variable-length Arguments
➢ The Python provides variable-length of arguments which enable us to pass an arbitrary
number of arguments.
➢ Here, all the arguments are stored as a tuple of parameters in the function definition.
And they are accessed using the index values (similar to a tuple).
Example:
def largest(*numbers):
return max(numbers)
print(largest(20, 35))
print(largest(2, 5, 3))
print(largest(10, 40, 80, 50))
print(largest(16, 3, 9, 12, 44, 40))
Output:
35
5
80
44
Variable Scope:
variable scope refers to the region of a program where a variable is defined and can be accessed or modified.
Scoping rules determine the visibility and lifetime of a variable within different parts of a program.
Understanding variable scope is fundamental for writing modular, efficient, and error-free code.
Python uses the LEGB Rule for resolving variable names, which stands for Local, Enclosing, Global, and
Built-in scopes.
Local Scope (L)
Local Scope: Variables declared within a function or block have local scope, meaning they are only
accessible within that function or block.
Eg:
def local_example():
x=5
print("Inside function, x =", x)
local_example()
output:
Inside function, x = 5
Enclosing Scope
• This is the scope of any enclosing functions, used in nested functions.
• The inner function can access variables of the outer (enclosing) function but cannot modify them
directly unless using nonlocal.
Eg:
def outer():
message = "Hello"
def inner():
print("Inner says:", message)
inner()
outer()
output:
Inner says: Hello
Global Scope: Variables declared outside of any function or block have global scope, meaning they can be
accessed from anywhere in the program.
Eg:
x = 10
def show():
print("Inside function, x =", x)
show()
print("Outside function, x =", x)
output:
Inside function, x = 10
Outside function, x = 10
Built-in Scope
It is the outermost scope in Python.
It contains all the names that are pre-defined in Python (like functions, exceptions, constants, types).
Examples: print(), len(), max(), min(), int, str, etc.
Eg:
print(len("Hello"))
print(max([2, 8, 4]))
print(min([2, 8, 4]))
output:
5
8
2
Recursion:
Recursion is a programming technique where a function calls itself in order to solve a problem. Recursive
functions typically have two main parts:
Base Case: This is a condition that determines when the recursion should stop. Without a base case, the
function would continue to call itself indefinitely, leading to a stack overflow error.
Purpose:
• It prevents infinite recursion.
• Provides a direct solution to the simplest/smallest input.
Eg:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
output:
120
Recursive Case: This is the part of the function where it calls itself with a modified version of the input.
This repetition continues until the base case is reached.
Purpose:
• Breaks down a big problem into smaller subproblems.
• Moves the problem closer to the base case.
Eg:
def sum_numbers(n):
return n + sum_numbers(n - 1)
print(sum_numbers(5))
output:
Recursive case: n + sum_numbers(n-1)
Again, without base case → infinite recursion.
Result: RecursionError
UNIT 4
UNIT IV:
Objects and their use: Software Objects - Turtle Graphics – Turtle attributes Modular
Design: Modules - Top-Down Design - Python Modules - Text Files: Opening, reading
and writing text files – Exception Handling.
1. Introduction
In programming, especially in Object-Oriented Programming (OOP), the concept
of objects is fundamental.
A software object is a model or representation of a real-world entity. It contains:
• State (data, properties, or attributes).
• Behavior (functions or methods that define what the object can do).
Objects allow programmers to create modular, reusable, and realistic programs by
mapping real-world things into code.
2. Objects in Python
• In Python, everything is an object, including integers, strings, lists, functions,
and user-defined data structures.
• An object is always created from a class, which acts as a blueprint.
• A class defines the attributes (variables) and methods (functions), while the
object represents a specific instance of that class.
For example:
• A class Car defines properties like brand, color, and methods like drive(),
stop().
• An object like mycar = Car("Toyota", "Red") represents a specific car with
those features.
Example in Python
class Car:
def __init__(self, brand, color):
[Link] = brand
[Link] = color
def drive(self):
return f"{[Link]} {[Link]} is driving on the road"
def stop(self):
return f"{[Link]} {[Link]} has stopped"
# Creating objects
car1 = Car("Toyota", "Red")
car2 = Car("Honda", "Blue")
print([Link]())
print([Link]())
Output:
Red Toyota is driving on the road
Blue Honda has stopped
2. Basic Concepts
Turtle – a cursor shaped like an arrow that moves and draws on the screen.
Turtle
• The turtle is a small cursor, usually shaped like an arrow, that moves around
the screen.
• Wherever the turtle moves, it can draw a line (if the pen is down).
• It can be controlled by giving commands such as moving forward, turning left
or right, or lifting the pen.
• In Python, the turtle is created by calling [Link]().
Example:
import turtle
t = [Link]()
[Link](100)
[Link]()
Output: The turtle moves forward and draws a straight line.
2. Screen
• The screen is the drawing area where the turtle moves.
• It acts like a canvas or paper.
• The turtle starts at the center of the screen (0,0).
• The screen can be customized with a background color or title.
Example:
import turtle
s = [Link]()
[Link]("lightblue")
[Link]("My Turtle Screen")
t = [Link]()
[Link](50)
[Link]()
Output: A circle is drawn on a light blue background with the title "My Turtle
Screen".
3. Movement Commands
These commands control the movement of the turtle:
• forward(x) – moves the turtle forward by x units in the current direction.
• backward(x) – moves the turtle backward by x units.
• left(angle) – turns the turtle left by the given angle in degrees.
• right(angle) – turns the turtle right by the given angle in degrees.
Example:
import turtle
t = [Link]()
[Link](100)
[Link](90)
[Link](100)
[Link]()
Output: An L-shaped line.
4. Pen Control
Pen control commands decide how the turtle draws on the screen.
• penup() – lifts the pen; the turtle moves without drawing.
• pendown() – puts the pen down; the turtle draws while moving.
• color(c) – sets the pen color, e.g., color("red").
• pensize(n) – sets the thickness of the pen line.
Example:
import turtle
t = [Link]()
[Link](5)
[Link]("red")
[Link](100)
[Link]()
[Link](50)
[Link]()
[Link]("blue")
[Link](100)
[Link]()
Output: A thick red line, a gap, and then a blue line.
5. Shapes
Turtle can draw not only straight lines but also shapes such as circles, triangles,
rectangles, polygons, and even complex designs.
• circle(radius) – draws a circle of given radius.
• Polygons are drawn using loops with forward() and right()/left().
Example 1: Circle
import turtle
t = [Link]()
[Link](80)
[Link]()
Output: A circle with radius 80.
More examples:
Example A square.
import turtle
t = [Link]()
for i in range(4):
[Link](100)
[Link](90)
[Link]()
Output: A square.
Example : A Rectangle
import turtle
t = [Link]()
for i in range(2):
[Link](150)
[Link](90)
[Link](80)
[Link](90)
[Link]()
Output: A rectangle.
Turtle Attributes:
In the context of turtle graphics, a turtle object represents a cursor that moves around a
canvas, drawing lines and shapes. These turtle objects have various attributes that
control their appearance and behavior. Some common turtle attributes include:
Position: The turtle's position on the canvas, usually represented by its x and y
coordinates.
Direction: The direction the turtle is facing, often measured in degrees clockwise
from the positive x-axis.
Pen State: Whether the turtle's pen is up (not drawing) or down (drawing).
Pen Size: The width of the lines drawn by the turtle's pen.
Turtle Speed: The speed at which the turtle moves on the canvas.
These attributes can be manipulated to create various drawings and designs using
turtle graphics.
Reuse: Modular design encourages code reuse, as modules can be imported and used
in multiple parts of a program or in different projects.
Divide and Conquer: The problem is divided into smaller sub-problems that are
easier to solve individually. Each sub-problem is then further divided into even
smaller sub-problems, and so on, until the problems are small enough to be solved
directly.
Stepwise Refinement: The problem-solving process proceeds step by step, with each
step refining the solution and adding more detail. This iterative approach allows for a
gradual and systematic development of the solution.
Modularity: The solution is organized into modules or functions, each responsible for
a specific task or sub-problem. Modularity promotes code reuse, readability, and
maintainability.
Testing and Validation: At each level of refinement, the solution is tested and
validated to ensure that it meets the requirements and behaves as expected. This helps
in identifying and correcting errors early in the development process.
Python modules:
1. Introduction
A module in Python is a file containing code such as functions, variables, and
classes. Modules are used to organize programs, avoid repetition, and allow
reusability of code.
Python supports two main types of modules:
1. Built-in Modules – pre-installed with Python, ready for use.
2. User-Defined Modules – created by programmers to meet specific needs.
Both play a crucial role in software development by making programs modular,
manageable, and efficient.
2. Built-in Modules
Explanation
Built-in modules are part of Python’s Standard Library. They are already available
when Python is installed, so programmers can simply use them by importing. These
modules save time because programmers do not need to write basic logic themselves.
Explanation:
Built-in modules provide ready-made functions for mathematics, randomness, dates,
files, system-level operations, and text searching. They make Python powerful and
versatile without writing everything from scratch.
User-Defined Modules
Explanation
User-defined modules are created by programmers for specific purposes. They are
Python files (.py) that contain functions, variables, or classes.
Such modules are very useful in large projects where code can be organized into
multiple files and reused across programs.
4. Closing a File
Closing a file is necessary to release system resources and ensure data is written
properly. The close() method is used for this purpose.
Example:
file = open("[Link]", "r")
data = [Link]()
print(data)
[Link]()
Alternatively, the with statement can be used, which closes the file automatically after
execution.
Example:
with open("[Link]", "r") as file:
data = [Link]()
print(data)
4. Else Block
The else block is special. It runs only when no exception occurs in the try block. This
helps in separating the normal execution logic from the error-handling logic.
It is useful when you want to perform some task only if the risky code worked
correctly.
Example:
try:
num = int("123")
except ValueError:
print("Invalid input")
else:
print("Conversion successful:", num)
Output:
Conversion successful: 123
5. Finally Block
The finally block is always executed, whether there is an error or not. It is used for
cleanup operations such as closing files, disconnecting databases, or releasing
resources.
Even if an exception occurs and is not caught, the finally block will still run before the
program stops.
Example:
try:
f = open("[Link]", "w")
[Link]("Hello")
except Exception as e:
print("Error:", e)
finally:
[Link]()
print("File closed")
Output:
File closed