0% found this document useful (0 votes)
5 views

python basics cs 12 pdf

The document provides a comprehensive overview of Python programming, covering topics such as variables, data types, operators, conditional statements, loops, functions, file handling, and exception handling. It includes examples of built-in and user-defined functions, as well as practical applications for reading and writing files in different formats. Key takeaways emphasize understanding Python syntax, mastering functions, and practicing file operations for effective programming.

Uploaded by

anuchaitanya2017
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

python basics cs 12 pdf

The document provides a comprehensive overview of Python programming, covering topics such as variables, data types, operators, conditional statements, loops, functions, file handling, and exception handling. It includes examples of built-in and user-defined functions, as well as practical applications for reading and writing files in different formats. Key takeaways emphasize understanding Python syntax, mastering functions, and practicing file operations for effective programming.

Uploaded by

anuchaitanya2017
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

1.

Python Basics
Python is a high-level, interpreted programming language used for various applications such as
web development, data science, and automation.

A. Variables & Data Types

• Variables store data in memory.


• No need to declare data types explicitly.
Common Data Types:

Data Type Example


int (Integer) x = 10
float (Decimal) y = 3.14
str (String) name = "Alice"
bool (Boolean) is_valid = True
list (Ordered
nums = [1, 2, 3]
collection)
tuple (Immutable list) coords = (4, 5)
student = {"name": "Alice", "age":
dict (Key-value pairs)
18}
set (Unique values) unique_nums = {1, 2, 3}

Example:

python

a = 5 # Integer
b = 2.5 # Float
c = "Hello" # String
d = True # Boolean
print(type(a), type(b), type(c), type(d))

B. Operators in Python

Python provides various operators for calculations and logical operations.

1. Arithmetic Operators

• + (Addition), - (Subtraction), * (Multiplication), / (Division)


• // (Floor division), % (Modulus), ** (Exponentiation)
2. Comparison Operators

• ==, !=, >, <, >=, <= (Used for comparisons)

1 of 31
3. Logical Operators

• and, or, not


Example:

python

x = 10
y = 5
print(x + y) # Output: 15
print(x > y and y < 10) # Output: True

C. Conditional Statements

Used to make decisions in a program.

Syntax:

python

if condition:
# Code runs if condition is True
elif another_condition:
# Runs if previous condition is False but this one is
True
else:
# Runs if all conditions are False
Example:

python

marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
else:
print("Grade: C")

D. Loops

Loops allow repeated execution of a block of code.

1. for Loop

Iterates over sequences like lists, tuples, or strings.

2 of 31
python

for i in range(1, 6):


print(i) # Output: 1 2 3 4 5

2. while Loop

Executes while a condition remains True.

python

count = 1
while count <= 5:
print(count)
count += 1

2. Python Functions
Functions allow code reuse and modular programming.

A. Built-in Functions

Python provides many built-in functions:

• print(), len(), type(), max(), min(), round(), sorted()

Example: math.sqrt() from the math module, random.randint() from the


random module.

Example:
python
print(len("Hello")) # Output: 5
print(max([3, 7, 2, 9])) # Output: 9

B. User-de ned Functions

Custom functions are created using def.

python

def greet(name):
return "Hello, " + name

print(greet("Alice"))

3 of 31
fi
C. Function with Default Arguments

Python
def add(a, b=5):
return a + b

print(add(10)) # Output: 15

D. Lambda (Anonymous) Functions

One-liner functions using lambda.

python

square = lambda x: x ** 2
print(square(5)) # Output: 25

3. File Handling in Python


Python allows reading/writing les using the open() function.

A. File Modes

Mod
Description
e
r Read mode (default)
w Write mode (overwrites le)
Append mode (adds
a content)
r+ Read & Write mode

B. Reading a File

python

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


content = file.read()
print(content)
file.close()

C. Writing to a File
4 of 31
fi
fi
python
file = open("example.txt", "w")
file.write("Hello, CBSE Students!")
file.close()

D. Appending to a File

python

file = open("example.txt", "a")


file.write("\nKeep learning Python!")
file.close()

E. Using with Statement (Best Practice)

python

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


content = file.read()
print(content)

4. Key Takeaways for CBSE Exams


✔ Understand Python syntax, data types, operators
✔ Learn conditional statements (if-else) and loops (for, while)
✔ Master functions (built-in, user-de ned, lambda)
✔ Learn how to read, write, and append les
✔ Practice previous year questions

