Thursday, October 8, 2026

Python Modules and Packages

 

Python Modules and Packages – Organize Your Python Programs Like a Pro

When Python programs become bigger, putting everything into one file can make the code difficult to understand, maintain, and reuse.

Imagine you have a school bag containing books for Maths, Science, English, and Computer Science. Would you put everything into one notebook?

Probably not!

You would keep different subjects in different notebooks and organize them properly.

Python provides Modules and Packages to do exactly the same thing with programs.

In this Python Pebbles tutorial, we will learn:

  • What is a module?

  • How import works

  • from ... import

  • Built-in modules

  • The math module

  • The random module

  • The datetime module

  • The os module

  • The statistics module

  • How to create your own module

  • What are packages?

  • How to install packages using pip

  • Practice questions

  • Mini challenges

  • A master project


1. What is a Module?

A module is simply a Python file containing Python code.

A module can contain:

  • Variables

  • Functions

  • Classes

  • Statements

A Python module normally has the extension:

.py

For example:

calculator.py

can contain:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

Now another Python program can use these functions instead of writing them again.

Think of a module as a toolbox

Imagine you have a toolbox containing:

hammer
screwdriver
spanner
pliers

Instead of carrying every tool separately, you carry the toolbox.

Similarly, a Python module can contain a collection of useful functions.

calculator.py
       |
       +-- add()
       +-- subtract()
       +-- multiply()
       +-- divide()

Other Python programs can use these functions.


2. Why Do We Need Modules?

Modules provide several advantages.

1. Code Reusability

Write a function once and use it in multiple programs.

2. Better Organization

Large programs can be divided into smaller files.

3. Easier Maintenance

If something needs to be changed, you can modify the appropriate module.

4. Avoid Repeating Code

You don't need to write the same functions again and again.

5. Collaboration

Different programmers can work on different modules.


3. The import Statement

Python provides the import statement to use a module.

For example:

import math

Now we can use functions available inside the math module.

import math

print(math.sqrt(25))

Output:

5.0

Notice the syntax:

module_name.function_name()

Here:

math.sqrt()

means:

Use the sqrt() function from the math module.


4. Importing More Than One Module

We can import multiple modules.

import math
import random
import statistics

Now all three modules are available to our program.


5. Importing a Module with an Alias

Sometimes a module name can be long.

We can give it another name using as.

import statistics as stats

Now we can write:

print(stats.mean([10, 20, 30]))

Output:

20

The general syntax is:

import module_name as short_name

For example:

import math as m

print(m.sqrt(81))

Output:

9.0

6. from ... import

Sometimes we don't want to import the entire module.

We can import a particular function.

For example:

from math import sqrt

Now we can directly use:

print(sqrt(49))

Output:

7.0

Notice that we don't need:

math.sqrt()

We can simply write:

sqrt()

7. Importing Multiple Functions

We can import multiple functions.

from math import sqrt, factorial, ceil

Example:

print(sqrt(64))
print(factorial(5))
print(ceil(4.2))

Output:

8.0
120
5

8. import vs from ... import

Let's compare.

Using import

import math

print(math.sqrt(100))

Using from ... import

from math import sqrt

print(sqrt(100))

Both produce:

10.0

Python Pebble

Using:

import math

makes it very clear where sqrt() came from:

math.sqrt()

This can make larger programs easier to understand.


9. Built-in Modules

Python comes with a large collection of modules.

These are often called standard library modules.

You don't normally need to install them separately.

Some useful modules are:

ModuleCommon Use
mathMathematical operations
randomRandom numbers and choices
datetimeDates and time
osOperating-system operations
statisticsStatistical calculations

Let's explore them one by one.


10. The math Module

The math module provides many mathematical functions and constants.

First:

import math

Square Root

print(math.sqrt(81))

Output:

9.0

Power

print(math.pow(2, 5))

Output:

32.0

Factorial

print(math.factorial(5))

Output:

120

Because:

5! = 5 × 4 × 3 × 2 × 1

Ceiling

ceil() rounds a number upward.

print(math.ceil(4.2))

Output:

5

Floor

floor() rounds a number downward.

print(math.floor(4.9))

Output:

4

Mathematical Constants

Python provides useful constants.

print(math.pi)

Output will be approximately:

3.141592653589793

Example:

radius = 5

area = math.pi * radius * radius

print("Area =", area)

11. The random Module

Computers normally generate pseudo-random values.

Python provides the random module for generating random values.

Start with:

import random

Generate a Random Number

print(random.randint(1, 10))

Possible output:

7

Another run could produce:

3

The result can change each time.


Random Number Between Two Values

number = random.randint(100, 999)

print(number)

This generates a random integer between 100 and 999, inclusive.


Random Choice

Suppose we have:

colors = ["Red", "Green", "Blue", "Yellow"]

We can randomly select one:

print(random.choice(colors))

Possible output:

Blue

Randomly Select a Student

students = ["Raman", "Aman", "Riya", "Neha"]

winner = random.choice(students)

print("Winner:", winner)

Possible output:

Winner: Riya

Shuffle a List

numbers = [1, 2, 3, 4, 5]

random.shuffle(numbers)

print(numbers)

Possible output:

[3, 1, 5, 2, 4]

The order may be different every time.

Mini Challenge

Create a program that randomly selects one number from:

1 to 100

and prints:

Lucky Number: <number>

12. The datetime Module

The datetime module is used for working with:

  • Dates

  • Times

  • Date and time calculations

Import it:

import datetime

Get Current Date and Time

now = datetime.datetime.now()

print(now)

Possible output:

2026-10-08 15:30:25.123456

The exact result depends on when the program is executed.


Get Today's Date

today = datetime.date.today()

print(today)

Possible output:

2026-10-08

Extract Year, Month and Day

today = datetime.date.today()

print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)

Create a Specific Date

birthday = datetime.date(2012, 8, 15)

print(birthday)

Output:

2012-08-15

Calculate Difference Between Dates

today = datetime.date.today()
exam_date = datetime.date(2026, 12, 1)

remaining = exam_date - today

print("Days remaining:", remaining.days)

This is useful for creating:

  • Exam countdowns

  • Birthday reminders

  • Project deadlines

  • Event countdowns

Python Pebble

Dates can be subtracted to calculate the difference between them.


13. The os Module

The os module allows Python to interact with the operating system.

Import it:

import os

It can be used for tasks such as:

  • Working with folders

  • Checking files

  • Getting the current directory

  • Creating directories

  • Listing directory contents


Current Working Directory

print(os.getcwd())

getcwd() means:

Get Current Working Directory

Possible output:

C:\Users\Student\PythonProjects

List Files and Folders

print(os.listdir())

Possible output:

['program.py', 'data.txt', 'images', 'projects']

Create a Folder

os.mkdir("PythonProjects")

This creates a folder named:

PythonProjects

Be careful: if the folder already exists, Python will raise an error.


Check Whether a File Exists

import os

if os.path.exists("data.txt"):
    print("File exists")
else:
    print("File does not exist")

This is extremely useful in real-world programs.


14. The statistics Module

The statistics module provides common statistical functions.

Import it:

import statistics

Mean

The mean is the average.

marks = [70, 80, 90, 60, 100]

print(statistics.mean(marks))

Output:

80

Median

numbers = [10, 20, 30, 40, 50]

print(statistics.median(numbers))

Output:

30

Mode

Mode is the value that occurs most frequently.

numbers = [10, 20, 20, 30, 20, 40]

print(statistics.mode(numbers))

Output:

20

Complete Example

import statistics

marks = [78, 85, 92, 67, 88]

print("Mean:", statistics.mean(marks))
print("Median:", statistics.median(marks))
print("Mode:", statistics.mode(marks))

15. Creating Your Own Module

One of the most useful features of Python is that you can create your own modules.

Suppose we create a file:

calculator.py

Add:

def add(a, b):
    return a + b


def subtract(a, b):
    return a - b


def multiply(a, b):
    return a * b


def divide(a, b):
    return a / b

Now create another file:

main.py

We can import our module:

import calculator

Then:

