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:

FeatureSetDictionary
Data StorageStores unique elements onlyStores key-value pairs
OrderUnordered collectionOrdered (Python 3.7+)
DuplicatesNo duplicates allowedKeys must be unique
AccessCannot access by indexAccess 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:

OperationSyntaxExample
Createlist_name = []fruits = ['apple', 'banana']
Accesslist[index]fruits[0] returns 'apple'
Addappend()fruits.append('orange')
Removeremove()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:

PropertyDescriptionExample
ImmutableCannot change after creationt = (1, 2, 3)
OrderedElements have defined orderAccess by index
DuplicatesAllows duplicate values(1, 1, 2)
IndexingAccess elements by positiont[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:

MethodPurposeExample
keys()Get all keysdict.keys()
values()Get all valuesdict.values()
items()Get key-value pairsdict.items()
get()Safe key accessdict.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:

AdvantageDescription
OrganizationGroups related modules together
NamespaceAvoids naming conflicts
ReusabilityCode can be reused across projects
MaintainabilityEasier to manage large codebases
DistributionEasy 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:

MethodSyntaxUsage
Normal Importimport package.moduleAccess with full path
From Importfrom package import moduleDirect module access
Specific Importfrom package.module import functionImport specific items
Wildcard Importfrom 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:

TypeSyntaxUsage
Absolutefrom mypackage.math_ops import basicFull path from package root
Relativefrom . import basicCurrent package
Parentfrom .. import utilsParent package
Siblingfrom ..utils import helpersSibling 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:

AdvantageDescription
Code ReusabilityWrite once, use multiple times
NamespaceSeparate namespace for functions
OrganizationBetter code structure
MaintainabilityEasier to debug and update
CollaborationMultiple 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:

MethodSyntaxAccess Pattern
Direct Importimport module_namemodule_name.function()
From Importfrom module_name import functionfunction()
Alias Importimport module_name as aliasalias.function()
Wildcard Importfrom 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:

FeatureImplementation
Functionsarea(), circumference()
Error HandlingCheck for negative radius
ConstantsPI value
DocumentationFunction 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 TypeDescriptionExample
Syntax ErrorWrong Python syntaxMissing colon :
Runtime ErrorOccurs during executionDivision by zero
Logical ErrorWrong program logicIncorrect algorithm
Name ErrorUndefined variableUsing undeclared variable
Type ErrorWrong data type operationString + 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:

ComponentPurposeExample
Class DefinitionCreate custom exceptionclass CustomError(Exception):
Raise StatementTrigger the exceptionraise CustomError("message")
Error MessageDescribe the problemInformative text
Exception HandlingCatch custom exceptionexcept 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:

BlockPurposeExecution
tryCode that might raise exceptionAlways executed first
exceptHandle specific exceptionsOnly if exception occurs
elseCode when no exceptionOnly if no exception
finallyCleanup codeAlways 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:

ExceptionMeaningExample
ValueErrorInvalid value for correct typeint("abc")
TypeErrorWrong data type operation"5" + 5
IndexErrorList index out of rangelist[10] for 5-item list
KeyErrorDictionary key not founddict["missing_key"]
ZeroDivisionErrorDivision by zero10 / 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:

ComponentPurposeSyntax
tryCode that might failtry:
exceptHandle specific exceptionexcept ErrorType:
Multiple exceptHandle different errorsMultiple except blocks
General exceptCatch any exceptionexcept:
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:

FeatureImplementation
ZeroDivisionErrorSpecific handling for division by zero
ValueErrorHandle invalid input types
Generic ExceptionCatch unexpected errors
Finally BlockAlways 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:

TermDefinitionExample
FileNamed storage location on diskdocument.txt, image.jpg
Binary FileContains non-text data in binary format.exe, .jpg, .mp3, .pdf
Text FileContains 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:

FunctionPurposeParameterUsage
write()Write single stringStringfile.write("Hello")
writelines()Write list of stringsList/Sequencefile.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:

FunctionPurposeReturn/ParameterUsage
tell()Get current positionReturns current byte positionpos = file.tell()
seek(offset, whence)Move to specific positionoffset: bytes, whence: referencefile.seek(10, 0)

Seek Whence Values:

ValueReference PointDescription
0Beginning of fileAbsolute positioning
1Current positionRelative to current
2End of fileRelative 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 TypeDescriptionExample
Absolute PathComplete path from root directory/home/user/documents/file.txt
Relative PathPath relative to current directory../documents/file.txt

Path Symbols:

SymbolMeaningExample
/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:

ModeTypePurposeFile Pointer
'r'TextRead onlyBeginning
'w'TextWrite (overwrites)Beginning
'a'TextAppendEnd
'rb'BinaryRead binaryBeginning
'wb'BinaryWrite binaryBeginning
'ab'BinaryAppend binaryEnd
'r+'TextRead and writeBeginning
'w+'TextWrite and readBeginning
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:

OperationMethodPurpose
Writepickle.dump()Serialize objects to binary
Readpickle.load()Deserialize objects from binary
AppendRead + Add + WriteAdd new records
SearchFilter loaded dataFind 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:

TermFull FormDescriptionExample
GUIGraphical User InterfaceVisual interface with windows, buttons, iconsWindows, Mac desktop
CLICommand Line InterfaceText-based interface using commandsTerminal, 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 TypeStructureUsageControl
for loopfor i in range(4):Known iterationsCounter-based
while loopwhile condition:Conditional iterationsCondition-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:

ComponentImplementationPurpose
Squares8x8 grid alternating colorsMain board pattern
ColorsBlack and white alternatingTraditional chess pattern
BorderBrown rectangle outlineFrame the board
LabelsA-H columns, 1-8 rowsChess notation
PiecesUnicode chess symbolsSample 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 TypeExamplesMethod
Basic ShapesCircle, Square, TriangleBuilt-in functions
Line PatternsStraight lines, Curvesforward(), backward()
PolygonsPentagon, Hexagon, OctagonLoop with angles
Complex ShapesStars, Spirals, FractalsMathematical patterns
Custom ShapesUser-defined patternsCombination 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:

MethodPurposeParametersExample
forward(distance)Move turtle forwarddistance in pixelsturtle.forward(100)
backward(distance)Move turtle backwarddistance in pixelsturtle.backward(50)
right(angle)Turn turtle rightangle in degreesturtle.right(90)
left(angle)Turn turtle leftangle in degreesturtle.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:

ShapeSidesPropertiesArea Formula
Square4 equalAll angles 90°side²
Rectangle4 (2 pairs)Opposite sides equallength × width
Circle0 (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"