Unit Wise Notes
Unit Wise Notes
Unit I
Unit II
Installing and Using Python: Installing Python and Writing A Program, Writing Paragraphs of
Unit III
Variables and Expressions: Declaring variables, working with data types and variables, working
Unit IV
Conditional Code and Decision: Conditional Statements, Defining and writing decision
statements, Illustrative programs Loops and Iteration: Loops and iteration, defining loops,
Unit V
Functions: Define and use functions and modules, recursive functions, Illustrative programs
Department of Computer Science & Engineering
Why Program
Programming is one of the most powerful tools in the modern world, playing a vital role in
technology, science, business, and virtually every industry. Understanding why programming is
important involves recognizing its profound impact on our lives, as well as the unique
At its core, programming is about solving problems. Programmers create software that addresses
real-world challenges—whether it's designing apps that improve communication, algorithms that
predict market trends, or systems that streamline complex operations. Learning to program
allows individuals to think logically and break down large tasks into smaller, manageable pieces.
Programming enables the automation of repetitive tasks, freeing up time for more meaningful
work. From automating data entry to creating scripts that perform complex calculations, coding
allows businesses and individuals to boost productivity and reduce human error. In a world
Programming provides a platform for creativity. It allows you to build anything from mobile
apps and websites to interactive games and advanced AI models. The only limit is your
Department of Computer Science & Engineering
imagination. By writing code, you can bring ideas to life in a tangible form, whether it's
4. Career Opportunities
The demand for programming skills has skyrocketed, with software development being one of
the fastest-growing professions globally. Knowledge of coding is essential in tech careers, but it
is also increasingly valuable in fields like healthcare, finance, and media. Mastering
programming opens up a vast array of career opportunities, often with high earning potential and
flexibility.
In a world where technology is embedded in nearly every aspect of life, learning to program
helps you understand how things work behind the scenes. From social media algorithms to smart
home devices, programming knowledge gives you insight into the technology shaping the
Learning to program offers a sense of empowerment. You no longer rely on others to bring your
ideas to fruition; instead, you have the tools to build them yourself. Whether you're creating your
Hardware Overview
Hardware refers to the physical components of a computer system that are essential for its
operation. These components work together to execute tasks and run software, making the
Department of Computer Science & Engineering
overall system functional. Understanding the key elements of computer hardware provides
insight into how computers process information, store data, and interact with external devices.
The CPU, often called the "brain" of the computer, is responsible for executing instructions from
programs. It performs basic arithmetic, logic, control, and input/output (I/O) operations specified
by the instructions. The CPU typically consists of multiple cores, each capable of processing
tasks in parallel to increase efficiency. Faster CPUs enable computers to run complex programs
2. Memory (RAM)
Random Access Memory (RAM) is the temporary storage used by the CPU to store data that is
actively being used or processed. RAM allows for quick read and write access, which speeds up
data handling during program execution. The more RAM a system has, the better it can handle
3. Storage
Computer systems require long-term storage to save data and applications. There are two main
types of storage:
Hard Disk Drives (HDD): These use spinning disks to store data magnetically. HDDs
offer large capacities at a lower cost but are slower than SSDs.
Solid-State Drives (SSD): SSDs use flash memory to store data electronically, offering
much faster read/write speeds and durability compared to HDDs. SSDs are becoming the
4. Motherboard
Department of Computer Science & Engineering
The motherboard is the main circuit board that connects all of the computer's hardware
components. It houses the CPU, RAM, storage devices, and other components like the graphics
card. It also provides the pathways for data to travel between the different parts of the computer.
The motherboard includes essential ports for connecting external devices like USBs, monitors,
The power supply unit converts electrical power from an outlet into usable power for the
internal components of the computer. Different components require varying amounts of power,
and the PSU ensures a stable supply, providing the necessary voltage and current to the CPU,
The GPU, or graphics card, is responsible for rendering images, video, and animations. It is
particularly important for tasks like video editing, gaming, and 3D rendering, where visual
processing demands are high. GPUs come in two forms: integrated (built into the CPU) and
discrete (a separate component). Discrete GPUs are more powerful and are necessary for high-
Input devices include peripherals like keyboards, mice, microphones, and scanners,
Output devices display or transmit data from the computer to the user. Examples include
monitors, printers, and speakers. Both input and output devices connect to the
Computers generate heat during operation, particularly from the CPU and GPU. Cooling
systems, including fans and heat sinks, help dissipate this heat to prevent overheating and ensure
smooth performance. Advanced systems may use liquid cooling for better efficiency, especially
Network interface cards allow computers to connect to a network (local or internet) through
wired or wireless connections. A NIC can be built into the motherboard or installed as a separate
card. Modern systems often use Ethernet for wired connections and Wi-Fi for wireless
connectivity.
Peripheral devices are external devices connected to the computer, expanding its functionality.
These include:
External storage: USB drives or external hard drives for additional or portable data
storage.
experiences.
Python as a Language
readability, and versatility. It has become one of the most popular languages across many fields,
Department of Computer Science & Engineering
from web development to scientific computing, machine learning, data analysis, and automation.
Below are the key aspects that make Python stand out as a programming language:
Python’s syntax is designed to be clear and concise, resembling natural language. This makes it
an ideal language for beginners and experienced developers alike. Code written in Python is
typically easier to read and maintain compared to other languages, allowing developers to focus
Example:
print("Hello, World!")
2. Interpreted Language
Python is an interpreted language, which means that code is executed line by line, without the
need for compiling it beforehand. This allows for quick testing, debugging, and iteration, making
3. Cross-Platform Compatibility
Python is cross-platform, meaning it can run on different operating systems such as Windows,
macOS, and Linux without requiring modifications to the code. This flexibility makes Python a
go-to choice for developers who need to create software that works on multiple platforms.
One of Python's greatest strengths is its vast ecosystem of libraries and frameworks. Whether
you're working on data analysis, web development, machine learning, or automation, there’s a
APIs straightforward.
Data Science: Libraries such as Pandas, NumPy, and Matplotlib help with data
Automation: Tools like Selenium and Scrapy allow you to automate web scraping,
(OOP) and functional programming. This means developers can choose the approach that best
suits their project. Python’s OOP model is particularly useful for organizing and managing
complex code, while its support for functional programming allows for writing concise, elegant
class Dog:
self.name = name
self.age = age
def bark(self):
print(f"{self.name} is barking!")
Department of Computer Science & Engineering
my_dog = Dog("Buddy", 5)
my_dog.bark()
Python has a massive and active community of developers who contribute to its ecosystem. This
community-driven nature means that Python has abundant tutorials, documentation, forums, and
third-party libraries. If you encounter a problem or need help with a specific task, it's likely that
someone has already solved it, and resources are readily available online.
Python is dynamically typed, meaning you don’t need to declare the type of a variable when you
write code. This flexibility allows for quicker development, though it can also introduce bugs
that wouldn’t occur in statically typed languages. For example, Python automatically figures out
Example:
x = 10 # x is an integer
Web Development: Frameworks like Django and Flask simplify building secure,
Data Science: Python’s popularity in data analysis and machine learning is driven by
repetitive tasks, such as managing files, web scraping, or running scheduled jobs.
Scientific Computing: Python is widely used in scientific research, thanks to its libraries
Game Development: Python, along with frameworks like Pygame, is used for creating
simple 2D games.
Python easily integrates with other languages like C, C++, Java, and JavaScript. This makes it
possible to use Python in systems where high performance is required, and certain portions of the
code need to be written in a lower-level language for speed. It also facilitates the development of
Python is open-source, meaning it is free to use and distribute. Its development is governed by a
global community, and contributions come from developers around the world. Python’s open-
source nature ensures that it continues to evolve and stay relevant in the ever-changing landscape
of programming languages.
Department of Computer Science & Engineering
To get started with Python, you’ll need to install it on your computer and write your first
program. Here’s a step-by-step guide on how to install Python and write a simple program.
1. Installing Python
1. Download Python:
o Download the latest version of Python by clicking on the button that says
o During installation, make sure to check the box that says "Add Python to
PATH." This ensures you can run Python from the command line.
o Click "Install Now" and follow the prompts. Once installed, Python is ready to
use.
Once Python is installed, you can use the Python IDLE to run Program.
2. Save it as hello.py.
Hello, World!
Hello World
This is the simplest Python program that prints a string to the console.
print("Hello, World!")
Variables
age = 25
print(age)
Explanation:
there are several rules and best practices you need to follow:
1. Valid Names
Variable names must begin with a letter (a-z, A-Z) or an underscore (_).
The rest of the variable name can include letters, digits (0-9), or underscores.
valid_var = 10 # valid
_anotherVar = 20 # valid
2. Case Sensitivity
Variable names are case-sensitive, meaning age, Age, and AGE are considered different
variables.
age = 25
Age = 30
AGE = 35
3. No Reserved Keywords
You cannot use Python keywords (reserved words) as variable names. Examples of
keywords include if, else, while, for, class, def, return, etc.
import keyword
print(keyword.kwlist)
Department of Computer Science & Engineering
4. Avoid Special Characters
5. No Spaces
Spaces are not allowed in variable names. Use underscores (_) or camelCase to combine
words.
6. Assignment
x=5
y = "Hello"
7. Dynamic Typing
Python is dynamically typed, meaning variables do not need an explicit type declaration.
a = 10 # Integer
x, y, z = 1, 2, 3 # Multiple assignment
Data Types
Numbers:
Numeric values are stored in numbers. The whole number, float, and complex qualities
Int:
Department of Computer Science & Engineering
Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and
so on. An integer can be any length you want in Python. It’s worth has a place
with int.
Float:
Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to
Complex:
An intricate number contains an arranged pair, i.e., x + iy, where x and y signify
the genuine and non-existent parts separately. The complex numbers like 2.14j,
Sequence Type :
String :
The sequence of characters in the quotation marks can be used to describe the
string. A string can be defined in Python using single, double, or triple quotes.
Lists :
Lists in Python are like arrays in C, but lists can contain data of different types.
The things put away in the rundown are isolated with a comma (,) and encased
To gain access to the list's data, we can use slice [:] operators. Like how they
worked with strings, the list is handled by the concatenation operator (+) and the
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of
items from various data types. A parenthetical space () separates the tuple's
Because we cannot alter the size or value of the items in a tuple, it is a read-only
data structure.
Dictionary :
A dictionary is a key-value pair set arranged in any order. It stores a specific value for
each key, like an associative array or a hash table. Value is any Python object, while the
key can hold any primitive data type.The comma (,) and the curly braces are used to
Boolean :
True and False are the two default values for the Boolean type. These qualities are
utilized to decide the given assertion valid or misleading. The class book indicates this.
False can be represented by the 0 or the letter "F," while true can be represented by any
Set :
The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It
might return the element's altered sequence. Either a sequence of elements is passed
through the curly braces and separated by a comma to create the set or the built-in
function set() is used to create the set. It can contain different kinds of values.
Department of Computer Science & Engineering
# Simple Python Data Types Program
# Integer
x = 10
print("Integer:", x)
# Float
y = 10.5
print("Float:", y)
# String
name = "Alice"
print("String:", name)
# Boolean
is_valid = True
print("Boolean:", is_valid)
1. Arithmetic Operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus (remainder) x % y
** Exponentiation x ** y
// Floor Division x // y
Department of Computer Science & Engineering
x = 10
y=3
print(x + y) # 13
print(x - y) # 7
print(x * y) # 30
print(x / y) # 3.3333
2. Comparison Operators
== Equal to x == y
!= Not equal to x != y
y=3
print(x == y) # False
print(x != y) # True
3. Logical Operators
x = 10
y=3
4. Assignment Operators
Department of Computer Science & Engineering
Used to assign values to variables.
= Assign value x = 10
x = 10
x += 5 # x = x + 5, so x becomes 15
print(x) # 15
x *= 2 # x = x * 2, so x becomes 30
print(x) # 30
5. Bitwise Operators
` ` OR
^ XOR x^y
~ NOT ~x
x = 5 # Binary: 0101
y = 3 # Binary: 0011
print("Hello, World!")
2. Save it as hello.py.
Hello, World!
Explanation:
"Hello, World!" is a string of text, and when passed into the print() function, it
Variables and Expressions: Declaring variables, working with data types and variables, working
Variables:
A variable is a symbol or name that stands for a value, which can change. Variables are like
containers that store information. In programming, variables are used to store data, while in
mathematics, they typically represent unknown or changing values.
Example in Math:
o Let x=5. Here, x is a variable that holds the value 5.
Example in Programming (Python):
x = 5
In Python, variables are used to store data values. Unlike some programming languages, Python
does not require you to declare the variable type explicitly; it is dynamically typed, meaning you
can change the type of the data stored in a variable at any time. Here’s a brief overview of how
to work with variables in Python:
Creating Variables
You can change the type of a variable by simply assigning a new value.
Multiple Assignments
a, b, c = 1, 2, 3 # a = 1, b = 2, c = 3
Constants
While Python doesn’t have a built-in constant type, by convention, constants are defined using
uppercase letters.
PI = 3.14159
You can check the type of a variable using the type() function.
Deleting Variables
Example Usage
# Defining variables
name = "Alice"
age = 30
# Outputting a message
print(f"{name} is {age} years old.")
Department of Computer Science & Engineering
Declaration of Variables
In Python, you declare a variable simply by assigning it a value. You don’t need to specify a data
type; Python infers it from the assigned value.
Example:
# Variable declaration
x = 10 # x is an integer
name = "Alice" # name is a string
price = 19.99 # price is a float
Re-declaration of Variables
You can redeclare a variable by assigning a new value to it. The new value can be of a different
type from the previous value.
Example:
# Redeclaring variable
x = 10 # x is initially an integer
print(x) # Output: 10
In Python, you can declare variables without explicitly specifying their data types. Python uses
dynamic typing, meaning that the type of a variable is inferred from the value it is assigned.
Here’s a quick overview of common data types in Python and examples of how to declare
variables:
1. Numeric Types
# Integer
age = 25
# Float
height = 5.9
Department of Computer Science & Engineering
# Complex
complex_num = 2 + 3j
2. String
name = "Alice"
greeting = 'Hello, World!'
3. Boolean
is_student = True
is_employed = False
4. Sequence Types
# List
fruits = ['apple', 'banana', 'cherry']
# Tuple
coordinates = (10.0, 20.0)
5. Set
unique_numbers = {1, 2, 3, 4, 5}
6. Dictionary
person = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
7. NoneType
Department of Computer Science & Engineering
Represents the absence of a value.
value = None
Summary
Integers (int): Whole numbers, both positive and negative (e.g., 5, -10).
Floating-point numbers (float): Numbers with decimal points (e.g., 3.14, -0.001).
Complex numbers (complex): Numbers with a real and imaginary part (e.g., 3 + 4j).
You can perform arithmetic operations on numeric types using standard operators:
Addition: +
Subtraction: -
Multiplication: *
Division: / (returns a float)
Integer Division: // (returns an integer)
Modulus: % (returns the remainder)
Exponentiation: ** (raises to a power)
Department of Computer Science & Engineering
a = 10
b=5
addition = a + b # 15
subtraction = a - b # 5
multiplication = a * b # 50
division = a / b # 2.0
Working with string data in Python involves using various operations and methods to manipulate
and analyze strings. Here's a comprehensive overview of string handling in Python, complete
with explanations and examples.
1. Creating Strings
You can create strings using single quotes ('), double quotes ("), or triple quotes (''' or """) for
multi-line strings.
# Multi-line string
multi_line = '''This is a multi-line
string that spans multiple
lines.'''
2. Accessing Characters
You can access individual characters in a string using indexing, where the index starts from 0.
my_string = "Python"
first_char = my_string[0] # 'P'
last_char = my_string[-1] # 'n'
3. String Length
length = len(my_string) # 6
4. String Slicing
Department of Computer Science & Engineering
You can extract parts of a string using slicing.
5. String Concatenation
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!" # 'Hello, Alice!'
6. String Formatting
age = 30
formatted_string = f"My name is {name} and I am {age} years old." # 'My name
is Alice and I am 30 years old.'
str.format() method:
Python provides many built-in string methods for manipulating strings. Here are some
commonly used ones:
8. Checking Substrings
You can check if a substring exists within a string using the in keyword.
9. String Immutability
Strings in Python are immutable, meaning that once a string is created, it cannot be changed.
Operations that modify strings will return a new string instead of modifying the original.
original_string = "Hello"
new_string = original_string.replace('H', 'J') # 'Jello'
# original_string is still 'Hello'
To include special characters in strings, you can use escape characters, like \n for a new line, \t
for a tab, and \\ for a backslash.
Expression
42 # An integer literal
3.14 # A float literal
"Hello" # A string literal
2. Arithmetic Expressions
3. Comparison Expressions
These expressions compare two values and return a boolean value (True or False).
Operators: Common comparison operators include ==, !=, >, <, >=, and <=.
4. Logical Expressions
Logical expressions combine boolean values using logical operators and return a boolean value.
5. Compound Expressions
x = 5
Department of Computer Science & Engineering
y = 10
result = (x + y) * 2 > 20 # Evaluates to False (30 > 20 is True, but the
entire expression is still just an expression)
Function calls can also be considered expressions because they return a value.
Conditional Statements
Conditional statements are programming constructs that execute different code paths based on
whether a condition is true or false. They are fundamental in decision-making processes within
algorithms. Here’s a brief overview:
Basic Structure
1. If Statement: Executes a block of code if the condition is true.
if condition:
# code to execute if condition is true
2. Else Statement: Executes a block of code if the condition is false.
if condition:
# code if true
else:
# code if false
3. Elif (Else If): Checks additional conditions if the previous conditions are false.
if condition1:
# code if condition1 is true
elif condition2:
# code if condition2 is true
else:
# code if both conditions are false
Example in Python
age = 18
# Using continue
for i in range(5):
if i == 2:
continue # Skips the rest of the loop body when i is 2
print(i)
Definition of Loops
Loops: A loop is a programming structure that repeats a sequence of instructions until a specific
condition is met or until all items in a collection have been processed. They are used to automate
repetitive tasks and can help reduce code duplication.
Department of Computer Science & Engineering
Types of Loops
1. For Loop: Used to iterate over a sequence (like a list, tuple, string, or range) and execute
a block of code for each item in that sequence.
2. While Loop: Executes a block of code as long as a specified condition is true. This loop
checks the condition before each iteration.
Syntax and Usage
1. For Loop
Syntax:
for variable in iterable:
# Code to execute for each item
Example:
# Iterating over a list
animals = ["dog", "cat", "rabbit"]
for animal in animals:
print(animal)
2. While Loop
Syntax:
while condition:
# Code to execute while the condition is true
Example:
# Simple countdown using a while loop
count = 5
while count > 0:
print(count)
count -= 1 # Decrement the counter
Key Characteristics
Iteration: Each time the loop executes, it’s called an iteration. In a for loop, each item
from the iterable is processed once. In a while loop, iterations continue as long as the
condition remains true.
Department of Computer Science & Engineering
Termination: A loop must eventually terminate; otherwise, it will result in an infinite
loop. For for loops, this is controlled by the length of the iterable. For while loops, it
relies on the condition to eventually become false.
Loop Control Statements
break: Exits the loop immediately.
continue: Skips the current iteration and proceeds to the next one.
pass: Does nothing and acts as a placeholder.
Definition of Recursion
Recursion: A method of solving a problem where the solution depends on solutions to smaller
instances of the same problem. A recursive function typically has two main components:
1. Base Case: A condition under which the function stops calling itself, preventing infinite
recursion.
2. Recursive Case: The part of the function that calls itself with a modified argument,
moving towards the base case.
How Recursion Works
1. The function checks if it meets the base case.
2. If it does, it returns a result directly.
3. If it doesn’t, it performs some operations and calls itself with a new argument.
4. This process continues until the base case is reached.
Example: Factorial
The factorial of a number nnn (denoted as n!n!n!) is the product of all positive integers up to
nnn.
Recursive Definition:
Base Case: 0!=10! = 10!=1
Recursive Case: n!=n×(n−1)!n! = n \times (n-1)!n!=n×(n−1)!
Python Implementation
def factorial(n):
# Base case
if n == 0:
Department of Computer Science & Engineering
return 1
# Recursive case
return n * factorial(n - 1)
Illustrative programs
1. Factorial Calculation (Recursion)
This program calculates the factorial of a number using recursion.
Department of Computer Science & Engineering
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
# Test the function
num = 5
print(f"The factorial of {num} is {factorial(num)}") # Output: 120
2. Fibonacci Series (Recursion)
This program generates the Fibonacci series up to a specified number of terms using recursion.
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
# Test the function
terms = 6
print("Fibonacci series:")
for i in range(terms):
print(fibonacci(i), end=' ') # Output: 0 1 1 2 3 5
3. Simple Calculator (Decision Statements)
This program performs basic arithmetic operations based on user input.
def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
Department of Computer Science & Engineering
choice = input("Enter choice (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = num1 + num2
print(f"The result is: {result}")
elif choice == '2':
result = num1 - num2
print(f"The result is: {result}")
elif choice == '3':
result = num1 * num2
print(f"The result is: {result}")
elif choice == '4':
if num2 != 0:
result = num1 / num2
print(f"The result is: {result}")
else:
print("Error: Division by zero.")
else:
print("Invalid input.")
# Run the calculator
calculator()
4. Prime Number Checker (Loop and Decision Statements)
This program checks if a number is prime.
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
Department of Computer Science & Engineering
return False
return True
# Test the function
number = 29
if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
5. Simple Guessing Game (Loops)
This program implements a simple number guessing game.
import random
def guessing_game():
number_to_guess = random.randint(1, 100)
attempts = 0
guess = 0
print("Guess the number between 1 and 100!")
while guess != number_to_guess:
guess = int(input("Enter your guess: "))
attempts += 1
if guess < number_to_guess:
print("Too low! Try again.")
elif guess > number_to_guess:
print("Too high! Try again.")
else:
print(f"Congratulations! You've guessed the number in {attempts} attempts.")
# Run the guessing game
guessing_game()
Department of Computer Science & Engineering
Functions in Python
A function is a block of code designed to perform a specific task. It can take inputs, process
them, and return an output.
Defining a Function
To define a function, you use the def keyword followed by the function name and parentheses.
Here’s an example:
Using a Function
result = add_numbers(5, 3)
print(result) # Output: 8
Modules in Python
A module is a file that contains Python code, such as functions and variables, which can be
imported into other Python scripts. This allows you to organize your code better and reuse it
across different programs.
Creating a Module
# math_operations.py
Using a Module
To use the functions from your module, you can import it into another Python file.
# main.py
import math_operations
Summary
Recursive functions
Recursive functions are functions that call themselves in order to solve a problem. They typically
break down a problem into smaller subproblems and solve each one until reaching a base case,
which stops the recursion.
The factorial of a number nnn (denoted as n!n!n!) is the product of all positive integers up to
nnn. The recursive definition is:
Here’s how you can implement the factorial function recursively in Python:
def factorial(n):
"""Calculate the factorial of n using recursion."""
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)
Another common example of a recursive function is calculating the Fibonacci sequence, where
each number is the sum of the two preceding ones:
F(0)=0F(0) = 0F(0)=0
F(1)=1F(1) = 1F(1)=1
F(n)=F(n−1)+F(n−2)F(n) = F(n - 1) + F(n - 2)F(n)=F(n−1)+F(n−2)
Considerations
Efficiency: Recursive functions can be less efficient than iterative solutions, especially if they
compute the same values multiple times (as in the Fibonacci example). Techniques like
memoization can help improve performance.
Stack Overflow: Too many recursive calls can lead to a stack overflow error. Ensure that the
base case is reached to avoid infinite recursion.
Illustrative programs
1. Factorial Calculation
def factorial(n):
"""Calculate the factorial of n using recursion."""
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)
# Example usage
number = 5
print(f"Factorial of {number} is {factorial(number)}") # Output: 120
2. Fibonacci Sequence
def fibonacci(n):
"""Calculate the nth Fibonacci number using recursion."""
if n == 0: # Base case
return 0
elif n == 1: # Base case
return 1
else: # Recursive case
return fibonacci(n - 1) + fibonacci(n - 2)
# Example usage
n = 10
print(f"The {n}th Fibonacci number is {fibonacci(n)}") # Output: 55
3. Sum of a List
This program calculates the sum of all elements in a list using recursion.
Department of Computer Science & Engineering
def sum_list(lst):
"""Calculate the sum of a list using recursion."""
if not lst: # Base case: if the list is empty
return 0
else: # Recursive case
return lst[0] + sum_list(lst[1:])
# Example usage
numbers = [1, 2, 3, 4, 5]
print(f"The sum of the list is {sum_list(numbers)}") # Output: 15
4. Reverse a String
def reverse_string(s):
"""Reverse a string using recursion."""
if len(s) == 0: # Base case: empty string
return s
else: # Recursive case
return s[-1] + reverse_string(s[:-1])
# Example usage
string = "Hello"
print(f"The reverse of '{string}' is '{reverse_string(string)}'") # Output:
olleH