print(calculator.add(10, 5))
print(calculator.subtract(10, 5))
print(calculator.multiply(10, 5))
print(calculator.divide(10, 5))

Output:

15
5
50
2.0

16. Understanding the Folder Structure

Our project may look like this:

MyProject/
│
├── main.py
└── calculator.py

calculator.py is our module.

main.py is the program that uses it.

This is the beginning of writing well-organized Python programs.


17. Importing Specific Functions from Your Module

Instead of:

import calculator

print(calculator.add(10, 20))

we can write:

from calculator import add

print(add(10, 20))

Output:

30

We can also import multiple functions:

from calculator import add, multiply

print(add(5, 10))
print(multiply(5, 10))

18. The __name__ Check

You may see this statement in Python modules:

if __name__ == "__main__":

For example:

def add(a, b):
    return a + b


if __name__ == "__main__":
    print(add(10, 20))

This allows us to run some code only when the file is executed directly.

It will not run that section when the module is imported by another program.

Python Pebble

Think of it as:

"Run this part only when I am the main program."

This becomes especially useful when creating reusable modules.


19. What is a Package?

A package is a way of organizing multiple Python modules.

Think about the difference:

Module
   ↓
One Python file

while:

Package
   ↓
Folder
   ├── module1.py
   ├── module2.py
   └── module3.py

A package helps organize larger projects.


20. Example of a Package

Suppose we create:

school/
│
├── maths.py
├── science.py
└── english.py

The folder school can be used to organize modules related to school subjects.

For example:

maths.py

def square(n):
    return n * n

science.py

def gravity():
    return 9.8

We can import them using:

from school import maths

print(maths.square(5))

Output:

25

Or:

from school.maths import square

print(square(8))

Output:

64

21. Package Structure

A larger project could look like:

MyProject/
│
├── main.py
│
└── school/
    ├── __init__.py
    ├── maths.py
    ├── science.py
    └── english.py

The __init__.py file has traditionally been used to identify a directory as a Python package.

Modern Python also supports namespace packages, so __init__.py is not always required. For beginners, however, it is useful to understand it as part of the traditional package structure.


22. Installing Packages with pip

Python has a huge ecosystem of third-party packages.

Examples include packages for:

  • Data analysis

  • Machine learning

  • Web development

  • Automation

  • Visualization

  • Artificial intelligence

  • Scientific computing

One of the most common tools used to install Python packages is:

pip

23. What is pip?

pip is Python's package installer.

It allows us to install packages from the Python Package Index, commonly known as PyPI.

For example:

pip install requests

This installs the requests package.

Then we can use it in Python:

import requests

24. Installing Popular Python Packages

For example:

pip install numpy
pip install pandas
pip install matplotlib
pip install yfinance

These packages are commonly used in data analysis, visualization, finance and other Python applications.


25. Checking Installed Packages

You can use:

pip list

This displays packages installed in your Python environment.

You can also check a particular package:

pip show numpy

26. Upgrading a Package

To upgrade a package:

pip install --upgrade numpy

27. Uninstalling a Package

To remove a package:

pip uninstall numpy

Python will normally ask for confirmation before uninstalling it.


28. Installing Packages in Google Colab

If you are working in Google Colab, you can install packages using:

!pip install package_name

For example:

!pip install yfinance

After installation:

import yfinance as yf

Python Pebble

The ! tells a Colab/Jupyter notebook to execute the command through the system shell rather than as normal Python syntax.


29. Module vs Package

Let's make the difference crystal clear.

FeatureModulePackage
Basic ideaPython fileCollection of modules
Usually.py fileDirectory/folder
PurposeOrganize reusable codeOrganize larger collections of code
Examplecalculator.pyschool/
Can containFunctions, classes, variablesMultiple modules

Think:

Module = Notebook
Package = School Bag containing multiple notebooks

30. Standard Library vs Third-Party Packages

This is an important distinction.

Standard Library

These are provided with Python.

Examples:

import math
import random
import datetime
import os
import statistics

You normally don't install these using pip.

Third-Party Packages

These are developed and distributed separately.

Examples:

numpy
pandas
matplotlib
requests
yfinance

These may need to be installed using:

pip install package_name

31. Real-World Example – Student Marks Analyzer

Let's combine modules.

import statistics
import random

marks = [78, 85, 92, 67, 88]

average = statistics.mean(marks)

print("Marks:", marks)
print("Average:", average)

print("Lucky Number:", random.randint(1, 100))

Possible output:

Marks: [78, 85, 92, 67, 88]
Average: 82
Lucky Number: 47

We have used two modules in one program.


32. Real-World Example – Exam Countdown

import datetime

today = datetime.date.today()

exam_date = datetime.date(2026, 12, 1)

days_left = exam_date - today

print("Today:", today)
print("Exam Date:", exam_date)
print("Days Left:", days_left.days)

This could become the foundation of a useful Exam Countdown App.


33. Real-World Example – Random Quiz Question

Suppose we have:

import random

questions = [
    "What is Python?",
    "What is a variable?",
    "What is a module?",
    "What is a package?"
]

question = random.choice(questions)

print("Today's Question:")
print(question)

Every time the program runs, a different question may be selected.


34. A Simple Module-Based Project

Let's build a small project.

Project: Student Utility Toolkit

Folder structure:

StudentToolkit/
│
├── main.py
└── student_utils.py

student_utils.py

def percentage(marks):
    return sum(marks) / len(marks)


def highest(marks):
    return max(marks)


def lowest(marks):
    return min(marks)

main.py

import student_utils

marks = [85, 92, 76, 88, 95]

print("Average:", student_utils.percentage(marks))
print("Highest:", student_utils.highest(marks))
print("Lowest:", student_utils.lowest(marks))

Output:

Average: 87.2
Highest: 95
Lowest: 76

Congratulations!

You have just created your own reusable Python module.


35. Common Mistakes

Mistake 1: Wrong module name

import maths

when you actually wanted:

import math

Python module names must be correct.


Mistake 2: Forgetting the module name

If you write:

import math

print(sqrt(25))

you may get an error because sqrt was not imported directly.

Correct:

print(math.sqrt(25))

Or:

from math import sqrt

print(sqrt(25))

Mistake 3: Installing a standard library module

You don't normally need:

pip install math

because math is already part of Python's standard library.


Mistake 4: Naming your file after a standard module

Avoid naming your own files:

math.py
random.py
statistics.py
os.py

because your file may interfere with Python's standard modules.

Prefer names such as:

my_math.py
student_tools.py
quiz_utils.py

36. Practice Time

Level 1 – Beginner

Q1

What is a Python module?

Q2

Which statement is used to import a module?

Q3

Write the statement to import the math module.

Q4

Write a program to find the square root of 144.

Q5

Which module can be used to generate random numbers?

Q6

Write a program to generate a random number between 1 and 50.

Q7

Which module is used for dates and time?

Q8

Which module can be used to calculate the mean of a list?

Q9

What does pip do?

Q10

What is the difference between a module and a package?


37. Level 2 – Coding Practice

Q11

Write a program using math to calculate the area of a circle.

Input:

Radius = 7

Q12

Generate five random numbers between 1 and 100.


Q13

Create a program that randomly selects one student from:

["Aman", "Riya", "Raman", "Neha", "Arjun"]

Q14

Write a program that calculates the number of days between two dates.


Q15

Use the statistics module to calculate:

  • Mean

  • Median

  • Mode

for:

[10, 20, 20, 30, 40, 20]

38. Level 3 – Create Your Own Module

Create a module:

calculator.py

with these functions:

add()
subtract()
multiply()
divide()

Then create:

main.py

and import the functions.


39. Master Challenge – Student Result Analyzer

Create a Python project using modules.

Requirements

Create:

StudentResult/
│
├── main.py
└── result_utils.py

The module should contain functions for:

average()
highest()
lowest()
percentage()
grade()

The main program should:

  1. Accept marks for five subjects.

  2. Calculate total marks.

  3. Calculate percentage.

  4. Find highest marks.

  5. Find lowest marks.

  6. Calculate average.

  7. Assign a grade.

  8. Display the result.

