Advanced Python Programming (4321602) - Summer 2023 Solution
Solution guide for Advanced Python Programming (4321602) Summer 2023 exam
Question 1(a) [3 marks]
What is List? What are the use of List in python and write characteristics of List.
Answer:
A List is an ordered collection of items (elements) that can store multiple values in a single variable. Lists are mutable and allow duplicate elements.
Table: List Characteristics
| Feature | Description |
|---|---|
| Ordered | Elements have a defined order |
| Mutable | Can be changed after creation |
| Indexed | Access elements using index [0,1,2...] |
| Duplicates | Allows duplicate values |
Uses in Python:
- Data Storage: Store multiple related items
- Dynamic Arrays: Size can change during runtime
- Iteration: Easy to loop through elements
Mnemonic: "OMID - Ordered, Mutable, Indexed, Duplicates"
Question 1(b) [4 marks]
Explain String built-in functions in python.
Answer:
String built-in functions help manipulate and process text data efficiently in Python programs.
Table: Common String Functions
| Function | Purpose | Example |
|---|---|---|
| upper() | Convert to uppercase | "hello".upper() → "HELLO" |
| lower() | Convert to lowercase | "WORLD".lower() → "world" |
| strip() | Remove whitespace | " hi ".strip() → "hi" |
| split() | Split into list | "a,b".split(",") → ['a','b'] |
| replace() | Replace substring | "cat".replace("c","b") → "bat" |
| find() | Find substring position | "hello".find("e") → 1 |
Key Points:
- Immutable: Original string remains unchanged
- Return Values: Functions return new strings
- Case Sensitive: Functions consider case differences
Mnemonic: "ULSR-FR - Upper, Lower, Strip, Replace, Find, Replace"
Question 1(c) [7 marks]
Write how to add, remove, an element from a set. Explain why POP is different from remove.
Answer:
Sets are unordered collections of unique elements. Python provides various methods to modify sets.
Table: Set Operations
| Operation | Method | Syntax | Example |
|---|---|---|---|
| Add | add() | set.add(element) | s.add(5) |
| Remove | remove() | set.remove(element) | s.remove(3) |
| Remove Safe | discard() | set.discard(element) | s.discard(7) |
| Pop | pop() | set.pop() | s.pop() |
Code Example:
Python
POP vs REMOVE Differences:
| Aspect | pop() | remove() |
|---|---|---|
| Target | Random element | Specific element |
| Parameter | No parameter needed | Requires element value |
| Return | Returns removed element | Returns None |
| Error | Error if set is empty | Error if element not found |
Key Points:
- Random Nature: pop() removes arbitrary element due to unordered nature
- Predictability: remove() targets specific known element
- Error Handling: Use discard() to avoid KeyError
Mnemonic: "PRRE - Pop Random, Remove Exact"
Question 1(c OR) [7 marks]
List out built-in Dictionary functions. Write a program to demonstrate the dictionaries functions and operations.
Answer:
Dictionary is a collection of key-value pairs that provides fast lookup and flexible data organization.
Table: Dictionary Functions
| Function | Purpose | Returns |
|---|---|---|
| keys() | Get all keys | dict_keys object |
| values() | Get all values | dict_values object |
| items() | Get key-value pairs | dict_items object |
| get() | Safe value retrieval | Value or None |
| pop() | Remove and return value | Removed value |
| clear() | Remove all items | None |
| update() | Merge dictionaries | None |
Program Example:
Python
Key Features:
- Fast Lookup: O(1) average time complexity
- Flexible Keys: Use strings, numbers, tuples as keys
- Dynamic: Can add/remove items anytime
Mnemonic: "KVIGPCU - Keys, Values, Items, Get, Pop, Clear, Update"
Question 2(a) [3 marks]
Define Tuple and how is it created in python?
Answer:
A Tuple is an ordered collection of items that is immutable (cannot be changed after creation).
Table: Tuple Creation Methods
| Method | Syntax | Example |
|---|---|---|
| Parentheses | (item1, item2) | (1, 2, 3) |
| Without Parentheses | item1, item2 | 1, 2, 3 |
| Single Item | (item,) | (5,) |
| Empty Tuple | () | () |
Code Examples:
Python
Key Points:
- Immutable: Cannot change elements after creation
- Ordered: Elements maintain their position
- Indexable: Access using index like lists
Mnemonic: "IOI - Immutable, Ordered, Indexed"
Question 2(b) [4 marks]
Explain the advantages of the module.
Answer:
Modules are Python files containing functions, classes, and variables that can be imported and reused in other programs.
Table: Module Advantages
| Advantage | Description | Benefit |
|---|---|---|
| Reusability | Use same code multiple times | Saves development time |
| Organization | Separate code into logical units | Better code structure |
| Namespace | Avoid naming conflicts | Cleaner code |
| Maintainability | Update code in one place | Easy debugging |
Benefits:
- Code Reuse: Write once, use many times
- Modularity: Break large programs into smaller parts
- Collaboration: Multiple developers can work on different modules
- Testing: Test individual modules separately
Example Structure:
Python
Mnemonic: "RONM - Reusability, Organization, Namespace, Maintainability"
Question 2(c) [7 marks]
List out the steps to create a user defined package with proper example.
Answer:
A package is a directory containing multiple modules with a special __init__.py file.
Steps to Create Package:
Example Package Structure:
mathtools/
__init__.py
basic.py
advanced.py
Step-by-Step Implementation:
Step 1: Create Directory
Bash
Step 2: Create init.py
Python
Step 3: Create basic.py
Python
Step 4: Create advanced.py
Python
Step 5: Use Package
Python
Key Requirements:
- Directory: Package must be a directory
- init.py: Required file (can be empty)
- Modules: Python files inside package
- Import Path: Python must find package in path
Mnemonic: "DDMFU - Directory, Dunder-init, Modules, Functions, Use"
Question 2(a OR) [3 marks]
Differentiate between Tuple and List.
Answer:
Both Tuple and List are sequence data types but have important differences in behavior and usage.
Table: Tuple vs List Comparison
| Feature | Tuple | List |
|---|---|---|
| Mutability | Immutable (cannot change) | Mutable (can change) |
| Syntax | (1, 2, 3) | [1, 2, 3] |
| Performance | Faster | Slower |
| Methods | Limited methods | Many methods available |
| Use Case | Fixed data | Dynamic data |
| Memory | Less memory | More memory |
Code Example:
Python
When to Use:
- Tuple: Coordinates, database records, function arguments
- List: Shopping cart, student grades, dynamic collections
Mnemonic: "TIF-LIM - Tuple Immutable Fixed, List Mutable Dynamic"
Question 2(b OR) [4 marks]
Explain the intra-package reference concept in python.
Answer:
Intra-package references allow modules within a package to import and use each other using relative imports.
Types of Imports:
Table: Import Types
| Type | Syntax | Usage |
|---|---|---|
| Absolute | from package.module import function | Full path from root |
| Relative | from .module import function | Within same package |
| Parent | from ..module import function | Parent package |
Package Structure Example:
calculator/
__init__.py
basic.py
scientific.py
utils/
__init__.py
helpers.py
Implementation:
Python
Benefits:
- Clean Code: Shorter import statements
- Package Independence: Easy to relocate packages
- Clear Structure: Shows package relationships
Mnemonic: "RAP - Relative, Absolute, Parent imports"
Question 2(c OR) [7 marks]
What is module? Write a program to define a module to find the area and circumference of circle. Import this module in a program and call functions from it.
Answer:
A module is a Python file containing functions, classes, and variables that can be imported and used in other programs.
Circle Module (circle.py):
Python
Main Program (main.py):
Python
Alternative Import Methods:
Python
Module Benefits:
- Reusability: Use in multiple programs
- Organization: Keep related functions together
- Namespace: Avoid function name conflicts
- Testing: Test module functions separately
Output Example:
Using module name:
Area: 78.54
Circumference: 31.42
Using direct import:
Area: 78.54
Circumference: 31.42
PI value: 3.1416
Mnemonic: "IRUD - Import, Reuse, Use, Debug"
Question 3(a) [3 marks]
Explain Types of errors in python.
Answer:
Python errors occur when code cannot execute properly. Understanding error types helps in debugging and writing robust programs.
Table: Python Error Types
| Error Type | Description | Example |
|---|---|---|
| Syntax Error | Code structure is wrong | Missing colon, brackets |
| Runtime Error | Error during execution | Division by zero |
| Logical Error | Code runs but wrong result | Wrong formula used |
Common Examples:
Python
Error Characteristics:
- Syntax: Detected before execution
- Runtime: Detected during execution
- Logical: Not detected automatically
Mnemonic: "SRL - Syntax, Runtime, Logical"
Question 3(b) [4 marks]
Explain the structure of try except.
Answer:
Try-except structure handles runtime errors gracefully, preventing program crashes and providing user-friendly error messages.
Basic Structure:
Syntax Structure:
Python
Table: Structure Components
| Block | Purpose | Required |
|---|---|---|
| try | Contains risky code | Yes |
| except | Handles specific errors | Yes |
| else | Runs if no error | No |
| finally | Always executes | No |
Example:
Python
Mnemonic: "TEEF - Try, Except, Else, Finally"
Question 3(c) [7 marks]
Develop a function for marks Result which contains two arguments English and Maths marks, if the value of any argument is less than 0 then raise an error.
Answer:
Custom error handling ensures data validation and provides meaningful feedback for invalid inputs.
Complete Implementation:
Python
Key Features:
- Custom Exception: InvalidMarksError for specific validation
- Multiple Validations: Negative, type, and range checks
- Comprehensive Results: Total, percentage, grade calculation
- User-Friendly: Interactive input with error handling
Error Handling Benefits:
- Data Integrity: Ensures valid input data
- User Experience: Clear error messages
- Program Stability: Prevents crashes
- Debugging: Easier to identify issues
Mnemonic: "CVIR - Custom, Validate, Interactive, Robust"
Question 3(a OR) [3 marks]
List any Five built-in exceptions in python.
Answer:
Built-in exceptions are predefined error types that Python raises when specific error conditions occur during program execution.
Table: Common Built-in Exceptions
| Exception | Cause | Example |
|---|---|---|
| ValueError | Invalid value for operation | int("abc") |
| TypeError | Wrong data type | "5" + 5 |
| IndexError | Index out of range | list[10] for 5-item list |
| KeyError | Dictionary key not found | dict["missing_key"] |
| ZeroDivisionError | Division by zero | 10 / 0 |
Code Examples:
Python
Additional Common Exceptions:
- FileNotFoundError: File doesn't exist
- AttributeError: Object has no attribute
- ImportError: Module cannot be imported
Mnemonic: "VTIKZ - ValueError, TypeError, IndexError, KeyError, ZeroDivisionError"
Question 3(b OR) [4 marks]
Write points on finally and explain with example.
Answer:
The finally block is a special block that always executes regardless of whether an exception occurs or not.
Table: Finally Block Characteristics
| Feature | Description |
|---|---|
| Always Executes | Runs even if exception occurs |
| Cleanup Code | Perfect for resource cleanup |
| After try/except | Executes after try and except blocks |
| Cannot Skip | Even return statements can't skip it |
Key Points:
- Guaranteed Execution: Runs in all scenarios
- Resource Management: Close files, database connections
- Cleanup Operations: Free memory, reset variables
- Even with Return: Executes before function returns
Example Program:
Python
Output Example:
=== Test 1: Valid file ===
Opening file...
Reading file content...
File content: Hello World
Finally block executing...
File closed successfully
Cleanup completed
=== Test 2: Non-existent file ===
Opening file...
Error: File not found
Finally block executing...
No file to close
Cleanup completed
Mnemonic: "ARGC - Always Runs, Resource Cleanup"
Question 3(c OR) [7 marks]
Write a program to catch on Divide by Zero Exception with finally clause.
Answer:
Divide by zero exception handling demonstrates proper error management with resource cleanup using finally clause.
Complete Program:
Python
Key Features:
- Comprehensive Error Handling: Multiple exception types
- Finally Clause: Always executes for cleanup
- Logging: Tracks operations and errors
- Interactive Mode: User-friendly interface
- Statistics: Operation success tracking
Mnemonic: "CFLIS - Comprehensive, Finally, Logging, Interactive, Statistics"
Question 4(a) [3 marks]
What is file Handling? List file Handling Operations.
Answer:
File Handling is the process of working with files stored on computer storage devices to read, write, and manipulate data.
Table: File Handling Operations
| Operation | Purpose | Method |
|---|---|---|
| Open | Access file for operations | open() |
| Read | Retrieve content from file | read(), readline() |
| Write | Add content to file | write(), writelines() |
| Close | Release file resources | close() |
| Seek | Move file pointer | seek() |
| Tell | Get current position | tell() |
Common Use Cases:
- Data Storage: Save program data permanently
- Configuration: Read settings from files
- Logging: Record program activities
- Import/Export: Exchange data with other programs
Basic Example:
Python
Mnemonic: "ORWCST - Open, Read, Write, Close, Seek, Tell"
Question 4(b) [4 marks]
Explain Object Serialization.
Answer:
Object Serialization is the process of converting Python objects into a format that can be stored in files or transmitted over networks.
Table: Serialization Methods
| Method | Module | Purpose | File Type |
|---|---|---|---|
| Pickle | pickle | Python objects | Binary |
| JSON | json | Web-compatible data | Text |
| CSV | csv | Tabular data | Text |
| XML | xml | Structured documents | Text |
Pickle Example:
Python
Benefits:
- Persistence: Store objects permanently
- Data Transfer: Send objects between programs
- Caching: Save processed results
- Backup: Create object snapshots
Limitations:
- Python Specific: Pickle works only with Python
- Security Risk: Don't load untrusted pickle files
- Version Compatibility: Different Python versions may have issues
Mnemonic: "SPDT - Store, Persist, Data Transfer"
Question 4(c) [7 marks]
Write a program to count all the vowels in the file.
Answer:
Vowel counting program demonstrates file reading and text processing with comprehensive error handling.
Complete Program:
Python
Program Features:
- File Validation: Checks file existence and permissions
- Error Handling: Comprehensive exception management
- Multiple Modes: File input, text input, batch processing
- Statistics: Individual and overall vowel counts
- Interactive Interface: User-friendly menu system
Output Example:
--- Processing file: sample.txt ---
File size: 245 characters
Total characters (letters only): 195
Total vowels found: 78
Vowel percentage: 40.00%
Individual vowel counts:
A: 15 (19.2%)
E: 20 (25.6%)
I: 12 (15.4%)
O: 18 (23.1%)
U: 13 (16.7%)
Mnemonic: "FVESI - File Validation, Vowel Extraction, Statistics, Interactive"
Question 4(a OR) [3 marks]
How to open and close file? Also give the syntax for same.
Answer:
File opening and closing are fundamental operations for file handling in Python with specific syntax and modes.
Table: File Opening Modes
| Mode | Purpose | Description |
|---|---|---|
| 'r' | Read | Read existing file (default) |
| 'w' | Write | Create new or overwrite existing |
| 'a' | Append | Add to end of existing file |
| 'r+' | Read/Write | Read and write existing file |
Syntax Examples:
Python
Best Practices:
- Always Close: Prevent resource leaks
- Use 'with': Automatic file closing
- Specify Mode: Be explicit about file mode
- Handle Errors: Use try-except for file operations
Mnemonic: "ORWA - Open, Read, Write, Append modes"
Question 4(b OR) [4 marks]
What is Differentiate between Text file and Binary file?
Answer:
Text and Binary files store data in different formats, requiring different handling approaches in Python programming.
Table: Text vs Binary Files Comparison
| Aspect | Text File | Binary File |
|---|---|---|
| Content | Human-readable characters | Machine-readable bytes |
| Mode | 'r', 'w', 'a' | 'rb', 'wb', 'ab' |
| Encoding | UTF-8, ASCII encoding | No encoding |
| Size | Larger due to encoding | Smaller, compact |
| Examples | .txt, .py, .html | .jpg, .exe, .pkl |
| Editing | Any text editor | Specialized software |
Code Examples:
Python
When to Use:
- Text Files: Configuration, logs, source code, documentation
- Binary Files: Images, videos, executables, serialized objects
Key Differences:
- Portability: Text files more portable across systems
- Efficiency: Binary files more space and time efficient
- Human Readable: Text files can be viewed directly
Mnemonic: "TCEB - Text Character Encoding Bigger, Binary Compact Efficient"
Question 4(c OR) [7 marks]
Write a program to create a binary file to store Seat no and Name. Search any Seat no and display name if Seat No. found otherwise "Seat no not found".
Answer:
Binary file program for student record management with search functionality using pickle serialization.
Complete Program:
Python
Program Features:
- Binary Storage: Uses pickle for efficient data storage
- Search Functionality: Quick seat number lookup
- Error Handling: Comprehensive input validation
- CRUD Operations: Create, Read, Update, Delete records
- Statistics: File and record information
- Interactive Menu: User-friendly interface
Sample Output:
Enter seat number to search: 102
Found: Seat 102 - Jane Smith
Enter seat number to search: 999
Seat no not found
Mnemonic: "BSECH - Binary Storage, Search Efficiently, CRUD Handling"
Question 5(a) [3 marks]
What is Turtle and how is it used to draw objects?
Answer:
Turtle is a Python graphics module that provides a virtual drawing canvas with a turtle cursor for creating graphics programmatically.
Table: Turtle Basics
| Component | Description | Purpose |
|---|---|---|
| Canvas | Drawing surface | Area where graphics appear |
| Turtle | Drawing cursor | Moves and draws lines |
| Pen | Drawing tool | Controls line appearance |
| Commands | Movement functions | Control turtle actions |
Basic Drawing Concept:
Python
Key Features:
- Visual Programming: See results immediately
- Educational: Great for learning programming concepts
- Interactive: Real-time drawing feedback
- Simple Syntax: Easy commands for complex graphics
Common Uses:
- Geometric Shapes: Squares, circles, polygons
- Patterns: Fractals, spirals, designs
- Educational Graphics: Teaching geometry and programming
Mnemonic: "CPTT - Canvas, Pen, Turtle, Teaching tool"
Question 5(b) [4 marks]
Explain Different ways to move turtle to another position.
Answer:
Turtle provides multiple movement methods for positioning and navigation on the drawing canvas.
Table: Turtle Movement Methods
| Method | Purpose | Pen State | Example |
|---|---|---|---|
| forward(distance) | Move forward | Draws line | forward(100) |
| backward(distance) | Move backward | Draws line | backward(50) |
| goto(x, y) | Move to coordinates | Draws line | goto(100, 50) |
| penup() | Lift pen | No drawing | penup() |
| pendown() | Lower pen | Draws line | pendown() |
| setx(x) | Set X coordinate | Draws line | setx(200) |
| sety(y) | Set Y coordinate | Draws line | sety(150) |
Movement Examples:
Python
Rotation Methods:
- right(angle): Turn clockwise
- left(angle): Turn counterclockwise
- setheading(angle): Set absolute direction
Position Control:
- Drawing Mode: Pen down, leaves trail
- Moving Mode: Pen up, no trail
- Coordinate System: Center (0,0), positive Y up
Mnemonic: "FGPRS - Forward, Goto, Penup, Rotate, Set coordinates"
Question 5(c) [7 marks]
Explain how loops can be useful in turtle and provide an example.
Answer:
Loops in turtle graphics enable creation of repetitive patterns, complex shapes, and efficient code for geometric designs.
Loop Benefits in Turtle:
Table: Loop Applications
| Loop Type | Use Case | Example Pattern |
|---|---|---|
| For Loop | Fixed repetitions | Regular polygons |
| While Loop | Conditional drawing | Spirals |
| Nested Loops | Complex patterns | Grids, fractals |
| Range Loop | Incremental changes | Color gradients |
Complete Example Program:
Python
Loop Advantages in Turtle:
Table: Loop Benefits
| Benefit | Description | Example |
|---|---|---|
| Code Efficiency | Less repetitive code | One loop vs 100 lines |
| Pattern Creation | Regular geometric patterns | Polygons, spirals |
| Dynamic Graphics | Variable-based drawing | Size/color changes |
| Complex Designs | Nested loop patterns | Flowers, fractals |
Key Programming Concepts:
- Iteration: Repeat drawing commands
- Variables: Control size, angle, color
- Nesting: Create complex multi-layer patterns
- Conditionals: Change behavior based on conditions
Mathematical Applications:
- Geometry: Regular polygons (360°/n sides)
- Trigonometry: Circular patterns using angles
- Fibonacci: Spiral patterns with mathematical ratios
- Fractals: Self-repeating patterns
Performance Tips:
- Speed Control: Use
pen.speed(0)for fastest drawing - Minimize Pen Movements: Group drawing operations
- Color Efficiency: Pre-define color lists
- Screen Updates: Use
screen.tracer(0)for complex patterns
Mnemonic: "LPDC - Loops, Patterns, Dynamic, Complex graphics"
Question 5(a OR) [3 marks]
Explain Shape function in Turtle. How many types of shapes are their in turtle?
Answer:
Turtle shape function changes the cursor appearance from default arrow to various predefined shapes for better visual representation.
Table: Built-in Turtle Shapes
| Shape Name | Description | Usage |
|---|---|---|
| "arrow" | Default arrow cursor | turtle.shape("arrow") |
| "turtle" | Turtle icon | turtle.shape("turtle") |
| "circle" | Circular cursor | turtle.shape("circle") |
| "square" | Square cursor | turtle.shape("square") |
| "triangle" | Triangle cursor | turtle.shape("triangle") |
| "classic" | Classic turtle shape | turtle.shape("classic") |
Shape Function Usage:
Python
Custom Shapes:
- Register New: Create custom polygon shapes
- Import Images: Use external image files
- Shape Coordinates: Define shape using coordinate points
Benefits:
- Visual Appeal: Better than default arrow
- Orientation: Shows turtle's direction clearly
- Thematic Design: Match shape to project theme
Mnemonic: "ATCSTC - Arrow, Turtle, Circle, Square, Triangle, Classic"
Question 5(b OR) [4 marks]
What are the various types of pen command in Turtle? Explain them.
Answer:
Pen commands control the drawing behavior and appearance of lines created by turtle movement.
Table: Pen Control Commands
| Command Category | Commands | Purpose |
|---|---|---|
| Pen State | penup(), pendown() | Control drawing |
| Pen Size | pensize(width) | Line thickness |
| Pen Color | pencolor(color) | Line color |
| Pen Speed | speed(value) | Drawing speed |
Detailed Pen Commands:
State Control:
Python
Appearance Control:
Python
Speed Control:
Python
Table: Speed Values
| Value | Speed | Description |
|---|---|---|
| 1 | Slowest | Step-by-step animation |
| 3 | Slow | Clear movement |
| 6 | Normal | Default speed |
| 10 | Fast | Quick drawing |
| 0 | Fastest | No animation delay |
Fill Commands:
Python
Example Program:
Python
Mnemonic: "SSCSF - State, Size, Color, Speed, Fill commands"
Question 5(c OR) [7 marks]
Write a program for draw an Indian Flag using Turtle.
Answer:
Indian Flag drawing program demonstrates turtle graphics with precise measurements, colors, and geometric construction.
Complete Indian Flag Program:
Python
Program Features:
- Accurate Proportions: 2:3 flag ratio as per specifications
- Proper Colors: Official saffron, white, green colors
- Ashoka Chakra: 24-spoke wheel with mathematical precision
- Flag Pole: Complete with base
- Educational Info: Color meanings and significance
- Interactive: User-friendly demonstration
Technical Concepts:
- Geometric Calculations: Mathematical spoke positioning
- Color Management: Hex color codes for accuracy
- Modular Design: Separate functions for each component
- Object-Oriented: Class-based organization
Mathematical Elements:
- Circle Geometry: Chakra radius calculations
- Trigonometry: Spoke angle calculations (360°/24 = 15°)
- Coordinate System: Precise positioning
- Proportional Scaling: Maintaining flag ratios
Mnemonic: "SWACP - Stripes, White-chakra, Accurate, Colors, Proportional"