5 of 31
fi
fi
2. 🔥 1. Functions
A. Types of Functions

1. Built-in Functions: Pre-de ned functions in Python.


◦ Examples: print(), len(), sum(), type(), input(), max(), min()

Python comes with many built-in functions, such as:

• len() → Returns the length of a string, list, or tuple.


• max() → Returns the largest item in an iterable.
• min() → Returns the smallest item in an iterable.
• abs() → Returns the absolute value of a number.
• round() → Rounds a oating-point number to the nearest integer.
✅ Example:

python
# Using built-in functions
print(len("Python")) # Output: 6
print(max([3, 7, 1, 9])) # Output: 9
print(abs(-10)) # Output: 10
print(round(5.67)) # Output: 6

2. De ned in Modules: Functions available in external modules.


◦ Example: math.sqrt() from the math module, random.randint()
from the random module.
3. User-De ned Functions: Functions created by the programmer using the def keyword.
✅ Example:

python
# Function with parameters
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")

greet("Alice", 25)
greet("Bob", 30)

B. Creating User-De ned Functions

python
def greet(name): # Function definition
print(f"Hello, {name}!")

greet("Alice") # Function call

6 of 31
fi
fi
fi
fl
fi
C. Arguments and Parameters

• Parameters: Variables listed in the function de nition.


• Arguments: Values passed when calling the function.

D. Types of Parameters

1. Positional Parameters: Values passed in the same order as the function de nition.
python
def details(name, age):
print(f"Name: {name}, Age: {age}")

details("Bob", 25)
2. Default Parameters: Parameters with pre-de ned values.
python
def greet(name="Guest"):
print(f"Hello, {name}!")

greet() # Output: Hello, Guest!


greet("Alice") # Output: Hello, Alice!
3. Keyword Arguments: Arguments passed using parameter names.
python
def display(name, age):
print(f"Name: {name}, Age: {age}")

display(age=20, name=“Alice")

4. Variable-Length Arguments:
◦ *args: For non-keyword variable-length arguments.
◦ **kwargs: For keyword variable-length arguments.

python
def sum_all(*args):
print(sum(args))

sum_all(1, 2, 3, 4) # Output: 10

def display_info(**kwargs):
print(kwargs)

display_info(name="Alice", age=25) # Output: {'name':


'Alice', 'age': 25}

E. Flow of Execution

7 of 31
fi
fi
fi
1. Function de nition is stored in memory but not executed immediately.
2. When called, control moves to the function.
3. After execution, control returns to the point where it was called.

F. Scope of Variables

• Local Scope: Variables declared inside a function.


• Global Scope: Variables declared outside all functions.
• Use global keyword to modify a global variable inside a function.
python
x = 10 # Global variable

def update():
global x
x += 5

update()
print(x) # Output: 15

⚠ 2. Exception Handling

•Exception: An error during program execution.


•Exception Handling: Using try-except-finally blocks to catch and manage
errors.
Syntax:

python
try:
# Code that may raise an exception
x = int(input("Enter a number: "))
print(10 / x)
except ValueError:
print("Invalid input. Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Execution complete.")
• try: The block where you write the code that might raise an exception.
• except: The block to catch the exception.
• finally: The block that always executes (optional).
💡 A. Try-Except Block

✅ Example:
python