Bonus Challenge

Add:

random

to generate sample marks for testing.


40. Quick Revision

ConceptRemember
ModulePython file containing reusable code
importImports a module
from ... importImports selected items
mathMathematical functions
randomRandom values and choices
datetimeDate and time
osOperating-system interaction
statisticsStatistical calculations
Own moduleA .py file created by you
PackageCollection/organization of modules
pipPython package installer

41. Python Pebble 🪨

Don't write the same code again and again.

Put reusable code into a module and use it whenever you need it.

A good Python programmer doesn't just ask:

"How do I make this program work?"

A better question is:

"How can I organize this code so that I can reuse it later?"

That is where Modules and Packages become powerful.


42. What You Learned

In this tutorial, you learned:

✅ What a module is
✅ How import works
✅ How from ... import works
✅ Built-in Python modules
✅ math
✅ random
✅ datetime
✅ os
✅ statistics
✅ Creating your own module
✅ Packages
✅ Installing packages using pip
✅ Using modules in real-world projects

The next time your Python program becomes too large, don't put everything into one file.

Break it into modules. Organize modules into packages. Reuse your code.

That's how small Python programs gradually become well-structured software projects.

Tuesday, October 6, 2026

📖 File Handling in Python – Save, Read and Manage Your Data

 

Learn • Experiment • Solve • Build

“A program that forgets everything when it closes isn't very useful. File handling teaches Python how to remember!”


🌟 Welcome to File Handling!

Imagine you create a Python program that stores student marks.

You run the program:

Raman - 92
Aman  - 85
Priya - 96

Everything works perfectly.

But then you close Python.

The next time you run the program...

Everything is gone! 😱

Why?

Because the data was stored only in the computer's memory.

To permanently store information, we can use files.

Python Program
      ↓
   Data
      ↓
   File
      ↓
Saved permanently

This is called File Handling.


1. What is File Handling?

File handling means using Python to:

  • Create files

  • Open files

  • Read files

  • Write files

  • Add new information

  • Modify stored information

  • Work with structured data

  • Handle file-related errors

For example, Python can work with:

students.txt
marks.csv
students.json

2. Why Do We Need Files?

Consider a school management program.

It might need to store:

Student Name
Roll Number
Class
Marks
Address
Phone Number

If we store this information only in variables:

name = "Raman"
marks = 92

the information exists only while the program is running.

When the program stops, the variables disappear.

But if we save the information in a file:

students.txt

we can retrieve it later.

🧠 Python Pebble

Variables remember data temporarily. Files allow us to store data for future use.


3. Opening a File

Python provides the open() function.

Basic syntax:

file = open("filename.txt", "mode")

For example:

file = open("students.txt", "r")

Here:

students.txt → file name
r             → read mode

4. File Modes

The mode tells Python what we want to do with the file.

ModeMeaning
rRead
wWrite
aAppend
xCreate a new file
r+Read and write
w+Write and read
a+Append and read

The most important modes for beginners are:

r → Read
w → Write
a → Append

5. Reading a File 📖

Suppose students.txt contains:

Raman
Aman
Priya

We can read it using:

file = open("students.txt", "r")

data = file.read()

print(data)

file.close()

Output:

Raman
Aman
Priya

6. Why Do We Need close()?

When Python opens a file, it uses a system resource.

After finishing our work, we should close it.

file.close()

So the traditional pattern is:

file = open("students.txt", "r")

data = file.read()

print(data)

file.close()

But there is an even better way.


7. The Better Way – with open() ⭐

Python provides a safer and cleaner approach:

with open("students.txt", "r") as file:
    data = file.read()
    print(data)

Python automatically closes the file after the with block.

This means we don't need:

file.close()

🧠 Python Pebble

Prefer with open() when working with files.

It makes programs:

  • Safer

  • Cleaner

  • Easier to understand


8. Reading Line by Line

Instead of reading the entire file at once, we can process each line.

with open("students.txt", "r") as file:

    for line in file:
        print(line)

If the file contains:

Raman
Aman
Priya

Python processes:

Raman
Aman
Priya

one line at a time.

This is particularly useful for large files.


9. readline()

We can read one line at a time using readline().

with open("students.txt", "r") as file:

    print(file.readline())
    print(file.readline())

If the file contains:

Raman
Aman
Priya

Output:

Raman

Aman

10. readlines()

readlines() reads all lines and returns them as a list.

with open("students.txt", "r") as file:

    lines = file.readlines()

print(lines)

Output:

['Raman\n', 'Aman\n', 'Priya\n']

Notice the \n.

It represents a new line.


11. Removing the New Line

We can use strip().

with open("students.txt", "r") as file:

    for line in file:
        print(line.strip())

Output:

Raman
Aman
Priya

12. Writing to a File ✍️

Now let's create a file.

with open("students.txt", "w") as file:

    file.write("Raman\n")
    file.write("Aman\n")
    file.write("Priya\n")

The file will contain:

Raman
Aman
Priya

13. Important: Write Mode Can Replace Existing Data ⚠️

Suppose the file already contains:

Raman
Aman
Priya

Now we run:

with open("students.txt", "w") as file:
    file.write("Rahul\n")

The previous contents are replaced.

The file now contains:

Rahul

🧠 Remember

w means write/overwrite.

Be careful!


14. Appending Data ➕

What if we want to add information without deleting existing data?

Use a.

with open("students.txt", "a") as file:
    file.write("Neha\n")

If the file originally contains:

Raman
Aman
Priya

after appending:

Raman
Aman
Priya
Neha

🧠 Python Pebble

w → Replace
a → Add to the end


15. Writing Multiple Lines

We can use writelines().

students = ["Raman\n", "Aman\n", "Priya\n"]

with open("students.txt", "w") as file:
    file.writelines(students)

The file becomes:

Raman
Aman
Priya

16. Text Files

A normal .txt file is a text file.

Example:

student.txt

It can contain:

Name: Raman
Class: 9
Marks: 92

Python can read this information as text.

with open("student.txt", "r") as file:
    data = file.read()

print(data)

17. Creating a Simple Notes Program 📝

Let's build something useful.

note = input("Enter your note: ")

with open("notes.txt", "a") as file:
    file.write(note + "\n")

print("Note saved successfully!")

Example:

Enter your note: Complete Python homework
Note saved successfully!

Every time the program runs, a new note is added.


18. Reading Our Notes

with open("notes.txt", "r") as file:
    notes = file.read()

print("My Notes")
print("--------")
print(notes)

We have now created a tiny digital notebook using Python!


19. Handling File Errors 🚨

What happens if we try to open a file that doesn't exist?

with open("unknown.txt", "r") as file:
    print(file.read())

Python may generate:

FileNotFoundError

Instead of allowing the program to crash, we can handle the error.


20. Using try-except

try:

    with open("unknown.txt", "r") as file:
        print(file.read())

except FileNotFoundError:

    print("File does not exist.")

Output:

File does not exist.

Now our program is much more user-friendly.


21. Other Common File Exceptions

Some useful exceptions include:

ExceptionMeaning
FileNotFoundErrorFile doesn't exist
PermissionErrorFile cannot be accessed
IsADirectoryErrorA directory was used where a file was expected
UnicodeDecodeErrorFile encoding could not be decoded

For beginners, the most important one is:

FileNotFoundError

22. Reading and Writing Structured Data

So far, we stored simple text.

But real applications often store structured information.

For example:

Roll No: 101
Name: Raman
Marks: 92

Or:

101,Raman,92
102,Aman,85
103,Priya,96

Or:

{
    "roll": 101,
    "name": "Raman",
    "marks": 92
}

Python supports several ways to work with structured data.

Two important formats are:

  • CSV

  • JSON


23. CSV Files 📊

CSV stands for:

Comma-Separated Values

A CSV file might look like this:

Roll,Name,Marks
101,Raman,92
102,Aman,85
103,Priya,96

CSV is commonly used for:

  • Student records

  • Employee data

  • Sales data

  • Marks

  • Expenses

  • Reports


24. Writing a CSV File

Python has a built-in csv module.

