Advanced Python Programming (4321602) - Winter 2024 Solution
Solution guide for Advanced Python Programming (4321602) Winter 2024 exam
Question 1(a) [3 marks]
Give the difference between Set and Dictionary in python.
Answer:
| Feature | Set | Dictionary |
|---|---|---|
| Data Storage | Stores unique elements only | Stores key-value pairs |
| Order | Unordered collection | Ordered (Python 3.7+) |
| Duplicates | No duplicates allowed | Keys must be unique |
| Access | Cannot access by index | Access values by keys |
| Syntax | {1, 2, 3} | {'key': 'value'} |
- Set: Collection of unique, unordered elements
- Dictionary: Collection of key-value pairs with unique keys
Mnemonic: "Sets are Unique, Dicts have Keys"
Question 1(b) [4 marks]
Explain List in Python with example.
Answer:
List is an ordered, mutable collection that can store different data types.
Table of List Operations:
| Operation | Syntax | Example |
|---|---|---|
| Create | list_name = [] | fruits = ['apple', 'banana'] |
| Access | list[index] | fruits[0] returns 'apple' |
| Add | append() | fruits.append('orange') |
| Remove | remove() | fruits.remove('apple') |
Python
- Ordered: Elements maintain their position
- Mutable: Can be modified after creation
- Flexible: Stores any data type
Mnemonic: "Lists are Ordered and Modifiable"
Question 1(c) [7 marks]
What is Tuple in Python? Write a Python program to swap two tuple values.
Answer:
Tuple is an ordered, immutable collection that stores multiple items.
Table of Tuple Features:
| Property | Description | Example |
|---|---|---|
| Immutable | Cannot change after creation | t = (1, 2, 3) |
| Ordered | Elements have defined order | Access by index |
| Duplicates | Allows duplicate values | (1, 1, 2) |
| Indexing | Access elements by position | t[0] |
Python
- Immutable: Cannot modify once created
- Ordered: Maintains element sequence
- Heterogeneous: Can store different data types
Mnemonic: "Tuples are Immutable and Ordered"
Question 1(c OR) [7 marks]
What is Dictionary in Python? Write a Python program to traverse a dictionary using loop.
Answer:
Dictionary is an unordered collection of key-value pairs with unique keys.
Table of Dictionary Methods:
| Method | Purpose | Example |
|---|---|---|
| keys() | Get all keys | dict.keys() |
| values() | Get all values | dict.values() |
| items() | Get key-value pairs | dict.items() |
| get() | Safe key access | dict.get('key') |
Python
- Key-Value storage: Each key maps to a value
- Unique keys: No duplicate keys allowed
- Fast lookup: O(1) average time complexity
Mnemonic: "Dicts map Keys to Values"
Question 2(a) [3 marks]
What is Package? List out advantages of using Package.
Answer:
Package is a directory containing multiple modules organized together.
Table of Package Advantages:
| Advantage | Description |
|---|---|
| Organization | Groups related modules together |
| Namespace | Avoids naming conflicts |
| Reusability | Code can be reused across projects |
| Maintainability | Easier to manage large codebases |
| Distribution | Easy to share and install |
- Modular structure: Better code organization
- Hierarchical namespace: Prevents name conflicts
- Code reuse: Promotes software reusability
Mnemonic: "Packages Organize Related Modules"
Question 2(b) [4 marks]
Explain any two package import method with example.
Answer:
Table of Import Methods:
| Method | Syntax | Usage |
|---|---|---|
| Normal Import | import package.module | Access with full path |
| From Import | from package import module | Direct module access |
| Specific Import | from package.module import function | Import specific items |
| Wildcard Import | from package import * | Import all modules |
Python
- Normal import: Requires full package path
- From import: Allows direct module access
- Specific function import: Import only needed functions
Mnemonic: "Import Normally or From Package"
Question 2(c) [7 marks]
Explain about intra-package reference with example.
Answer:
Intra-package reference allows modules within a package to import from each other.
Diagram of Package Structure:
goat
Table of Reference Types:
| Type | Syntax | Usage |
|---|---|---|
| Absolute | from mypackage.math_ops import basic | Full path from package root |
| Relative | from . import basic | Current package |
| Parent | from .. import utils | Parent package |
| Sibling | from ..utils import helpers | Sibling package |
Python
- Relative imports: Use dots (.) for current package
- Absolute imports: Full package path
- Package hierarchy: Navigate using dot notation
Mnemonic: "Dots Navigate Package Levels"
Question 2(a OR) [3 marks]
What is Module? List out advantages of using Module.
Answer:
Module is a Python file containing definitions, statements, and functions.
Table of Module Advantages:
| Advantage | Description |
|---|---|
| Code Reusability | Write once, use multiple times |
| Namespace | Separate namespace for functions |
| Organization | Better code structure |
| Maintainability | Easier to debug and update |
| Collaboration | Multiple developers can work |
- Reusable code: Functions can be imported anywhere
- Modular design: Break large programs into smaller parts
- Easy maintenance: Changes in one place affect all imports
Mnemonic: "Modules Make Code Reusable"
Question 2(b OR) [4 marks]
Explain any two module import method with example.
Answer:
Table of Module Import Methods:
| Method | Syntax | Access Pattern |
|---|---|---|
| Direct Import | import module_name | module_name.function() |
| From Import | from module_name import function | function() |
| Alias Import | import module_name as alias | alias.function() |
| Wildcard Import | from module_name import * | function() |
Python
- Direct import: Access with module name prefix
- From import: Direct function access without prefix
- Namespace control: Choose appropriate import method
Mnemonic: "Import Directly or From Module"
Question 2(c OR) [7 marks]
Write a program to define a module to find the area and circumference of a circle.
Answer:
Python
Table of Module Features:
| Feature | Implementation |
|---|---|
| Functions | area(), circumference() |
| Error Handling | Check for negative radius |
| Constants | PI value |
| Documentation | Function docstrings |
- Module creation: Save functions in .py file
- Import flexibility: Whole module or specific functions
- Code reuse: Use same functions in multiple programs
Mnemonic: "Modules Contain Reusable Functions"
Question 3(a) [3 marks]
Explain the types of error in Python.
Answer:
Table of Python Error Types:
| Error Type | Description | Example |
|---|---|---|
| Syntax Error | Wrong Python syntax | Missing colon : |
| Runtime Error | Occurs during execution | Division by zero |
| Logical Error | Wrong program logic | Incorrect algorithm |
| Name Error | Undefined variable | Using undeclared variable |
| Type Error | Wrong data type operation | String + Integer |
- Syntax errors: Detected before program runs
- Runtime errors: Occur during program execution
- Logical errors: Program runs but gives wrong results
Mnemonic: "Syntax, Runtime, Logic Errors"
Question 3(b) [4 marks]
Explain user-defined exception using raise statement with example.
Answer:
User-defined exceptions are custom error classes created by programmers.
Table of Exception Components:
| Component | Purpose | Example |
|---|---|---|
| Class Definition | Create custom exception | class CustomError(Exception): |
| Raise Statement | Trigger the exception | raise CustomError("message") |
| Error Message | Describe the problem | Informative text |
| Exception Handling | Catch custom exception | except CustomError: |
Python
- Custom exception class: Inherits from Exception
- Raise statement: Manually trigger exceptions
- Meaningful messages: Help debug problems
Mnemonic: "Raise Custom Exceptions for Validation"
Question 3(c) [7 marks]
Explain try-except-finally clause with example.
Answer:
Try-except-finally provides complete exception handling mechanism.
Table of Exception Handling Blocks:
| Block | Purpose | Execution |
|---|---|---|
| try | Code that might raise exception | Always executed first |
| except | Handle specific exceptions | Only if exception occurs |
| else | Code when no exception | Only if no exception |
| finally | Cleanup code | Always executed |
Python
Flow Diagram:
- try: Contains risky code
- except: Handles specific errors
- finally: Always executes for cleanup
Mnemonic: "Try-Except-Finally Always Cleans"
Question 3(a OR) [3 marks]
What is built-in exception? List out any two with their meaning.
Answer:
Built-in exceptions are predefined error types in Python.
Table of Built-in Exceptions:
| Exception | Meaning | Example |
|---|---|---|
| ValueError | Invalid value for correct type | int("abc") |
| TypeError | Wrong data type operation | "5" + 5 |
| IndexError | List index out of range | list[10] for 5-item list |
| KeyError | Dictionary key not found | dict["missing_key"] |
| ZeroDivisionError | Division by zero | 10 / 0 |
Two Main Built-in Exceptions:
- ValueError: Occurs when function receives correct type but invalid value
- TypeError: Occurs when operation performed on inappropriate data type
Mnemonic: "Built-in Exceptions Handle Common Errors"
Question 3(b OR) [4 marks]
Explain try-except clause with example.
Answer:
Try-except handles exceptions that might occur during program execution.
Table of Exception Handling:
| Component | Purpose | Syntax |
|---|---|---|
| try | Code that might fail | try: |
| except | Handle specific exception | except ErrorType: |
| Multiple except | Handle different errors | Multiple except blocks |
| General except | Catch any exception | except: |
Python
- try block: Contains potentially risky code
- except block: Handles specific exception types
- Multiple handlers: Different exceptions handled differently
Mnemonic: "Try Risky Code, Except Handles Errors"
Question 3(c OR) [7 marks]
Write a program to catch on Divide by zero Exception with finally clause.
Answer:
Python
Table of Exception Handling Features:
| Feature | Implementation |
|---|---|
| ZeroDivisionError | Specific handling for division by zero |
| ValueError | Handle invalid input types |
| Generic Exception | Catch unexpected errors |
| Finally Block | Always execute cleanup code |
Exception Handling Flow:
- Specific exception handling: ZeroDivisionError caught separately
- Finally clause: Always executes for cleanup
- Resource management: Proper cleanup regardless of errors
Mnemonic: "Finally Always Cleans Up Resources"
Question 4(a) [3 marks]
Define: File, Binary File, Text File
Answer:
Table of File Definitions:
| Term | Definition | Example |
|---|---|---|
| File | Named storage location on disk | document.txt, image.jpg |
| Binary File | Contains non-text data in binary format | .exe, .jpg, .mp3, .pdf |
| Text File | Contains human-readable text characters | .txt, .py, .html, .csv |
Detailed Definitions:
- File: A collection of data stored on storage device with a unique name
- Binary File: Stores data in binary format (0s and 1s), not human-readable
- Text File: Contains ASCII or Unicode characters, human-readable format
Mnemonic: "Files store data, Binary=Machine, Text=Human"
Question 4(b) [4 marks]
Explain write() and writelines() function with example.
Answer:
Table of Write Functions:
| Function | Purpose | Parameter | Usage |
|---|---|---|---|
| write() | Write single string | String | file.write("Hello") |
| writelines() | Write list of strings | List/Sequence | file.writelines(["line1", "line2"]) |
Python
Key Differences:
- write(): Writes one string at a time
- writelines(): Writes multiple strings from a sequence
- Newlines: Must be added manually with
\n - Return value: Both return number of characters written
Mnemonic: "write() Single, writelines() Multiple"
Question 4(c) [7 marks]
Explain tell() and seek() function with example.
Answer:
File pointer functions control position within a file for reading/writing.
Table of Position Functions:
| Function | Purpose | Return/Parameter | Usage |
|---|---|---|---|
| tell() | Get current position | Returns current byte position | pos = file.tell() |
| seek(offset, whence) | Move to specific position | offset: bytes, whence: reference | file.seek(10, 0) |
Seek Whence Values:
| Value | Reference Point | Description |
|---|---|---|
| 0 | Beginning of file | Absolute positioning |
| 1 | Current position | Relative to current |
| 2 | End of file | Relative to end |
Python
Position Control Diagram:
- tell(): Returns current byte position in file
- seek(): Moves file pointer to specified position
- Positioning: Essential for random file access
- Binary mode: Works with byte positions
Mnemonic: "tell() Position, seek() Movement"
Question 4(a OR) [3 marks]
What is Absolute and Relative file path?
Answer:
Table of Path Types:
| Path Type | Description | Example |
|---|---|---|
| Absolute Path | Complete path from root directory | /home/user/documents/file.txt |
| Relative Path | Path relative to current directory | ../documents/file.txt |
Path Symbols:
| Symbol | Meaning | Example |
|---|---|---|
| / | Root directory (Linux/Mac) | /home/user/ |
| C:\ | Drive letter (Windows) | C:\\Users\\Documents\\ |
| . | Current directory | ./file.txt |
| .. | Parent directory | ../folder/file.txt |
- Absolute: Complete path from system root
- Relative: Path from current working directory
Mnemonic: "Absolute from Root, Relative from Current"
Question 4(b OR) [4 marks]
Explain about various mode to open binary and text file.
Answer:
Table of File Opening Modes:
| Mode | Type | Purpose | File Pointer |
|---|---|---|---|
| 'r' | Text | Read only | Beginning |
| 'w' | Text | Write (overwrites) | Beginning |
| 'a' | Text | Append | End |
| 'rb' | Binary | Read binary | Beginning |
| 'wb' | Binary | Write binary | Beginning |
| 'ab' | Binary | Append binary | End |
| 'r+' | Text | Read and write | Beginning |
| 'w+' | Text | Write and read | Beginning |
Python
- Text modes: Handle string data with encoding
- Binary modes: Handle raw bytes without encoding
- Plus modes: Allow both reading and writing
Mnemonic: "Text for Strings, Binary for Bytes"
Question 4(c OR) [7 marks]
Write a Python program to write student's subject record like branch name, semester, subject code and subject name in the binary file.
Answer:
Python
Table of Binary File Operations:
| Operation | Method | Purpose |
|---|---|---|
| Write | pickle.dump() | Serialize objects to binary |
| Read | pickle.load() | Deserialize objects from binary |
| Append | Read + Add + Write | Add new records |
| Search | Filter loaded data | Find specific records |
Binary File Structure:
- Binary storage: Uses pickle for object serialization
- Efficient storage: Compact binary format
- Object preservation: Maintains data structure integrity
- Cross-platform: Works on different operating systems
Mnemonic: "Pickle Preserves Python Objects"
Question 5(a) [3 marks]
Define: GUI, CLI
Answer:
Table of Interface Definitions:
| Term | Full Form | Description | Example |
|---|---|---|---|
| GUI | Graphical User Interface | Visual interface with windows, buttons, icons | Windows, Mac desktop |
| CLI | Command Line Interface | Text-based interface using commands | Terminal, Command Prompt |
Key Differences:
- GUI: User-friendly, mouse-driven, visual elements
- CLI: Text-based, keyboard-driven, command syntax
- Interaction: GUI uses clicks, CLI uses typed commands
Mnemonic: "GUI Graphics, CLI Commands"
Question 5(b) [4 marks]
Write a Python program to draw square shape using for and while loop using Turtle.
Answer:
Python
Table of Loop Comparison:
| Loop Type | Structure | Usage | Control |
|---|---|---|---|
| for loop | for i in range(4): | Known iterations | Counter-based |
| while loop | while condition: | Conditional iterations | Condition-based |
- for loop: Best for known number of iterations
- while loop: Best for condition-based repetition
- Both achieve: Same square drawing result
Mnemonic: "For Count, While Condition"
Question 5(c) [7 marks]
Write a Python program to draw a chessboard using Turtle.
Answer:
Python
Table of Chessboard Components:
| Component | Implementation | Purpose |
|---|---|---|
| Squares | 8x8 grid alternating colors | Main board pattern |
| Colors | Black and white alternating | Traditional chess pattern |
| Border | Brown rectangle outline | Frame the board |
| Labels | A-H columns, 1-8 rows | Chess notation |
| Pieces | Unicode chess symbols | Sample piece placement |
Chessboard Pattern Logic:
- Alternating pattern: (row + col) % 2 determines color
- Grid system: 8x8 squares with precise positioning
- Visual enhancements: Border, labels, and sample pieces
- Scalable design: Easy to modify square size
Mnemonic: "Alternate Colors in Grid Pattern"
Question 5(a OR) [3 marks]
How many types of shapes in turtle? Explain any one shape with suitable example.
Answer:
Table of Turtle Shapes:
| Shape Type | Examples | Method |
|---|---|---|
| Basic Shapes | Circle, Square, Triangle | Built-in functions |
| Line Patterns | Straight lines, Curves | forward(), backward() |
| Polygons | Pentagon, Hexagon, Octagon | Loop with angles |
| Complex Shapes | Stars, Spirals, Fractals | Mathematical patterns |
| Custom Shapes | User-defined patterns | Combination of moves |
Circle Shape Example:
Python
- Built-in shapes: Circle, square, triangle readily available
- Custom shapes: Created using movement combinations
- Mathematical shapes: Use geometry for precise drawing
Mnemonic: "Turtle Draws Many Shape Types"
Question 5(b OR) [4 marks]
Explain about four basic methods of Turtle module.
Answer:
Table of Basic Turtle Methods:
| Method | Purpose | Parameters | Example |
|---|---|---|---|
| forward(distance) | Move turtle forward | distance in pixels | turtle.forward(100) |
| backward(distance) | Move turtle backward | distance in pixels | turtle.backward(50) |
| right(angle) | Turn turtle right | angle in degrees | turtle.right(90) |
| left(angle) | Turn turtle left | angle in degrees | turtle.left(45) |
Python
- Movement methods: forward() and backward() for distance
- Rotation methods: right() and left() for direction changes
- Coordinate system: Based on current turtle position and heading
- Angle measurement: Degrees (0-360)
Mnemonic: "Forward, Backward, Right, Left Basics"
Question 5(c OR) [7 marks]
Write a Python program to draw square, rectangle, and circle using Turtle.
Answer:
Python
Table of Shape Characteristics:
| Shape | Sides | Properties | Area Formula |
|---|---|---|---|
| Square | 4 equal | All angles 90° | side² |
| Rectangle | 4 (2 pairs) | Opposite sides equal | length × width |
| Circle | 0 (curved) | All points equidistant | π × radius² |
Shape Drawing Process:
- Geometric accuracy: Precise angle and distance measurements
- Visual appeal: Different colors and filled shapes
- Educational value: Shows formulas
- Mathematical calculations: Area formulas included
- Interactive features: User can customize parameters
Mnemonic: "Square Equal, Rectangle Opposite, Circle Round"