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

FeatureDescription
OrderedElements have a defined order
MutableCan be changed after creation
IndexedAccess elements using index [0,1,2...]
DuplicatesAllows 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

FunctionPurposeExample
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

OperationMethodSyntaxExample
Addadd()set.add(element)s.add(5)
Removeremove()set.remove(element)s.remove(3)
Remove Safediscard()set.discard(element)s.discard(7)
Poppop()set.pop()s.pop()

Code Example:

Python

POP vs REMOVE Differences:

Aspectpop()remove()
TargetRandom elementSpecific element
ParameterNo parameter neededRequires element value
ReturnReturns removed elementReturns None
ErrorError if set is emptyError 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

FunctionPurposeReturns
keys()Get all keysdict_keys object
values()Get all valuesdict_values object
items()Get key-value pairsdict_items object
get()Safe value retrievalValue or None
pop()Remove and return valueRemoved value
clear()Remove all itemsNone
update()Merge dictionariesNone

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

MethodSyntaxExample
Parentheses(item1, item2)(1, 2, 3)
Without Parenthesesitem1, item21, 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

AdvantageDescriptionBenefit
ReusabilityUse same code multiple timesSaves development time
OrganizationSeparate code into logical unitsBetter code structure
NamespaceAvoid naming conflictsCleaner code
MaintainabilityUpdate code in one placeEasy 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

FeatureTupleList
MutabilityImmutable (cannot change)Mutable (can change)
Syntax(1, 2, 3)[1, 2, 3]
PerformanceFasterSlower
MethodsLimited methodsMany methods available
Use CaseFixed dataDynamic data
MemoryLess memoryMore 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

TypeSyntaxUsage
Absolutefrom package.module import functionFull path from root
Relativefrom .module import functionWithin same package
Parentfrom ..module import functionParent 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 TypeDescriptionExample
Syntax ErrorCode structure is wrongMissing colon, brackets
Runtime ErrorError during executionDivision by zero
Logical ErrorCode runs but wrong resultWrong 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

BlockPurposeRequired
tryContains risky codeYes
exceptHandles specific errorsYes
elseRuns if no errorNo
finallyAlways executesNo

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

ExceptionCauseExample
ValueErrorInvalid value for operationint("abc")
TypeErrorWrong data type"5" + 5
IndexErrorIndex out of rangelist[10] for 5-item list
KeyErrorDictionary key not founddict["missing_key"]
ZeroDivisionErrorDivision by zero10 / 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

FeatureDescription
Always ExecutesRuns even if exception occurs
Cleanup CodePerfect for resource cleanup
After try/exceptExecutes after try and except blocks
Cannot SkipEven 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

OperationPurposeMethod
OpenAccess file for operationsopen()
ReadRetrieve content from fileread(), readline()
WriteAdd content to filewrite(), writelines()
CloseRelease file resourcesclose()
SeekMove file pointerseek()
TellGet current positiontell()

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

MethodModulePurposeFile Type
PicklepicklePython objectsBinary
JSONjsonWeb-compatible dataText
CSVcsvTabular dataText
XMLxmlStructured documentsText

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

ModePurposeDescription
'r'ReadRead existing file (default)
'w'WriteCreate new or overwrite existing
'a'AppendAdd to end of existing file
'r+'Read/WriteRead 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

AspectText FileBinary File
ContentHuman-readable charactersMachine-readable bytes
Mode'r', 'w', 'a''rb', 'wb', 'ab'
EncodingUTF-8, ASCII encodingNo encoding
SizeLarger due to encodingSmaller, compact
Examples.txt, .py, .html.jpg, .exe, .pkl
EditingAny text editorSpecialized 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

ComponentDescriptionPurpose
CanvasDrawing surfaceArea where graphics appear
TurtleDrawing cursorMoves and draws lines
PenDrawing toolControls line appearance
CommandsMovement functionsControl 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

MethodPurposePen StateExample
forward(distance)Move forwardDraws lineforward(100)
backward(distance)Move backwardDraws linebackward(50)
goto(x, y)Move to coordinatesDraws linegoto(100, 50)
penup()Lift penNo drawingpenup()
pendown()Lower penDraws linependown()
setx(x)Set X coordinateDraws linesetx(200)
sety(y)Set Y coordinateDraws linesety(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 TypeUse CaseExample Pattern
For LoopFixed repetitionsRegular polygons
While LoopConditional drawingSpirals
Nested LoopsComplex patternsGrids, fractals
Range LoopIncremental changesColor gradients

Complete Example Program:

Python

Loop Advantages in Turtle:

Table: Loop Benefits

BenefitDescriptionExample
Code EfficiencyLess repetitive codeOne loop vs 100 lines
Pattern CreationRegular geometric patternsPolygons, spirals
Dynamic GraphicsVariable-based drawingSize/color changes
Complex DesignsNested loop patternsFlowers, 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 NameDescriptionUsage
"arrow"Default arrow cursorturtle.shape("arrow")
"turtle"Turtle iconturtle.shape("turtle")
"circle"Circular cursorturtle.shape("circle")
"square"Square cursorturtle.shape("square")
"triangle"Triangle cursorturtle.shape("triangle")
"classic"Classic turtle shapeturtle.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 CategoryCommandsPurpose
Pen Statepenup(), pendown()Control drawing
Pen Sizepensize(width)Line thickness
Pen Colorpencolor(color)Line color
Pen Speedspeed(value)Drawing speed

Detailed Pen Commands:

State Control:

Python

Appearance Control:

Python

Speed Control:

Python

Table: Speed Values

ValueSpeedDescription
1SlowestStep-by-step animation
3SlowClear movement
6NormalDefault speed
10FastQuick drawing
0FastestNo 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"