import csv

students = [
    [101, "Raman", 92],
    [102, "Aman", 85],
    [103, "Priya", 96]
]

with open("students.csv", "w", newline="") as file:

    writer = csv.writer(file)

    writer.writerow(["Roll", "Name", "Marks"])
    writer.writerows(students)

This creates:

Roll,Name,Marks
101,Raman,92
102,Aman,85
103,Priya,96

25. Reading a CSV File

import csv

with open("students.csv", "r") as file:

    reader = csv.reader(file)

    for row in reader:
        print(row)

Output:

['Roll', 'Name', 'Marks']
['101', 'Raman', '92']
['102', 'Aman', '85']
['103', 'Priya', '96']

Notice that values read from CSV are generally strings.

If we need marks as numbers:

marks = int(row[2])

26. CSV Using Dictionaries

A very useful approach is DictReader.

import csv

with open("students.csv", "r") as file:

    reader = csv.DictReader(file)

    for row in reader:
        print(row["Name"], row["Marks"])

Output:

Raman 92
Aman 85
Priya 96

This is easier to understand because we can use column names.


27. JSON Files 🤖

JSON stands for:

JavaScript Object Notation

Don't let the name worry you!

JSON is simply a popular format for storing structured data.

Example:

{
    "name": "Raman",
    "class": 9,
    "marks": 92
}

JSON is commonly used by:

  • Websites

  • Apps

  • APIs

  • Databases

  • AI applications

  • Data exchange systems


28. Writing JSON Using Python

Python provides the json module.

import json

student = {
    "roll": 101,
    "name": "Raman",
    "class": 9,
    "marks": 92
}

with open("student.json", "w") as file:
    json.dump(student, file, indent=4)

The file contains:

{
    "roll": 101,
    "name": "Raman",
    "class": 9,
    "marks": 92
}

29. Reading JSON

import json

with open("student.json", "r") as file:

    student = json.load(file)

print(student)

Output:

{'roll': 101, 'name': 'Raman', 'class': 9, 'marks': 92}

We can access individual values:

print(student["name"])
print(student["marks"])

Output:

Raman
92

30. JSON with Multiple Students

We can store a list of dictionaries.

import json

students = [
    {
        "roll": 101,
        "name": "Raman",
        "marks": 92
    },
    {
        "roll": 102,
        "name": "Aman",
        "marks": 85
    },
    {
        "roll": 103,
        "name": "Priya",
        "marks": 96
    }
]

with open("students.json", "w") as file:
    json.dump(students, file, indent=4)

Now we have a structured student database stored in a file!


31. Reading Structured JSON Data

import json

with open("students.json", "r") as file:
    students = json.load(file)

for student in students:
    print(
        student["roll"],
        student["name"],
        student["marks"]
    )

Output:

101 Raman 92
102 Aman 85
103 Priya 96

32. Updating JSON Data

Suppose Raman's marks change from 92 to 95.

We can:

  1. Read the file

  2. Modify the data

  3. Write it back

import json

with open("students.json", "r") as file:
    students = json.load(file)

for student in students:
    if student["roll"] == 101:
        student["marks"] = 95

with open("students.json", "w") as file:
    json.dump(students, file, indent=4)

This is the basic idea behind many real-world data-management programs.


33. Text vs CSV vs JSON

Which format should we use?

FormatBest For
TXTSimple text
CSVTables and spreadsheet-like data
JSONStructured/nested data

For example:

TXT

Raman
Aman
Priya

CSV

101,Raman,92
102,Aman,85

JSON

{
    "roll": 101,
    "name": "Raman",
    "marks": 92
}

34. File Handling + String Processing

Remember our previous Python Pebble about strings?

File handling and strings work very well together.

Suppose a file contains:

Python is easy
Python is powerful
Python is fun

We can count the number of times Python appears.

with open("message.txt", "r") as file:

    data = file.read()

count = data.lower().count("python")

print("Python appears", count, "times.")

Output:

Python appears 3 times.

Now we are combining:

Files + Strings + Conditions + Counting

That's how programming becomes powerful!


35. Mini Project – Student Record Management 🎓

Let's build something bigger.

Our application will store student information in a JSON file.

Each student will have:

Roll Number
Name
Class
Marks

We will create a menu:

===== STUDENT RECORD MANAGEMENT =====

1. Add Student
2. View Students
3. Search Student
4. Update Marks
5. Delete Student
6. Exit

36. Step 1 – Load Existing Records

import json

FILE_NAME = "students.json"

def load_students():

    try:
        with open(FILE_NAME, "r") as file:
            return json.load(file)

    except FileNotFoundError:
        return []

If the file doesn't exist, we return an empty list.


37. Step 2 – Save Records

def save_students(students):

    with open(FILE_NAME, "w") as file:
        json.dump(students, file, indent=4)

This function stores the current records.


38. Step 3 – Add a Student

def add_student(students):

    roll = input("Enter roll number: ")
    name = input("Enter student name: ")
    student_class = input("Enter class: ")
    marks = float(input("Enter marks: "))

    student = {
        "roll": roll,
        "name": name,
        "class": student_class,
        "marks": marks
    }

    students.append(student)

    save_students(students)

    print("Student added successfully!")

39. Step 4 – Display Students

def view_students(students):

    if not students:
        print("No student records found.")
        return

    for student in students:

        print(
            f"Roll: {student['roll']}, "
            f"Name: {student['name']}, "
            f"Class: {student['class']}, "
            f"Marks: {student['marks']}"
        )

40. Step 5 – Search Student

def search_student(students):

    roll = input("Enter roll number to search: ")

    for student in students:

        if student["roll"] == roll:

            print("\nStudent Found")
            print("Name:", student["name"])
            print("Class:", student["class"])
            print("Marks:", student["marks"])

            return

    print("Student not found.")

41. Step 6 – Update Marks

def update_marks(students):

    roll = input("Enter roll number: ")

    for student in students:

        if student["roll"] == roll:

            new_marks = float(
                input("Enter new marks: ")
            )

            student["marks"] = new_marks

            save_students(students)

            print("Marks updated successfully!")

            return

    print("Student not found.")

42. Step 7 – Delete a Student

def delete_student(students):

    roll = input("Enter roll number: ")

    for student in students:

        if student["roll"] == roll:

            students.remove(student)

            save_students(students)

            print("Student deleted successfully!")

            return

    print("Student not found.")

43. Step 8 – Create the Menu

Now let's bring everything together.

def main():

    students = load_students()

    while True:

        print("\n===== STUDENT RECORD MANAGEMENT =====")
        print("1. Add Student")
        print("2. View Students")
        print("3. Search Student")
        print("4. Update Marks")
        print("5. Delete Student")
        print("6. Exit")

        choice = input("Enter your choice: ")

        if choice == "1":
            add_student(students)

        elif choice == "2":
            view_students(students)

        elif choice == "3":
            search_student(students)

        elif choice == "4":
            update_marks(students)

        elif choice == "5":
            delete_student(students)

        elif choice == "6":
            print("Thank you!")
            break

        else:
            print("Invalid choice.")

Finally:

main()

44. Complete Student Record Program

import json

FILE_NAME = "students.json"


def load_students():

    try:
        with open(FILE_NAME, "r") as file:
            return json.load(file)

    except FileNotFoundError:
        return []


def save_students(students):

    with open(FILE_NAME, "w") as file:
        json.dump(students, file, indent=4)


def add_student(students):

    roll = input("Enter roll number: ")
    name = input("Enter student name: ")
    student_class = input("Enter class: ")
    marks = float(input("Enter marks: "))

    student = {
        "roll": roll,
        "name": name,
        "class": student_class,
        "marks": marks
    }

    students.append(student)

    save_students(students)

    print("Student added successfully!")


def view_students(students):

    if not students:
        print("No student records found.")
        return

    for student in students:

        print(
            f"Roll: {student['roll']}, "
            f"Name: {student['name']}, "
            f"Class: {student['class']}, "
            f"Marks: {student['marks']}"
        )


