Python Programming Guide for B.Tech Students
Python Programming Guide for B.Tech Students
Units IV & V
Page 1 of 38
UNIT IV
Python Fundamentals
1. Python Interpreter
The Python interpreter is a program that reads and executes Python code. Python can be run
in two modes: interactive mode and script mode.
# File: [Link]
print("Hello, Python!")
print("This is script mode")
# Run from terminal: python [Link]
# Output:
# Hello, Python!
# This is script mode
Note: Python is an interpreted language, meaning code is executed line by line. This makes
debugging easier but can be slower than compiled languages like C.
Page 2 of 38
2. Basic Python Structure
Python programs consist of statements organized into logical blocks. A well-structured Python
program is easy to read and maintain.
# Basic structure of a Python program
# 1. Comments (for documentation)
# This is a single-line comment
"""
This is a multi-line comment
or docstring, used for documentation
"""
# 2. Import statements (at the top)
import math
from datetime import datetime
# 3. Constants and global variables
PI = 3.14159
GRAVITY = 9.8
# 4. Function definitions
def calculate_area(radius):
"""Calculate area of a circle"""
return PI * radius ** 2
# 5. Main program code
if __name__ == "__main__":
radius = 5
area = calculate_area(radius)
print(f"Area of circle: {area}")
3. Indentation
Python uses indentation (whitespace at the beginning of lines) to define code blocks. This is
unique to Python and makes code highly readable. Most other languages use curly braces {}.
Page 3 of 38
Nested blocks Increase indentation for each level if y > 0:
Page 4 of 38
4. Python Concepts
4.1 Keywords
Keywords are reserved words in Python that have special meanings. You cannot use them as
variable names or identifiers.
4.2 Identifiers
Identifiers are names given to variables, functions, classes, etc. They must follow specific
rules in Python.
# Valid identifiers
student_name = "Alice"
_private_var = 100
Course2024 = "Python Programming"
my_list = [1, 2, 3]
Page 5 of 38
# Naming conventions (not rules, but good practice)
CONSTANT_VALUE = 3.14159 # Constants: UPPERCASE
class_name = "[Link]" # Variables: lowercase with underscores
MyClass = "Example" # Classes: PascalCase
# Invalid identifiers (will cause errors)
# 2students = 10 # Starts with digit
# my-variable = 5 # Contains hyphen
# for = 10 # Keyword used as identifier
Page 6 of 38
4.3 Statements and Expressions
Statement: An instruction that Python can execute (does something).
Expression: A combination of values and operators that evaluates to a value.
Page 7 of 38
name = input("Enter your name: ")
print(f"Hello, {name}!")
# Input with type conversion
age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))
print(f"Age: {age}, Height: {height}")
# Complete example: Simple calculator
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Enter operation (+, -, *, /): ")
if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
elif operation == '/':
if num2 != 0:
result = num1 / num2
else:
result = "Error: Division by zero"
else:
result = "Invalid operation"
print(f"Result: {result}")
Important: input() always returns a string. Use int(), float(), etc. to convert to the required data
type.
Page 8 of 38
5. Functions
Functions are reusable blocks of code that perform specific tasks. They help organize code,
avoid repetition, and make programs easier to understand.
Page 9 of 38
# Multiple default parameters
def student_info(name, age=18, grade="A"):
"""Display student information"""
print(f"Name: {name}, Age: {age}, Grade: {grade}")
student_info("Alice") # Uses all defaults
student_info("Bob", 20) # Overrides age
student_info("Charlie", 19, "B") # Overrides both
student_info("Diana", grade="A+") # Keyword argument
Page 10 of 38
5.5 Variable-length Arguments
# *args - Variable number of positional arguments
def sum_all(*numbers):
"""Sum any number of arguments"""
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3)) # Output: 6
print(sum_all(10, 20, 30, 40)) # Output: 100
# **kwargs - Variable number of keyword arguments
def student_report(**details):
"""Print student details from keyword arguments"""
for key, value in [Link]():
print(f"{key}: {value}")
student_report(name="Alice", age=19, grade="A", city="Mumbai")
# Combining all types
def complex_function(pos1, pos2, *args, default_val=10, **kwargs):
print(f"Positional: {pos1}, {pos2}")
print(f"Extra positional: {args}")
print(f"Default: {default_val}")
print(f"Keyword args: {kwargs}")
complex_function(1, 2, 3, 4, 5, course="Python", level="Beginner")
# Regular function
def square(x):
return x ** 2
# Equivalent lambda function
square_lambda = lambda x: x ** 2
print(square(5)) # Output: 25
print(square_lambda(5)) # Output: 25
# Lambda with multiple arguments
add = lambda x, y: x + y
print(add(3, 7)) # Output: 10
# Lambda in sorting
students = [
{"name": "Alice", "age": 20},
{"name": "Bob", "age": 18},
{"name": "Charlie", "age": 22}
]
# Sort by age using lambda
students_by_age = sorted(students, key=lambda s: s["age"])
print(students_by_age)
# Lambda with map() - apply function to all items
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
# Lambda with filter() - filter items
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4]
Page 11 of 38
# Global variable
global_var = "I am global"
def my_function():
# Local variable
local_var = "I am local"
print(global_var) # Can access global
print(local_var) # Can access local
my_function()
print(global_var) # Can access global
# print(local_var) # Error: local_var not accessible outside function
# Modifying global variable
counter = 0
def increment():
global counter # Declare global to modify
counter += 1
print(f"Counter: {counter}")
increment() # Counter: 1
increment() # Counter: 2
print(counter) # Output: 2
Page 12 of 38
6. Recursion
Recursion is a programming technique where a function calls itself. Every recursive function
must have a base case (stopping condition) and a recursive case (where it calls itself).
Page 13 of 38
# Trace of sum_digits(123):
# sum_digits(123) = 3 + sum_digits(12)
# sum_digits(12) = 2 + sum_digits(1)
# sum_digits(1) = 1 + sum_digits(0)
# sum_digits(0) = 0 # Base case
# Working backwards: 0, 1+0=1, 2+1=3, 3+3=6
Warning: Deep recursion can cause stack overflow. Python has a default recursion limit
(usually 1000). For large inputs, prefer iterative solutions or increase the limit using
[Link]().
Page 14 of 38
UNIT V
Strings, Lists, Tuples, Dictionaries, and Files
Page 15 of 38
1.3 Important String Methods
text = " Python Programming "
# Case conversion
print([Link]()) # Output: PYTHON PROGRAMMING
print([Link]()) # Output: python programming
print([Link]()) # Output: python programming
print("hello world".title()) # Output: Hello World
# Whitespace removal
print([Link]()) # Output: Python Programming
print([Link]()) # Left strip
print([Link]()) # Right strip
# Finding substrings
sentence = "Python is awesome, Python is powerful"
print([Link]("Python")) # Output: 0 (first occurrence)
print([Link]("Java")) # Output: -1 (not found)
print([Link]("awesome")) # Output: 10
print([Link]("Python")) # Output: 2
# Replacing
new_sentence = [Link]("Python", "Java")
print(new_sentence) # Output: Java is awesome, Java is powerful
# Splitting and joining
words = "apple,banana,orange".split(",")
print(words) # Output: ['apple', 'banana', 'orange']
joined = " - ".join(words)
print(joined) # Output: apple - banana - orange
# Checking string properties
print("hello".isalpha()) # Output: True
print("hello123".isalnum()) # Output: True
print("12345".isdigit()) # Output: True
print(" ".isspace()) # Output: True
print("Hello World".istitle()) # Output: True
Page 16 of 38
2. Lists
Lists are ordered, mutable (changeable) collections that can hold items of different types.
They are one of the most versatile data structures in Python.
Page 17 of 38
[Link](1, 15) # Insert at index 1
print(numbers) # Output: [10, 15, 2, 3, 4, 5, 6]
[Link]([7, 8, 9]) # Add multiple elements
print(numbers) # Output: [10, 15, 2, 3, 4, 5, 6, 7, 8, 9]
# Removing elements
[Link](15) # Remove first occurrence of 15
print(numbers) # Output: [10, 2, 3, 4, 5, 6, 7, 8, 9]
popped = [Link]() # Remove and return last element
print(popped) # Output: 9
print(numbers) # Output: [10, 2, 3, 4, 5, 6, 7, 8]
del numbers[0] # Delete by index
print(numbers) # Output: [2, 3, 4, 5, 6, 7, 8]
[Link]() # Remove all elements
print(numbers) # Output: []
Page 18 of 38
2.4 List Methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
# Sorting
[Link]() # Sort in place (ascending)
print(numbers) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]
[Link](reverse=True) # Sort descending
print(numbers) # Output: [9, 6, 5, 5, 4, 3, 2, 1, 1]
# Sorted (returns new list)
original = [3, 1, 4, 1, 5]
sorted_list = sorted(original)
print(original) # Output: [3, 1, 4, 1, 5] (unchanged)
print(sorted_list) # Output: [1, 1, 3, 4, 5]
# Reversing
[Link]()
print(numbers) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]
# Counting and finding
count = [Link](1)
print(count) # Output: 2
index = [Link](5)
print(index) # Output: 5 (first occurrence)
# Copying
original = [1, 2, 3]
shallow_copy = [Link]() # or original[:]
shallow_copy[0] = 10
print(original) # Output: [1, 2, 3]
print(shallow_copy) # Output: [10, 2, 3]
3. Tuples
Tuples are ordered, immutable (unchangeable) collections. Once created, you cannot modify
their elements. They are faster than lists and protect data from accidental modification.
Page 19 of 38
# Concatenation
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined = tuple1 + tuple2
print(combined) # Output: (1, 2, 3, 4, 5, 6)
# Repetition
repeated = (0,) * 5
print(repeated) # Output: (0, 0, 0, 0, 0)
# Length
print(len(combined)) # Output: 6
# Membership
print(3 in tuple1) # Output: True
# Methods
numbers = (1, 2, 3, 2, 4, 2)
print([Link](2)) # Output: 3
print([Link](3)) # Output: 2
# Immutability demonstration
coords = (10, 20)
# coords[0] = 15 # Error: tuples are immutable
# But tuples can contain mutable objects
mixed_tuple = (1, [2, 3], 4)
mixed_tuple[1].append(5) # Can modify the list inside
print(mixed_tuple) # Output: (1, [2, 3, 5], 4)
Page 20 of 38
3.3 When to Use Tuples vs Lists
4. Dictionaries
Dictionaries are unordered collections of key-value pairs. They provide fast lookup and are
perfect for storing related information.
Page 21 of 38
}
# Accessing nested dictionaries
school = {
"students": {
"101": {"name": "Alice", "grade": "A"},
"102": {"name": "Bob", "grade": "B"}
}
}
print(school["students"]["101"]["name"]) # Output: Alice
Page 22 of 38
4.2 Modifying Dictionaries
student = {"name": "Alice", "roll_no": 101}
# Adding new key-value pair
student["grade"] = "A"
student["age"] = 19
print(student) # Output: {'name': 'Alice', 'roll_no': 101, 'grade': 'A', 'age': 19}
# Updating existing value
student["grade"] = "A+"
print(student)
# Updating multiple values
[Link]({"age": 20, "city": "Mumbai"})
print(student)
# Removing items
del student["city"] # Remove specific key
print(student)
removed_value = [Link]("age") # Remove and return value
print(removed_value) # Output: 20
last_item = [Link]() # Remove and return last item
print(last_item)
[Link]() # Remove all items
print(student) # Output: {}
Page 23 of 38
4.4 Dictionary Applications
# Word frequency counter
text = "hello world hello python python python"
words = [Link]()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count)
# Output: {'hello': 2, 'world': 1, 'python': 3}
# Student database
students_db = {
101: {"name": "Alice", "marks": [85, 90, 88]},
102: {"name": "Bob", "marks": [78, 82, 80]},
103: {"name": "Charlie", "marks": [92, 95, 89]}
}
# Calculate average marks for each student
for roll_no, info in students_db.items():
avg = sum(info["marks"]) / len(info["marks"])
print(f"{info['name']}: Average = {avg:.2f}")
# Phone book
phonebook = {
"Alice": "123-456-7890",
"Bob": "234-567-8901",
"Charlie": "345-678-9012"
}
name = "Bob"
if name in phonebook:
print(f"{name}'s phone: {phonebook[name]}")
Page 24 of 38
5. List Comprehension
List comprehension provides a concise way to create lists. It's more readable and often faster
than traditional loops.
Page 25 of 38
print(matrix) # Output: [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
# Same using list comprehension
matrix = [[i * 3 + j for j in range(3)] for i in range(3)]
print(matrix) # Output: [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
# Flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Create multiplication table
mult_table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
for row in mult_table:
print(row)
# Transpose a matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transposed) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Page 26 of 38
6. File Handling
File handling allows programs to read from and write to files, enabling data persistence and
interaction with external data sources.
Page 27 of 38
[Link]("Hello, World!\n")
[Link]("This is a new line.\n")
# Write multiple lines
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("[Link]", "w") as file:
[Link](lines)
# Append to file (adds to existing content)
with open("[Link]", "a") as file:
[Link]("This line is appended.\n")
# Writing data from list
students = [
{"name": "Alice", "roll": 101, "grade": "A"},
{"name": "Bob", "roll": 102, "grade": "B"},
{"name": "Charlie", "roll": 103, "grade": "A+"}
]
with open("[Link]", "w") as file:
for student in students:
line = f"{student['name']},{student['roll']},{student['grade']}\n"
[Link](line)
# Using print() to write to file
with open("[Link]", "w") as file:
print("Hello, World!", file=file)
print("This is printed to file", file=file)
Page 28 of 38
6.4 File Handling Examples
# Example 1: Count words in a file
def count_words(filename):
try:
with open(filename, "r") as file:
content = [Link]()
words = [Link]()
return len(words)
except FileNotFoundError:
return "File not found"
print(f"Word count: {count_words('[Link]')}")
# Example 2: Copy file contents
def copy_file(source, destination):
with open(source, "r") as src:
content = [Link]()
with open(destination, "w") as dest:
[Link](content)
print(f"Copied {source} to {destination}")
copy_file("[Link]", "[Link]")
# Example 3: Read and process data
def calculate_average_marks(filename):
with open(filename, "r") as file:
total = 0
count = 0
for line in file:
name, marks = [Link]().split(",")
total += int(marks)
count += 1
return total / count if count > 0 else 0
# File content: "Alice,85\nBob,90\nCharlie,78"
avg = calculate_average_marks("[Link]")
print(f"Average marks: {avg:.2f}")
# Example 4: Search in file
def search_in_file(filename, search_term):
with open(filename, "r") as file:
for line_num, line in enumerate(file, 1):
if search_term in line:
print(f"Line {line_num}: {[Link]()}")
search_in_file("[Link]", "Python")
7. Exception Handling
Exceptions are errors that occur during program execution. Exception handling allows
programs to deal with errors gracefully without crashing.
Page 29 of 38
# Multiple exceptions in one except block
try:
num = int(input("Enter a number: "))
result = 100 / num
except (ValueError, ZeroDivisionError) as e:
print(f"Error occurred: {e}")
# Generic exception handler (catches all)
try:
num = int(input("Enter a number: "))
result = 100 / num
except Exception as e:
print(f"An error occurred: {e}")
7.2 try-except-else-finally
# Complete exception handling structure
try:
# Code that might raise an exception
num = int(input("Enter a number: "))
result = 100 / num
except ValueError:
# Handles ValueError
print("Invalid input")
except ZeroDivisionError:
# Handles ZeroDivisionError
print("Cannot divide by zero")
else:
# Executes if no exception occurs
print(f"Result: {result}")
finally:
# Always executes (even if exception occurs)
print("Execution completed")
# File handling with exception
try:
file = open("[Link]", "r")
content = [Link]()
print(content)
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Permission denied")
finally:
# Close file if it was opened
try:
[Link]()
print("File closed")
except:
print("File was not opened")
# Better way using 'with'
try:
with open("[Link]", "r") as file:
content = [Link]()
print(content)
except FileNotFoundError:
print("File not found")
Page 30 of 38
7.3 Common Exceptions
Page 31 of 38
Modules are Python files containing functions, classes, and variables. Packages are
collections of modules organized in directories.
Page 32 of 38
8.2 Creating Your Own Modules
# File: [Link] (your module)
"""
Custom math module with utility functions
"""
PI = 3.14159
def add(a, b):
"""Add two numbers"""
return a + b
def multiply(a, b):
"""Multiply two numbers"""
return a * b
def circle_area(radius):
"""Calculate area of circle"""
return PI * radius ** 2
# File: [Link] (using your module)
import mymath
print([Link](5, 3)) # Output: 8
print(mymath.circle_area(5)) # Output: 78.53975
from mymath import add, PI
print(add(10, 20)) # Output: 30
print(PI) # Output: 3.14159
8.4 Packages
Page 33 of 38
A package is a directory containing multiple modules and a special __init__.py file. It helps
organize related modules.
# Package structure:
# mypackage/
# __init__.py
# [Link]
# [Link]
# subpackage/
# __init__.py
# [Link]
# File: mypackage/[Link]
def func1():
return "Function from module1"
# File: mypackage/[Link]
def func2():
return "Function from module2"
# File: mypackage/__init__.py
# Can be empty or contain initialization code
# Using the package:
# Method 1
import mypackage.module1
print(mypackage.module1.func1())
# Method 2
from mypackage import module1, module2
print(module1.func1())
print(module2.func2())
# Method 3
from mypackage.module1 import func1
print(func1())
Page 34 of 38
Practice Problems
Page 35 of 38
of circle, rectangle, triangle) and use it in another program.
9. Write a program using list comprehension to create a multiplication
table (1-10) as a 2D list.
10. Create a program that:
- Reads student data from a file
- Processes it using dictionaries
- Handles file not found and invalid data exceptions
- Writes results to another file
Page 36 of 38
Summary and Learning Tips
Tip Description
Page 37 of 38
Review Regularly Revisit concepts weekly for retention
Additional Resources
Official Documentation: [Link] Interactive Learning: [Link], [Link]
Practice Platforms: HackerRank, LeetCode, Codewars Video Tutorials: YouTube channels
(Corey Schafer, Programming with Mosh) Books: "Python Crash Course" by Eric Matthes,
"Automate the Boring Stuff" Remember: Programming is a skill that improves with practice.
Don't get discouraged by errors - they're part of the learning process. Every expert
programmer was once a beginner! Good luck with your Python programming journey! ■
Page 38 of 38