try:
8 of 31
fi
num = int(input("Enter a number: "))
print(10 / num)
except ValueError:
print("Invalid input. Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
Explanation:

• If the user enters a string → ValueError is raised.


• If the user enters 0 → ZeroDivisionError is raised.
• Both errors are handled separately.

💡 B. Try-Except-Finally

✅ Example:

python
try:
f = open("data.txt", "r")
print(f.read())
except FileNotFoundError:
print("File not found.")
finally:
print("Closing file.")
f.close()
• The finally block always executes, even if there is an exception.

Explanation : Write a Python program that reads two numbers from the user and divides the rst by
the second.
Use try-except blocks to handle:

• ValueError → If the input is not a number.


• ZeroDivisionError → If the second number is zero.

🗃 3. Introduction to Files

• Types of Files:

1. Text Files: Contains plain text data.


2. Binary Files: Contains binary data (images, videos, etc.).
3. CSV Files: Comma-separated values, used for tabular data.
• File Paths:

1. Relative Path: Refers to the current directory.


2. Absolute Path: Complete path from the root.

9 of 31
fi
📝 4. Text File Operations

A. Opening a Text File

python
# Modes: r, r+, w, w+, a, a+
file = open("data.txt", "r")
• r → Read ( le must exist)
• r+ → Read and write
• w → Write (overwrites le or creates a new le)
• w+ → Read and write (creates a new le if it doesn't exist)
• a → Append
• a+ → Append and read
B. Closing a File

python
file.close()
C. With Clause

• Automatically closes the le after use.


Python
with open("data.txt", "r") as file:
content = file.read()
print(content)
D. Writing/Appending Data

python
# Writing
with open("data.txt", "w") as file:
file.write("Hello, World!")

# Appending
with open("data.txt", "a") as file:
file.write("\nAppending new data.")
E. Reading Data

python
# Read the entire file
content = file.read()

# Read one line


line = file.readline()

# Read all lines into a list


lines = file.readlines()
F. Seek and Tell

10 of 31
fi
fi
fi
fi
fi
python
file.seek(0) # Moves the cursor to the beginning
pos = file.tell() # Gets current cursor position

🔥 5. Binary File Operations

• Use the pickle module for binary les.


A. Opening a Binary File

python
file = open("data.bin", "wb") # Write binary mode
B. Writing and Reading Binary Files

python
import pickle

# Writing to binary file


data = {"name": "Alice", "age": 25}
with open("data.bin", "wb") as file:
pickle.dump(data, file)

# Reading from binary file


with open("data.bin", "rb") as file:
content = pickle.load(file)
print(content)

📊 6. CSV File Operations

• Use the csv module for handling CSV les.


A. Writing to CSV File

python
import csv

# Writing to CSV
data = [["Name", "Age"], ["Alice", 25], ["Bob", 30]]
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
B. Reading from CSV File

python
# Reading from CSV
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
11 of 31
fi
fi
print(row)

🔥 7. Data Structures: Stack

• Stack: A linear data structure following LIFO (Last In, First Out).
A. Stack Operations

1. Push: Add an element to the top of the stack. Append()


2. Pop: Remove and return the topmost element. Pop()

B. Implementing Stack Using List

python
stack = []

# Push Operation
stack.append(10)
stack.append(20)

# Pop Operation
print(stack.pop()) # Removes and returns 20
print(stack) # Output: [10]

12 of 31
QUESTION AND PRACTICE:—

A : ✅ 💡 Python Programs for Binary File Operations with employee.bin

🚀 1. Program to Create a Binary File employee.bin with Employee Details

python
import pickle

# List to hold employee details


employees = []

# Function to add employee details


def add_employee():
name = input("Enter employee name: ")
age = int(input("Enter employee age: "))
salary = float(input("Enter employee salary: "))

# Create dictionary with employee details


employee = {"name": name, "age": age, "salary": salary}

# Append to the list


employees.append(employee)

# Ask the user how many employees to add


n = int(input("How many employees do you want to add? "))

# Add employee details


for _ in range(n):
add_employee()

# Write to binary file


with open("employee.bin", "wb") as f:
pickle.dump(employees, f)

print(f"{n} employee(s) saved successfully in


'employee.bin'.")
✅ Explanation:

• This program creates a binary le employee.bin with employee details (name, age,
salary) stored as dictionaries in a list.
• The list is saved into the binary le using pickle.dump().

13 of 31
fi
fi
🔥 2. Program to Read and Display the Contents of employee.bin

python
import pickle

# Read and display employee details from the binary file


try:
with open("employee.bin", "rb") as f:
employees = pickle.load(f)

print("\nEmployee Details:")
for emp in employees:
print(f"Name: {emp['name']}, Age: {emp['age']},
Salary: {emp['salary']}")
except FileNotFoundError:
print("File not found.")
except EOFError:
print("File is empty.")
✅ Explanation:

• This program reads the employee.bin binary le using pickle.load() and


displays the employee details.
• It handles exceptions like FileNotFoundError and EOFError gracefully.

🔍 3. Program to Search for an Employee by Name in the Binary File

python
import pickle

# Function to search for employee by name


def search_employee(name):
try:
with open("employee.bin", "rb") as f:
employees = pickle.load(f)

found = False
for emp in employees:
if emp['name'].lower() == name.lower():
print(f"\nEmployee Found:\nName:
{emp['name']}, Age: {emp['age']}, Salary: {emp['salary']}")
found = True
break

if not found:

14 of 31
fi
print(f"No employee found with the name
'{name}'.")

except FileNotFoundError:
print("File not found.")
except EOFError:
print("File is empty.")

# Take name as input from the user


emp_name = input("Enter the employee name to search: ")
search_employee(emp_name)
✅ Explanation:

• This program searches for an employee by name in the binary le.


• It compares the input name with each employee’s name (case-insensitive) and displays the
details if found.
• If no employee is found, it displays a message.

➕ 4. Program to Append New Employee Records to an Existing Binary File

python
import pickle
import os

# Function to append new employee details


def append_employee():
new_employee = {
"name": input("Enter employee name: "),
"age": int(input("Enter employee age: ")),
"salary": float(input("Enter employee salary: "))
}

# Load existing employees or create an empty list if the


file doesn't exist
employees = []

# Check if the file exists before reading


if os.path.exists("employee.bin"):
with open("employee.bin", "rb") as f:
try:
employees = pickle.load(f)
except EOFError:
employees = []

# Append the new employee and write back to the file

15 of 31
fi
employees.append(new_employee)

with open("employee.bin", "wb") as f:


pickle.dump(employees, f)

print("\nNew employee record appended successfully!")

# Append new employee


append_employee()
✅ Explanation:

• This program appends new employee records to an existing binary le.


• It rst reads the current contents, adds the new employee, and writes the updated list back to
the binary le.
• It handles the case when the le doesn’t exist or is empty.

💰 5. Program to Update the Salary of a Speci c Employee in the Binary File

python
import pickle

# Function to update employee salary


def update_salary(emp_name, new_salary):
try:
with open("employee.bin", "rb") as f:
employees = pickle.load(f)

updated = False

for emp in employees:


if emp['name'].lower() == emp_name.lower():
emp['salary'] = new_salary
updated = True
print(f"\nSalary updated successfully for
{emp['name']}.")
break

if not updated:
print(f"No employee found with the name
'{emp_name}'.")

# Write the updated data back to the file


with open("employee.bin", "wb") as f:
pickle.dump(employees, f)

16 of 31
fi
fi
fi
fi
fi
except FileNotFoundError:
print("File not found.")
except EOFError:
print("File is empty.")

# Take name and new salary as input from the user


emp_name = input("Enter the employee name to update salary:
")
new_salary = float(input("Enter the new salary: "))

# Call the function to update the salary


update_salary(emp_name, new_salary)
✅ Explanation:

• This program updates the salary of a speci c employee.


• It reads the existing binary le, updates the salary of the matching employee, and writes the
modi ed list back to the le.

🚀 🔥 ✅ Key Features in These Programs

1. Creation: Creates a binary le with employee details.


2. Reading: Reads and displays all employee details.
3. Searching: Finds an employee by name.
4. Appending: Adds new records to an existing binary le.
5. Updating: Modi es the salary of a speci c employee.

17 of 31
fi
fi
fi
fi
fi
fi
fi
fi
B: ✅ 💡 Python Code-Based Solutions

🔥 1. Function to Reverse a String

python
def reverse_string(s):
return s[::-1]

# Test the function


string = input("Enter a string: ")
print("Reversed String:", reverse_string(string))
✅ Explanation:

• The function uses slicing ([::-1]) to reverse the string.


• Example:
◦ Input: Python
◦ Output: nohtyP

🔥 2. Function to Find the Sum of All Even Numbers in a List

python
def sum_even(lst):
return sum(num for num in lst if num % 2 == 0)

# Test the function


numbers = list(map(int, input("Enter a list of numbers
separated by space: ").split()))
print("Sum of even numbers:", sum_even(numbers))
✅ Explanation:

• The function uses list comprehension to lter even numbers and then calculates their sum.
• Example:
◦ Input: 1 2 3 4 5 6
◦ Output: 12
🔥 3. Function with Default Parameters (Name and Age)

python
def greet(name, age=18):
print(f"Hello, {name}. You are {age} years old.")

# Test cases
greet("Alice") # Uses default age
greet("Bob", 25) # Uses provided age

18 of 31
fi
✅ Explanation:
• The function has a default parameter (age=18), so if no age is provided, it defaults to
18.
• Example Output:
◦ greet("Alice") → Hello, Alice. You are 18 years old.
◦ greet("Bob", 25) → Hello, Bob. You are 25 years old.
🔥 4. Program Using a Global Variable Inside a Function

python
x = 10 # Global variable

def modify_global():
global x # Access the global variable
x += 5 # Modify its value
print("Inside Function:", x)

# Test the program


print("Before Function:", x)
modify_global()
print("After Function:", x)
✅ Explanation:

• The program uses the global keyword to modify the value of a global variable inside a
function.
• Example Output:
◦ Before Function: 10
◦ Inside Function: 15
◦ After Function: 15
🔥 5. Function to Return a New List Containing Only Odd Numbers

python
def odd_numbers(lst):
return [num for num in lst if num % 2 != 0]

# Test the function


numbers = list(map(int, input("Enter a list of numbers
separated by space: ").split()))
print("Odd Numbers:", odd_numbers(numbers))
✅ Explanation:

• The function uses list comprehension to create a new list containing only odd numbers.
• Example:
◦ Input: 1 2 3 4 5 6 7
◦ Output: [1, 3, 5, 7]

19 of 31
C: ✅ 💡 Python Programs for Text File Operations with students.txt

🔥 1. Program to Create students.txt and Write Student Records

python
# Creating and writing to the text file
with open("students.txt", "w") as f:
f.write("Name: Alice, Age: 20\n")
f.write("Name: Bob, Age: 22\n")
f.write("Name: Charlie, Age: 23\n")

print("File 'students.txt' created and records added


successfully.")
✅ Explanation:

• The program creates a text le named students.txt using the write mode ("w").
• It writes three student records, each on a new line.

🔥 2. Program to Read and Display the Contents of students.txt Line by


Line

python
# Reading and displaying the contents line by line
with open("students.txt", "r") as f:
print("\nContents of 'students.txt':")
for line in f:
print(line.strip()) # Strip removes leading/trailing
whitespace
✅ Explanation:

• The program opens the le in read mode ("r") and iterates through each line using a loop.
• It displays each line one by one.
• .strip() removes any extra whitespace or newline characters.

🔥 3. Program to Write Multiple Lines to a Text File and Read in Different


Ways

📌 Part 1: Write Multiple Lines

python
# Writing multiple lines
lines = [
"Name: David, Age: 25\n",
20 of 31
fi
fi
"Name: Eva, Age: 24\n",
"Name: Frank, Age: 26\n"
]

# Writing to the file


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

print("\nNew lines written to 'students.txt'.")


📌 Part 2: Read Entire File Content

python
# Reading the entire file content
with open("students.txt", "r") as f:
content = f.read()
print("\nFull Content:\n", content)
📌 Part 3: Read Line by Line Using a Loop

python
# Reading line by line using a loop
with open("students.txt", "r") as f:
print("\nReading line by line:")
for line in f:
print(line.strip())
✅ Explanation:

• The program writes multiple lines using writelines().


• It reads the entire le content using .read() and displays it.
• It then reads the content line by line using a loop.

🔥 4. Program Using seek() and tell() Methods

python
# Create a sample text file
with open("sample.txt", "w") as f:
f.write("Hello, Python learners!\nWelcome to file
handling.")

# Using seek() and tell()


with open("sample.txt", "r") as f:
print("\nReading first 5 characters:")
print(f.read(5)) # Read first 5 characters

print("\nCurrent cursor position:", f.tell()) # Display


current position
21 of 31
fi
f.seek(0) # Move cursor back to the
beginning
print("\nContent from beginning:")
print(f.read()) # Read the entire file
again
✅ Explanation:

• The program rst creates a sample text le with two lines.


• It uses:
◦ f.read(5) → Reads the rst 5 characters.
◦ f.tell() → Displays the current cursor position.
◦ f.seek(0) → Moves the cursor to the beginning.

🔥 5. Program to Append New Student Records to an Existing Text File

python
# Append new records
new_students = [
"Name: George, Age: 21\n",
"Name: Hannah, Age: 22\n"
]

# Appending to the existing file


with open("students.txt", "a") as f:
f.writelines(new_students)

print("\nNew student records appended successfully.")

# Display the updated file content


print("\nUpdated 'students.txt' content:")
with open("students.txt", "r") as f:
print(f.read())
✅ Explanation:

• The program appends new student records to the existing le using append mode ("a").
• It writes the new records and displays the updated content.

🚀 🔥 ✅ Key Features in These Programs

1. Creation: Creates a text le and writes multiple records.


2. Reading: Reads and displays the content line by line or all at once.
3. Seek and Tell: Demonstrates cursor movement and position tracking.
4. Appending: Adds new records to an existing le without overwriting.

22 of 31
fi
fi
fi
fi
fi
fi
C: ✅ 💡 Python Programs for CSV File Operations with data.csv

🔥 1. Program to Create a CSV File data.csv with Sample Data

python
import csv

# Sample data
data = [
["Name", "Age", "City"],
["Alice", 25, "New York"],
["Bob", 30, "Los Angeles"],
["Charlie", 22, "Chicago"]
]

# Writing data to the CSV file


with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)

print("File 'data.csv' created successfully with sample


data.")
✅ Explanation:

• The program uses the csv module to create a CSV le named data.csv.
• The writer.writerows() method writes multiple rows at once.
• The newline="" parameter prevents the addition of extra blank lines between rows.

🔥 2. Program to Read and Display the Contents of data.csv

python
import csv

# Reading and displaying the content of the CSV file


with open("data.csv", "r") as f:
reader = csv.reader(f)

print("\nContents of 'data.csv':")
for row in reader:
print(", ".join(row))
✅ Explanation:

• The program opens the CSV le in read mode ("r").

23 of 31
fi
fi
• It uses csv.reader() to read the rows and displays them.
• The ", ".join(row) combines the elds with commas for clear display.

🔥 3. Program to Append New Rows to the Existing CSV File

python
import csv

# New rows to append


new_data = [
["David", 28, "San Francisco"],
["Eva", 35, "Houston"]
]

# Appending the new rows to the CSV file


with open("data.csv", "a", newline="") as f:
writer = csv.writer(f)
writer.writerows(new_data)

print("\nNew rows appended successfully!")

# Display the updated CSV content


print("\nUpdated 'data.csv' content:")
with open("data.csv", "r") as f:
print(f.read())
✅ Explanation:

• The program uses append mode ("a") to add new rows to the existing CSV le.
• It writes the new rows using writer.writerows().
• The program then displays the updated le content.

🔥 4. Program to Search for a Person by Name in the CSV File

python
import csv

# Function to search for a person by name


def search_by_name(name):
with open("data.csv", "r") as f:
reader = csv.reader(f)
found = False

# Skip header row


next(reader)

24 of 31
fi
fi
fi
for row in reader:
if row[0].lower() == name.lower():
print(f"\nPerson Found:\nName: {row[0]}, Age:
{row[1]}, City: {row[2]}")
found = True
break

if not found:
print(f"\nNo person found with the name
'{name}'.")

# Take name input from the user


person_name = input("Enter the name to search: ")
search_by_name(person_name)
✅ Explanation:

• The program reads the CSV le and searches for a person by name.
• It uses case-insensitive comparison for the name.
• If the name is found, it displays the details.
• If not, it shows a "No person found" message.

🔥 5. Program to Update the Age of a Person in the CSV File

python
import csv

# Function to update age


def update_age(name, new_age):
rows = []

# Read the existing data


with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
if row[0].lower() == name.lower():
row[1] = str(new_age) # Update age
print(f"\nAge updated for {name}.")
rows.append(row)

# Write the updated data back to the file


with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)

# Take name and new age as input from the user

25 of 31
fi
person_name = input("Enter the name to update age: ")
new_age = int(input("Enter the new age: "))

# Update the age in the CSV file


update_age(person_name, new_age)

# Display the updated content


print("\nUpdated 'data.csv' content:")
with open("data.csv", "r") as f:
print(f.read())
✅ Explanation:

• The program reads the CSV le into a list of rows.


• It searches for the speci ed name and updates the age.
• It writes the modi ed list back into the le, overwriting the old content.
• The updated CSV content is displayed.

🚀 🔥 ✅ Key Features in These Programs

1. Creation: Creates a CSV le with sample data.


2. Reading: Reads and displays the content of the CSV le.
3. Appending: Adds new rows without deleting existing data.
4. Searching: Finds and displays a person's details by name.
5. Updating: Modi es the age of a speci c person.

26 of 31
fi
fi
fi
fi
fi
fi
fi
fi
E: ✅ 💡 Python Programs for Stack Operations

🔥 1. Python Program to Implement a Stack Using a List

python
# Stack implementation using a list
stack = []

# Push operation
def push(element):
stack.append(element)
print(f"Pushed: {element}")

# Pop operation
def pop():
if len(stack) == 0:
print("Stack is empty.")
else:
print(f"Popped: {stack.pop()}")

# Display operation
def display():
if len(stack) == 0:
print("Stack is empty.")
else:
print("Stack contents:", stack)

# Menu-driven program
while True:
print("\n1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:
value = input("Enter the element to push: ")
push(value)
elif choice == 2:
pop()
elif choice == 3:
display()
elif choice == 4:
27 of 31
print("Exiting program.")
break
else:
print("Invalid choice. Try again.")
✅ Explanation:

• This program implements a stack with push, pop, and display operations.
• It uses a menu-driven approach for interaction.

🔥 2. Program to Reverse a String Using a Stack

python
# Function to reverse a string using a stack
def reverse_string(s):
stack = list(s) # Push all characters into the stack
reversed_str = ""

while stack:
reversed_str += stack.pop() # Pop and add to the
result

return reversed_str

# Test the program


string = input("Enter a string to reverse: ")
print("Reversed String:", reverse_string(string))
✅ Explanation:

• The program pushes all characters of the string into a stack.


• It pops them one by one to form the reversed string.
• Example:
◦ Input: Python
◦ Output: nohtyP

🔥 3. Program to Check if a String is Balanced with Respect to Parentheses ()

python
# Function to check balanced parentheses
def is_balanced(s):
stack = []

for char in s:
if char == "(":
stack.append(char)
elif char == ")":

28 of 31
if len(stack) == 0:
return False
stack.pop()

return len(stack) == 0

# Test the program


expr = input("Enter a string with parentheses: ")

if is_balanced(expr):
print("The string is balanced.")
else:
print("The string is NOT balanced.")
✅ Explanation:

• The program uses a stack to track the opening and closing parentheses.
• It pushes ( onto the stack and pops it when ) is encountered.
• It checks if the stack is empty at the end to determine balance.
• Example:
◦ (a + b) * (c + d) → Balanced ✅
◦ ((a + b) * (c + d → Not Balanced ❌

🔥 4. Program to Convert Decimal Numbers to Binary Using a Stack

python
# Function to convert decimal to binary using a stack
def decimal_to_binary(n):
if n == 0:
return "0"

stack = []

while n > 0:
stack.append(str(n % 2)) # Push remainder (0 or 1)
onto stack
n = n // 2

binary = "".join(stack[::-1]) # Reverse the stack to get


the correct binary
return binary

# Test the program


num = int(input("Enter a decimal number: "))
print(f"Binary representation: {decimal_to_binary(num)}")

29 of 31
✅ Explanation:

• The program uses a stack to store the remainders of successive division by 2.


• It pops the elements to form the binary string.
• Example:
◦ Input: 10 → Output: 1010
◦ Input: 5 → Output: 101

🔥 5. Program to Sort Elements of a Stack Using Another Stack

python
# Function to sort stack using another stack
def sort_stack(original):
sorted_stack = []

while original:
temp = original.pop()

# Place temp at the right position in sorted_stack


while sorted_stack and sorted_stack[-1] > temp:
original.append(sorted_stack.pop())

sorted_stack.append(temp)

return sorted_stack

# Test the program


stack = [34, 3, 31, 98, 92, 23]
print("Original Stack:", stack)

# Sorting the stack


sorted_stack = sort_stack(stack)
print("Sorted Stack:", sorted_stack)
✅ Explanation:

• The program uses two stacks:


◦ Original stack: Holds the unsorted elements.
◦ Sorted stack: Holds the sorted elements.
• It repeatedly pops the elements from the original stack and inserts them into the sorted stack
in the correct order.
• Example:
◦ Input: [34, 3, 31, 98, 92, 23]
◦ Output: [3, 23, 31, 34, 92, 98]

🚀 🔥 ✅ Key Features in These Programs

30 of 31
1. Basic Stack Operations: Implemented push, pop, and display functions.
2. String Manipulation:
◦ Reversed a string using a stack.
◦ Checked for balanced parentheses.
3. Number Conversion:
◦ Converted decimal to binary using a stack.
4. Sorting:
◦ Sorted stack elements using another stack.

31 of 31

You might also like