def search_student(students):

    roll = input("Enter roll number to search: ")

    for student in students:

        if student["roll"] == roll:

            print("\nStudent Found")
            print("Name:", student["name"])
            print("Class:", student["class"])
            print("Marks:", student["marks"])

            return

    print("Student not found.")


def update_marks(students):

    roll = input("Enter roll number: ")

    for student in students:

        if student["roll"] == roll:

            new_marks = float(input("Enter new marks: "))

            student["marks"] = new_marks

            save_students(students)

            print("Marks updated successfully!")

            return

    print("Student not found.")


def delete_student(students):

    roll = input("Enter roll number: ")

    for student in students:

        if student["roll"] == roll:

            students.remove(student)

            save_students(students)

            print("Student deleted successfully!")

            return

    print("Student not found.")


def main():

    students = load_students()

    while True:

        print("\n===== STUDENT RECORD MANAGEMENT =====")
        print("1. Add Student")
        print("2. View Students")
        print("3. Search Student")
        print("4. Update Marks")
        print("5. Delete Student")
        print("6. Exit")

        choice = input("Enter your choice: ")

        if choice == "1":
            add_student(students)

        elif choice == "2":
            view_students(students)

        elif choice == "3":
            search_student(students)

        elif choice == "4":
            update_marks(students)

        elif choice == "5":
            delete_student(students)

        elif choice == "6":
            print("Thank you!")
            break

        else:
            print("Invalid choice.")


main()

🧪 Sample Run

===== STUDENT RECORD MANAGEMENT =====

1. Add Student
2. View Students
3. Search Student
4. Update Marks
5. Delete Student
6. Exit

Enter your choice: 1

Enter roll number: 101
Enter student name: Raman
Enter class: 9
Enter marks: 92

Student added successfully!

Now the information is stored in:

students.json

Even if the program is closed, the record remains.

That is the real power of file handling!


🧠 Python Pebble Challenge 1 – Predict the Output

Suppose data.txt contains:

Python
Programming

What will this program display?

with open("data.txt", "r") as file:
    data = file.read()

print(len(data))

Don't run it immediately.

Count the characters yourself!


🧠 Python Pebble Challenge 2 – Find the Bug

What's wrong here?

file = open("students.txt", "r")

data = file.read()

print(data)

Hint

Think about resource management.

How could with open() improve this code?


🧠 Python Pebble Challenge 3 – Append Data

Write a program that:

  1. Asks the user for their name.

  2. Adds the name to names.txt.

  3. Does not delete previous names.


🧠 Python Pebble Challenge 4 – Count Words

Create a program that reads story.txt and displays:

Number of words: 125

Hint

Use:

split()

🧠 Python Pebble Challenge 5 – Find a Student

Create a program that reads students.json and searches for a student using their roll number.

Display:

Student Found
Name: Raman
Marks: 92

or:

Student not found.

🏆 Master Challenge – Improve the Student Management System

The basic project is only the beginning.

Try adding:

Level 1

  • Calculate average marks

  • Find highest marks

  • Find lowest marks

  • Count students

Level 2

  • Search by name

  • Search by class

  • Sort students by marks

  • Display students scoring above 90

Level 3

  • Calculate grades

  • Prevent duplicate roll numbers

  • Validate marks between 0 and 100

  • Handle invalid numeric input

  • Add date of birth

Level 4 🚀

Add:

  • Attendance

  • Subject-wise marks

  • Percentage

  • Grade

  • Rank

  • Export to CSV

  • Import from CSV

  • JSON backup

  • Student report generation

Now you've moved from a simple Python program to a small Student Management Application.


📌 File Handling Quick Revision

ConceptPython
Open fileopen()
Read entire fileread()
Read one linereadline()
Read all linesreadlines()
Writewrite()
Write multiple lineswritelines()
Automatically closewith open()
Read moder
Write modew
Append modea
Create new filex
CSVcsv module
JSONjson module
Handle missing fileFileNotFoundError

🎯 TXT vs CSV vs JSON – Remember This

Think of three different notebooks.

📒 TXT

Good for simple notes.

Python is fun.
Python is powerful.

📊 CSV

Good for tables.

Roll,Name,Marks
101,Raman,92
102,Aman,85

🗂️ JSON

Good for structured information.

{
    "roll": 101,
    "name": "Raman",
    "marks": 92
}

🪨 One Final Python Pebble

File handling connects many Python concepts together:

             FILE HANDLING
                  │
       ┌──────────┼──────────┐
       ↓          ↓          ↓
      TXT        CSV        JSON
       │          │          │
       └──────────┼──────────┘
                  ↓
             Python Data
                  ↓
        ┌─────────┼─────────┐
        ↓         ↓         ↓
      Read      Write     Update
        │         │         │
        └─────────┼─────────┘
                  ↓
             REAL PROJECTS
                  ↓
        Student Record System

The important thing to remember is:

A good program processes data. A useful program also knows how to save that data.

Once you understand file handling, your Python programs don't have to forget everything when they close.

You can now build programs that store, retrieve, search, update and manage real information.


🚀 Your Next Mission

Build these projects in order:

  1. 📝 Digital Notes App

  2. 📖 Simple Diary

  3. 📊 Marks Record using CSV

  4. 🗂️ Contact Book using JSON

  5. 🎓 Student Record Management System

And then challenge yourself:

Can you build a complete Student Management System that stores all its data in JSON and also generates a CSV report?

That's your next Python Pebble!

🐍 Strings in Python – From Simple Words to Smart Text Processing

 

Learn • Experiment • Solve • Build

“A string is more than a collection of characters—it is a message waiting to be explored!”


🌟 Welcome to the World of Strings!

Imagine you receive this message:

Hello Sukhbir! Welcome to Python.

Computers don't see this as a sentence. Python sees it as a string—a sequence of characters.

A string can contain:

  • Letters

  • Numbers

  • Spaces

  • Symbols

  • Special characters

For example:

name = "Raman"
city = "Noida"
message = "Python is Fun!"

All three variables contain strings.


1. Creating a String

Strings can be created using:

Single quotes

name = 'Raman'

Double quotes

name = "Raman"

Both are perfectly valid.

name1 = 'Python'
name2 = "Python"

print(name1)
print(name2)

Output

Python
Python

2. Strings Are a Sequence

Here's an important idea:

word = "PYTHON"

Python stores the characters in a sequence:

 P   Y   T   H   O   N
 ↓   ↓   ↓   ↓   ↓   ↓
 0   1   2   3   4   5

Each character has a position called an index.

Python starts counting from 0, not 1.


3. String Indexing 🔍

Indexing means accessing an individual character from a string.

word = "PYTHON"

print(word[0])
print(word[1])
print(word[5])

Output

P
Y
N

Remember:

P Y T H O N
0 1 2 3 4 5

🧠 Python Pebble

Index = Position of a character

The first character always has index 0.


4. Negative Indexing

Python also allows us to count from the end.

P   Y   T   H   O   N
-6 -5 -4 -3 -2 -1

Example:

word = "PYTHON"

print(word[-1])
print(word[-2])

Output

N
O

So:

word[-1]

means:

Give me the last character.


5. String Slicing ✂️

What if we want more than one character?

That's where slicing comes in.

Syntax:

string[start:end]

The start position is included, but the end position is excluded.

word = "PYTHON"

print(word[0:3])

Output

PYT

Why?

P Y T H O N
0 1 2 3 4 5
|---|
0 1 2

The character at index 3 is not included.


More Slicing Examples

word = "PYTHON"

print(word[1:4])
print(word[2:6])
print(word[:3])
print(word[3:])

Output

YTH
THON
PYT
HON

6. Slicing with a Step

We can also specify a step.

word = "PYTHON"

print(word[0:6:2])

Output

PTO

It selects:

P → T → O

Syntax:

string[start:end:step]

7. Reverse a String 🔄

Here's one of Python's most useful string tricks:

word = "PYTHON"

print(word[::-1])

Output

NOHTYP

The -1 step means:

Move backwards one character at a time.


8. Finding the Length – len()

How many characters are present in a string?

Use len().

name = "Raman"

print(len(name))

Output

