Back to Study Material School Learning

Python Class 11

As programs grow longer and more complex, organising code into reusable units becomes essential. A function is a named block of code that performs a specif...

Python Class 11

Python Functions: Defining Reusable Blocks of Code

As programs grow longer and more complex, organising code into reusable units becomes essential. A function is a named block of code that performs a specific task and can be called (executed) from anywhere in the program, as many times as needed, without rewriting the code. Functions are one of the most powerful tools in any programming language, and Python's function syntax is clean and straightforward.

You define a function in Python using the def keyword, followed by the function name, parentheses (which may contain parameter names), and a colon. The body of the function is indented:

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

To call this function: greet("Amit") prints Hello, Amit! The value "Amit" passed into the function is called an argument; the variable name that receives it inside the function is the parameter.

Functions can return values using the return statement:

def square(n): return n * n

result = square(7) print(result) # Output: 49

The return statement ends the function and sends the computed value back to the caller. A function without a return statement returns None implicitly.

Functions can have default parameter values, which are used when the caller does not provide that argument:

def power(base, exponent=2): return base ** exponent

power(3) returns 9 (3 squared, using the default exponent 2). power(3, 3) returns 27 (3 cubed, overriding the default).

Variable scope is crucial to understand. Variables created inside a function (local variables) exist only within that function; they are destroyed when the function ends. Variables created outside all functions (global variables) are accessible throughout the program. To modify a global variable inside a function, use the global keyword, though this practice should be used sparingly.

Exam tip: CBSE Class 11 Python questions frequently test whether you understand the difference between a parameter (in the function definition) and an argument (in the function call), and whether you can trace the execution of a function and predict its return value.

Lists, Tuples, and Dictionaries: Python's Core Data Structures

Real programs rarely work with just one value at a time. Python provides several built-in data structures for working with collections of data. The three most important for Class 11 are lists, tuples, and dictionaries.

A list is an ordered, mutable (changeable) collection of items. Items can be of any data type and can be mixed. Lists are created with square brackets: marks = [85, 92, 78, 95, 88]. You access items by index (zero-based): marks[0] is 85, marks[-1] is 88 (the last item). Lists support slicing: marks[1:3] returns [92, 78] (items at indices 1 and 2). Common list methods include append() (add an item to the end), insert() (add at a specific position), remove() (remove by value), pop() (remove by index and return the value), sort() (sort in place), and len() (not a method but a function — returns the number of items).

A tuple is an ordered, immutable (unchangeable) collection. Once created, you cannot add, remove, or change items. Tuples use parentheses: coordinates = (10, 20). Because tuples cannot be changed accidentally, they are used for data that should remain constant — like the days of the week or coordinate pairs. Tuples are slightly faster than lists due to their immutability.

A dictionary stores data as key-value pairs. Dictionaries are unordered (in Python 3.6 and earlier) but maintain insertion order in Python 3.7 and later. Each key must be unique and immutable. Values can be anything: student = {"name": "Priya", "class": 11, "marks": 93} Access a value by its key: student["name"] returns "Priya". Add or update: student["city"] = "Delhi". Delete: del student["marks"]. Methods: keys() (all keys), values() (all values), items() (all key-value pairs as tuples).

Iteration with for loops works naturally over all three structures: for mark in marks: — iterates over each value in the list. for key, value in student.items(): — iterates over key-value pairs in the dictionary.

Exam tip: know when to use each structure. Use a list when order matters and data changes. Use a tuple for fixed data or as a dictionary key. Use a dictionary for labelled data (where each item has a meaningful name). CBSE asks you to trace dictionary operations and predict output very frequently.

File Handling in Python: Reading and Writing Data Persistently

All the programs you have written so far lose their data when they stop running — variables exist only in RAM. File handling allows Python programs to store data permanently on disk and read it back in future runs. This is how almost all practical applications — note-taking apps, grade tracking systems, log files — retain information.

To work with a file in Python, you first open it using the built-in open() function. This function takes the filename and a mode: "r" for reading (file must exist), "w" for writing (creates the file or overwrites existing content), "a" for appending (adds to the end without erasing existing content), and "r+" or "w+" for reading and writing simultaneously.

The modern, recommended approach uses a with statement, which automatically closes the file when the block ends, even if an error occurs:

with open("students.txt", "w") as f: f.write("Priya,11,93\n") f.write("Arjun,11,88\n")

The \n character inserts a newline. The write() method writes a string; it does not automatically add newlines.

Reading a file:

with open("students.txt", "r") as f: content = f.read() print(content)

The read() method reads the entire file as one string. readline() reads one line at a time. readlines() reads all lines and returns them as a list of strings, with \n included in each item.

A common pattern for processing a file line by line:

with open("students.txt", "r") as f: for line in f: line = line.strip() # removes leading/trailing whitespace including \n parts = line.split(",") name, cls, marks = parts[0], parts[1], parts[2] print(f"{name} in Class {cls} scored {marks}")

This parses each CSV-style line into its components.

Real-world use: a school's daily attendance logger could open "attendance.txt" in append mode each day, write the date and absent students, and build up a complete year's record in one growing file.

Exam tip: CBSE Class 11 and 12 file handling questions commonly ask you to write a program to count the number of lines, words, or specific characters in a file, or to search for a keyword and display matching lines. Practise these patterns until they are fluent.