python basics cs 12 pdf
python basics cs 12 pdf
Python Basics
Python is a high-level, interpreted programming language used for various applications such as
web development, data science, and automation.
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
1. Arithmetic Operators
1 of 31
3. Logical Operators
python
x = 10
y = 5
print(x + y) # Output: 15
print(x > y and y < 10) # Output: True
C. Conditional Statements
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
1. for Loop
2 of 31
python
2. while Loop
python
count = 1
while count <= 5:
print(count)
count += 1
2. Python Functions
Functions allow code reuse and modular programming.
A. Built-in Functions
Example:
python
print(len("Hello")) # Output: 5
print(max([3, 7, 2, 9])) # Output: 9
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
python
square = lambda x: x ** 2
print(square(5)) # Output: 25
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
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
python
5 of 31
fi
fi
2. 🔥 1. Functions
A. Types of Functions
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
python
# Function with parameters
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
greet("Alice", 25)
greet("Bob", 30)
python
def greet(name): # Function definition
print(f"Hello, {name}!")
6 of 31
fi
fi
fi
fl
fi
C. Arguments and Parameters
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}!")
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)
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
def update():
global x
x += 5
update()
print(x) # Output: 15
⚠ 2. Exception Handling
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:
💡 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:
🗃 3. Introduction to Files
• Types of Files:
9 of 31
fi
📝 4. Text File Operations
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
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()
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
python
file = open("data.bin", "wb") # Write binary mode
B. Writing and Reading Binary Files
python
import pickle
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)
• Stack: A linear data structure following LIFO (Last In, First Out).
A. Stack Operations
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:—
python
import pickle
• 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
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:
python
import pickle
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.")
python
import pickle
import os
15 of 31
fi
employees.append(new_employee)
python
import pickle
updated = False
if not updated:
print(f"No employee found with the name
'{emp_name}'.")
16 of 31
fi
fi
fi
fi
fi
except FileNotFoundError:
print("File not found.")
except EOFError:
print("File is empty.")
17 of 31
fi
fi
fi
fi
fi
fi
fi
fi
B: ✅ 💡 Python Code-Based Solutions
python
def reverse_string(s):
return s[::-1]
python
def sum_even(lst):
return sum(num for num in lst if num % 2 == 0)
• 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)
• 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]
• 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
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")
• The program creates a text le named students.txt using the write mode ("w").
• It writes three student records, each on a new 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.
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"
]
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:
python
# Create a sample text file
with open("sample.txt", "w") as f:
f.write("Hello, Python learners!\nWelcome to file
handling.")
python
# Append new records
new_students = [
"Name: George, Age: 21\n",
"Name: Hannah, Age: 22\n"
]
• The program appends new student records to the existing le using append mode ("a").
• It writes the new records and displays the updated content.
22 of 31
fi
fi
fi
fi
fi
fi
C: ✅ 💡 Python Programs for CSV File Operations with data.csv
python
import csv
# Sample data
data = [
["Name", "Age", "City"],
["Alice", 25, "New York"],
["Bob", 30, "Los Angeles"],
["Charlie", 22, "Chicago"]
]
• 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.
python
import csv
print("\nContents of 'data.csv':")
for row in reader:
print(", ".join(row))
✅ Explanation:
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.
python
import csv
• 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.
python
import csv
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}'.")
• 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.
python
import csv
25 of 31
fi
person_name = input("Enter the name to update age: ")
new_age = int(input("Enter the new age: "))
26 of 31
fi
fi
fi
fi
fi
fi
fi
fi
E: ✅ 💡 Python Programs for Stack Operations
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")
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.
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
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
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 ❌
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
29 of 31
✅ Explanation:
python
# Function to sort stack using another stack
def sort_stack(original):
sorted_stack = []
while original:
temp = original.pop()
sorted_stack.append(temp)
return sorted_stack
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