5

Spaces are also counted.

message = "Hello World"

print(len(message))

Output

11

Why 11?

Hello = 5
Space = 1
World = 5

Total = 11

9. Changing Case

Python provides useful methods for changing the case of characters.

upper()

name = "python"

print(name.upper())

Output:

PYTHON

lower()

name = "PYTHON"

print(name.lower())

Output:

python

Real-Life Example

Suppose a student enters:

raman

We can convert it to:

name = "raman"

print(name.upper())

Output:

RAMAN

10. Removing Extra Spaces – strip()

Sometimes users accidentally enter spaces.

name = "   Raman   "

print(name.strip())

Output:

Raman

strip() removes spaces from the beginning and end.

Important

It does not remove spaces between words.

message = "Hello World"

print(message.strip())

Output:

Hello World

11. Replacing Text – replace()

Suppose we want to replace one word with another.

message = "I like Java"

message = message.replace("Java", "Python")

print(message)

Output:

I like Python

Another Example

text = "cat cat cat"

print(text.replace("cat", "dog"))

Output:

dog dog dog

12. Splitting a String – split()

Suppose we have:

data = "Python is easy"

We can split it into individual words.

words = data.split()

print(words)

Output:

['Python', 'is', 'easy']

The result is a list.


Splitting Using a Separator

data = "apple,banana,mango"

fruits = data.split(",")

print(fruits)

Output:

['apple', 'banana', 'mango']

🧠 Remember

split():

String → List


13. Joining Strings – join()

Now let's go in the opposite direction.

Suppose:

words = ["Python", "is", "fun"]

We want:

Python is fun

Use join().

words = ["Python", "is", "fun"]

sentence = " ".join(words)

print(sentence)

Output:

Python is fun

Another Example

words = ["2026", "10", "05"]

date = "-".join(words)

print(date)

Output:

2026-10-05

🧠 Python Pebble

split() breaks a string apart.
join() puts strings together.


14. Searching Inside a String – find()

Want to know where a word occurs?

Use find().

message = "Python is powerful"

print(message.find("powerful"))

Output:

10

Why?

Python is powerful
0123456789...

If the text is not found:

message = "Python is powerful"

print(message.find("Java"))

Output:

-1

So -1 means:

The searched text was not found.


15. Counting Characters – count()

How many times does a character occur?

word = "banana"

print(word.count("a"))

Output:

3

We can also count words or groups of characters.

message = "Python is easy. Python is powerful."

print(message.count("Python"))

Output:

2

16. Checking the Beginning – startswith()

We can check whether a string starts with particular text.

website = "pythonpebbles"

print(website.startswith("python"))

Output:

True

Another example:

name = "Raman"

print(name.startswith("Ram"))
print(name.startswith("Raj"))

Output:

True
False

17. Checking the Ending – endswith()

Similarly, we can check how a string ends.

filename = "student.py"

print(filename.endswith(".py"))

Output:

True

This can be useful when checking file types.

filename = "photo.jpg"

print(filename.endswith(".py"))

Output:

False

18. f-Strings – The Smart Way to Create Messages 🚀

Suppose we have:

name = "Raman"
marks = 92

We want:

Raman scored 92 marks.

We can use an f-string.

name = "Raman"
marks = 92

print(f"{name} scored {marks} marks.")

Output:

Raman scored 92 marks.

The f tells Python:

“I want to insert variables inside this string.”


Multiple Variables

name = "Raman"
age = 14
city = "Noida"

print(f"{name} is {age} years old and lives in {city}.")

Output:

Raman is 14 years old and lives in Noida.

19. Calculations Inside f-Strings

We can even perform calculations.

price = 500
quantity = 3

print(f"Total amount = ₹{price * quantity}")

Output:

Total amount = ₹1500

That's powerful!


20. Formatting Numbers

Suppose:

price = 1234.5678

We want only two decimal places.

print(f"{price:.2f}")

Output:

1234.57

Percentage Example

score = 92.4567

print(f"Score: {score:.2f}%")

Output:

Score: 92.46%

21. Traditional String Formatting

Python also supports other formatting techniques.

.format()

name = "Raman"
marks = 95

print("{} scored {} marks.".format(name, marks))

Output:

Raman scored 95 marks.

We can also use positions:

print("{0} scored {1} marks.".format(name, marks))

For modern Python programs, f-strings are generally easier to read.


22. Escape Characters 🔐

What happens if we want to print:

He said, "Python is fun!"

We can use escape characters.

print("He said, \"Python is fun!\"")

Output:

He said, "Python is fun!"

The backslash \ tells Python that the following character has a special meaning.


Common Escape Characters

EscapeMeaning
\nNew line
\tTab
\\Backslash
\'Single quote
\"Double quote

New Line

print("Hello\nPython")

Output:

Hello
Python

Tab

print("Name\tMarks")
print("Raman\t95")

Output:

Name    Marks
Raman   95

23. Multi-Line Strings

Triple quotes can be used for multiple lines.

message = """Welcome to Python Pebbles!

Learn Python.
Practice Python.
Build Python projects.
"""

print(message)

Output:

Welcome to Python Pebbles!

Learn Python.
Practice Python.
Build Python projects.

24. Strings Are Immutable 🔒

Here's a very important Python concept.

You cannot directly change an individual character of a string.

This will produce an error:

word = "Python"

word[0] = "J"

Strings are immutable.

Instead, create a new string.

word = "Python"

word = "J" + word[1:]

print(word)

Output:

Jython

🧠 Python Pebble

Immutable means the original string cannot be changed character-by-character.


25. The Palindrome Challenge 🔄

A palindrome reads the same forward and backward.

Examples:

MADAM
LEVEL
RADAR
121

Let's check one.

word = "madam"

if word == word[::-1]:
    print("Palindrome")
else:
    print("Not a palindrome")

Output:

Palindrome

🎯 User Input Palindrome

word = input("Enter a word: ")

if word == word[::-1]:
    print("Palindrome")
else:
    print("Not a palindrome")

Try:

Enter a word: level
Palindrome

26. Palindrome – Advanced Version

What if the user enters:

Madam

The comparison becomes:

Madam
madam

We can normalize the input.

word = input("Enter a word: ")

word = word.lower()

if word == word[::-1]:
    print("Palindrome")
else:
    print("Not a palindrome")

27. Anagram Challenge 🔀

Two words are anagrams if they contain the same letters in a different order.

Examples:

listen
silent

Both contain:

l, i, s, t, e, n

We can solve this using sorted().

word1 = "listen"
word2 = "silent"

if sorted(word1) == sorted(word2):
    print("Anagram")
else:
    print("Not an Anagram")

Output:

Anagram

Why Does It Work?

sorted("listen")

produces characters in sorted order:

['e', 'i', 'l', 'n', 's', 't']

And:

sorted("silent")

produces the same result.

Therefore, they are anagrams.


28. Making Anagram Checking User-Friendly

Users may enter uppercase and lowercase letters.

word1 = input("Enter first word: ")
word2 = input("Enter second word: ")

word1 = word1.lower()
word2 = word2.lower()

if sorted(word1) == sorted(word2):
    print("Anagram")
else:
    print("Not an Anagram")

29. Frequency Counting 📊

Suppose we have:

word = "banana"

We want to know:

b → 1
a → 3
n → 2

One simple method is using count().

word = "banana"

for ch in "ban":
    print(ch, word.count(ch))

Output:

b 1
a 3
n 2

But what if we don't know which characters exist?

That's where a dictionary becomes extremely useful.


30. Character Frequency Using a Dictionary

word = "banana"

frequency = {}

for ch in word:
    if ch in frequency:
        frequency[ch] += 1
    else:
        frequency[ch] = 1

print(frequency)

Output:

{'b': 1, 'a': 3, 'n': 2}

How does it work?

First:

b → 1

Then:

a → 1

Then:

n → 1

When a appears again:

a → 2

And again:

a → 3

31. Frequency Counting – Using get()

We can make the program shorter.

word = "banana"

frequency = {}

for ch in word:
    frequency[ch] = frequency.get(ch, 0) + 1

print(frequency)

Output:

{'b': 1, 'a': 3, 'n': 2}

This is an important programming pattern.

Count = previous count + 1


32. Word Frequency

Frequency counting isn't limited to characters.

Consider:

sentence = "python is easy and python is powerful"

We can count words.

words = sentence.split()

frequency = {}

for word in words:
    frequency[word] = frequency.get(word, 0) + 1

print(frequency)

Output:

{'python': 2, 'is': 2, 'easy': 1, 'and': 1, 'powerful': 1}

Now our program is becoming a small text-analysis tool!


33. A Mini Text Analyzer 🚀

Let's combine several string concepts.

text = input("Enter a sentence: ")

print("\n--- Text Analysis ---")

print("Characters:", len(text))
print("Uppercase:", text.upper())
print("Lowercase:", text.lower())

words = text.split()

print("Number of words:", len(words))

Example:

Enter a sentence: Python is easy to learn

Output:

--- Text Analysis ---
Characters: 24
Uppercase: PYTHON IS EASY TO LEARN
Lowercase: python is easy to learn
Number of words: 5

34. Mini Project – Student Name Formatter 🎓

Suppose a student enters:

   rAMAN sINGH

We want:

Raman Singh

One approach:

name = input("Enter your name: ")

name = name.strip()
name = name.lower()
name = name.title()

print(f"Welcome, {name}!")

Output:

Enter your name:    rAMAN sINGH
Welcome, Raman Singh!

Here we combined:

  • input()

  • strip()

  • lower()

  • title()

  • f-strings


35. Mini Project – Username Validator 🔐

Let's check whether a username:

  • starts with "ram"

  • ends with a number

  • has at least 5 characters

username = input("Enter username: ")

if len(username) >= 5 and username.startswith("ram"):
    print("Username format looks good.")
else:
    print("Invalid username.")

This introduces an important idea:

String methods can be combined with conditions to solve real-world problems.


36. Mini Project – Word Search 🔎

sentence = input("Enter a sentence: ")
word = input("Enter word to search: ")

position = sentence.lower().find(word.lower())

if position != -1:
    print(f"Word found at position {position}")
else:
    print("Word not found.")

Example:

Enter a sentence: Python is easy to learn
Enter word to search: easy

Output:

Word found at position 10

🧠 Python Pebble Challenge 1 – Predict the Output

What will this program print?

word = "PYTHON"

print(word[1:5])
print(word[-3:])
print(word[::-1])

Think before running the program!


🧠 Python Pebble Challenge 2 – Find the Bug

What is wrong with this program?

name = "Python"

name[0] = "J"

print(name)

Hint

Think about immutability.


🧠 Python Pebble Challenge 3 – Palindrome

Write a program that accepts a word and determines whether it is a palindrome.

Example:

Enter word: radar
Palindrome

🧠 Python Pebble Challenge 4 – Anagram

Write a program that accepts two words and checks whether they are anagrams.

Example:

First word: triangle
Second word: integral

Anagram

🧠 Python Pebble Challenge 5 – Character Counter

Write a program that accepts a string and displays the frequency of every character.

Example:

Enter text: hello

Expected result:

h : 1
e : 1
l : 2
o : 1

🏆 Python Pebbles – Master Challenge

Create a Text Analyzer that accepts a sentence and displays:

  1. Number of characters

  2. Number of words

  3. Uppercase version

  4. Lowercase version

  5. First character

  6. Last character

  7. Number of occurrences of "Python"

  8. Whether the sentence starts with "Python"

  9. Whether it ends with "."

  10. Frequency of every character

Sample Input

Python is easy. Python is powerful.

Your program should produce a report similar to:

------ TEXT ANALYZER ------

Characters : 35
Words      : 6

Uppercase:
PYTHON IS EASY. PYTHON IS POWERFUL.

Lowercase:
python is easy. python is powerful.

First Character : P
Last Character  : .

Python Count   : 2
Starts with Python : True
Ends with .       : True

Character Frequency:
P : 2
y : 2
t : 2
h : 2
o : ...

📌 Quick Revision – String Toolkit

Function / MethodPurpose
len()Finds string length
upper()Converts to uppercase
lower()Converts to lowercase
strip()Removes leading/trailing whitespace
replace()Replaces text
split()Converts string into a list
join()Joins strings
find()Finds position of text
count()Counts occurrences
startswith()Checks beginning
endswith()Checks ending
[::-1]Reverses a string
f""Creates formatted strings
format()Formats strings
\nNew line
\tTab

🚀 What Have We Learned?

We started with:

"Hello"

But now we can:

🔍 Explore characters
✂️ Slice strings
🔄 Reverse strings
🔎 Search text
📊 Count characters
🧹 Clean user input
🔀 Split and join data
🎨 Format output
🔐 Work with escape characters
🧠 Detect palindromes
🔀 Detect anagrams
📊 Calculate frequencies
🚀 Build text-analysis programs

That's the real power of Python strings.


🪨 One Final Python Pebble

Remember these five ideas:

1️⃣ Indexing

word[0]

Get one character.

2️⃣ Slicing

word[1:4]

Get part of a string.

3️⃣ Methods

word.upper()

Process the string.

4️⃣ Formatting

f"Hello {name}"

Build useful messages.

5️⃣ Problem Solving

word == word[::-1]

Use strings to solve real problems.

Don't just memorize string methods. Experiment with them, combine them, and use them to build something!


🎯 Practice Mission

Before moving to the next Python Pebble, try building these five programs:

  1. Name Formatter

  2. Palindrome Checker

  3. Anagram Checker

  4. Character Frequency Counter

  5. Complete Text Analyzer

Once you can build these without looking at the solution, you've moved from learning strings to thinking like a Python programmer.

🐍 Python Function Arguments – How to Give Information to a Function

 

Have you ever asked someone to calculate the area of a rectangle?

You might say:

“Calculate the area of a rectangle with length 10 cm and width 5 cm.”

The person needs the length and width to do the calculation.

Python functions work in a similar way.

A function can receive information from the program that calls it. This information is called an argument.

In this lesson, we will learn:

  • What are function arguments?

  • Parameters vs arguments

  • Positional arguments

  • Keyword arguments

  • Default arguments

  • Multiple arguments

  • Returning results

  • Common mistakes

  • Practice challenges


🎯 What You'll Learn

By the end of this lesson, you will be able to:

  • Pass information to a Python function

  • Understand parameters and arguments

  • Use positional arguments

  • Use keyword arguments

  • Use default arguments

  • Create functions with multiple arguments

  • Write useful real-world functions

🟢 Level: Beginner
🎓 Suitable for: Classes 7–10
⏱️ Learning time: 25–30 minutes


1. What is a Function?

A function is a reusable block of code designed to perform a particular task.

For example:

def greet():
    print("Hello, Student!")

greet()

Output

Hello, Student!

Here:

def greet():

creates a function called greet.

And:

greet()

calls the function.

But what if we want the function to greet different students?

We need to give information to the function.

That's where arguments come in.


2. What is a Function Argument?

An argument is a value that we pass to a function when we call it.

Look at this example:

def greet(name):
    print("Hello", name)

greet("Raman")

Output

Hello Raman

Here:

name

is called a parameter.

And:

"Raman"

is called an argument.

Remember

Parameter = variable written in the function definition

Argument = actual value supplied when calling the function

Think of it like this:

Function Definition              Function Call

def greet(name):                 greet("Raman")
        ↑                              ↑
    Parameter                      Argument

3. Why Do We Need Arguments?

Without arguments, we would need to create separate functions for different values.

For example:

def square_of_5():
    print(5 * 5)

def square_of_10():
    print(10 * 10)

This is unnecessary.

Instead, we can create one reusable function:

def square(number):
    print(number * number)

square(5)
square(10)
square(20)

Output

25
100
400

One function can now work with many different values.

That's the real power of function arguments.


4. Positional Arguments

The simplest type of argument is a positional argument.

The values are matched with parameters according to their position.

Example:

def student_info(name, age):
    print("Name:", name)
    print("Age:", age)

student_info("Raman", 14)

Output

Name: Raman
Age: 14

Here:

name → "Raman"
age  → 14

The first argument goes to the first parameter, and the second argument goes to the second parameter.


5. Order Matters

Consider:

def introduce(name, city):
    print(name, "lives in", city)

introduce("Raman", "Noida")

Output:

Raman lives in Noida

Now change the order:

introduce("Noida", "Raman")

Output:

Noida lives in Raman

Python doesn't know that we accidentally changed the order.

It simply follows the position.

Therefore:

With positional arguments, order is important.


6. Multiple Arguments

A function can accept several arguments.

For example, let's calculate the total marks of three subjects.

def total_marks(math, science, english):
    total = math + science + english
    print("Total Marks:", total)

total_marks(85, 90, 88)

Output

Total Marks: 263

Here the function receives three arguments:

math     → 85
science  → 90
english  → 88

We can call the same function again:

total_marks(75, 82, 91)

Output:

Total Marks: 248

7. Keyword Arguments

Python also allows us to specify the parameter name while passing an argument.

These are called keyword arguments.

Example:

def student_info(name, age, city):
    print("Name:", name)
    print("Age:", age)
    print("City:", city)

student_info(
    name="Raman",
    age=14,
    city="Noida"
)

Output

Name: Raman
Age: 14
City: Noida

The advantage is that the meaning of each value is clear.


8. Keyword Arguments Don't Have to Follow the Same Order

With keyword arguments, we can change the order.

def student_info(name, age, city):
    print(name, age, city)

student_info(city="Noida", name="Raman", age=14)

Output

Raman 14 Noida

Python matches the values using the parameter names.

So:

city="Noida"
name="Raman"
age=14

is perfectly valid.


9. Positional vs Keyword Arguments

Let's compare them.

Positional

student_info("Raman", 14, "Noida")

The order matters.

Keyword

student_info(
    name="Raman",
    age=14,
    city="Noida"
)

The parameter names are specified, so the order can be changed.

Quick Comparison

TypeExampleOrder Important?
Positionalfun(10, 20)Yes
Keywordfun(a=10, b=20)No

10. Default Arguments

Sometimes we want a function to have a default value.

For example:

def greet(name="Student"):
    print("Hello", name)

greet()
greet("Raman")

Output

Hello Student
Hello Raman

When we don't provide an argument, Python uses the default value.

When we provide an argument, Python uses the supplied value.


11. Real-Life Example – Greeting Students

Suppose we create a function for greeting students.

def greet(name, message="Welcome to Python!"):
    print("Hello", name)
    print(message)

greet("Raman")

Output

Hello Raman
Welcome to Python!

We can also provide our own message:

greet("Raman", "Good morning!")

Output:

Hello Raman
Good morning!

The default value is used only when we don't provide the second argument.


12. Function Arguments Can Be Different Data Types

Arguments don't always have to be numbers.

They can be:

  • Strings

  • Integers

  • Floats

  • Lists

  • Tuples

  • Dictionaries

  • Boolean values

  • Objects

Example:

def show_student(name, marks):
    print("Student:", name)
    print("Marks:", marks)

show_student("Raman", [85, 90, 88])

Output

Student: Raman
Marks: [85, 90, 88]

13. Returning a Result

A function can receive arguments and return a result.

For example:

def add(a, b):
    return a + b

result = add(10, 20)

print("Result:", result)

Output

Result: 30

Here:

add(10, 20)

passes 10 and 20 to the function.

The function calculates:

10 + 20

and returns:

30

14. A Useful School Example – Calculate Percentage

Let's create a function to calculate a student's percentage.

def percentage(math, science, english):
    total = math + science + english
    percent = total / 300 * 100
    return percent

result = percentage(85, 90, 80)

print("Percentage:", result)

Output

Percentage: 85.0

This function can be reused for every student.

print(percentage(85, 90, 80))
print(percentage(70, 75, 80))
print(percentage(95, 92, 96))

Output

85.0
75.0
94.33333333333333

One function can solve the problem for many students.


15. Mixing Positional and Keyword Arguments

We can also combine positional and keyword arguments.

Example:

def student(name, age, city):
    print(name, age, city)

student("Raman", age=14, city="Noida")

This is valid.

However, there is an important rule:

Positional arguments must come before keyword arguments.

Correct:

student("Raman", age=14, city="Noida")

Incorrect:

student(name="Raman", 14, city="Noida")

The second example causes a syntax error.


16. What Happens If We Give the Wrong Number of Arguments?

Suppose we have:

def add(a, b):
    return a + b

Now we call:

add(10)

Python will report an error because the function requires two arguments.

Similarly:

add(10, 20, 30)

also causes an error because we provided three arguments.

Remember

If a function requires:

def add(a, b):

we normally need to provide exactly two arguments unless default values or special argument mechanisms are being used.


🧠 Think About It

What will this program print?

def multiply(a, b):
    return a * b

x = multiply(5, 4)

print(x)

A. 9
B. 20
C. 54
D. Error

Answer: B — 20

Because:

5 × 4 = 20

🐞 Debug This Code

Can you find the problem?

def greet(name, age):
    print("Hello", name)
    print("Age:", age)

greet("Raman")

What's wrong?

The function requires two arguments:

name
age

But only one argument was provided.

Correct code:

greet("Raman", 14)

🎯 Mini Project – Student Information

Let's combine everything we have learned.

def student_info(name, age, grade, city="Noida"):
    print("----- Student Information -----")
    print("Name:", name)
    print("Age:", age)
    print("Grade:", grade)
    print("City:", city)

student_info("Raman", 14, 9)

Output

----- Student Information -----
Name: Raman
Age: 14
Grade: 9
City: Noida

Notice that we didn't provide the city.

Python automatically used:

city="Noida"

because it was the default argument.


⭐ Challenge 1 – Easy

Create a function:

square(number)

that returns the square of a number.

Expected:

print(square(7))

Output:

49

⭐ Challenge 2 – Medium

Create a function:

average(a, b, c)

that returns the average of three numbers.

Example:

print(average(80, 90, 70))

Expected output:

80.0

⭐ Challenge 3 – School Project

Create a function:

student_result(name, math, science, english)

The function should:

  1. Calculate total marks.

  2. Calculate percentage.

  3. Display the student's name.

  4. Display total marks.

  5. Display percentage.

Example:

student_result("Raman", 85, 90, 88)

🧠 Python Pebble Challenge

Can you predict the output?

def calculate(a, b=10):
    return a + b

print(calculate(5))
print(calculate(5, 20))

Think before looking at the answer.

Answer

15
25

Why?

First call:

calculate(5)

uses the default value:

5 + 10 = 15

Second call:

calculate(5, 20)

replaces the default value:

5 + 20 = 25

📌 Quick Revision

ConceptExample
Parameterdef add(a, b):
Argumentadd(10, 20)
Positional argumentadd(10, 20)
Keyword argumentadd(a=10, b=20)
Default argumentdef greet(name="Student")
Multiple argumentsadd(a, b, c)
Return valuereturn a + b

🌟 Key Takeaways

Remember these five points:

  1. Parameters are variables defined inside the function definition.

  2. Arguments are actual values passed to the function.

  3. Positional arguments depend on order.

  4. Keyword arguments use parameter names.

  5. Default arguments provide a value when the caller doesn't supply one.

The biggest advantage of arguments is reusability.

Instead of writing:

square_of_5()
square_of_10()
square_of_20()

we can write one function:

def square(number):
    return number * number

and use it for any number:

square(5)
square(10)
square(20)

That's the power of functions in Python! 🐍


🚀 What's Next?

Now that you understand function arguments, the next topics to explore are:

Function Return Values → Local & Global Variables → Variable-Length Arguments (*args) → Keyword Variable-Length Arguments (**kwargs) → Lambda Functions

Keep coding, keep experimenting, and remember:

Small code. Big ideas. One Python Pebble at a time! 🪨🐍

Python Modules and Packages

  Python Modules and Packages – Organize Your Python Programs Like a Pro When Python programs become bigger, putting everything into one fil...