Advanced Python Programming (4321602) - Winter 2023 Solution

Solution guide for Advanced Python Programming (4321602) Winter 2023 exam

Question 1(a) [3 marks]

What is Dictionary? Explain with example.

Answer:

Dictionary એ Python માં key-value pairs નો collection છે જે mutable અને ordered હોય છે.

Table: Dictionary Properties

PropertyDescription
MutableValues ને change કરી શકાય છે
OrderedPython 3.7+ માં insertion order maintain રહે છે
IndexedKeys દ્વારા access કરાય છે
No DuplicatesDuplicate keys allow નથી
Python
  • Key-Value Structure: દરેક element માં key અને value હોય છે
  • Fast Access: O(1) time complexity માં data access
  • Dynamic Size: Runtime માં size વધારી-ઘટાડી શકાય છે

Mnemonic: "Dictionary = Key Value Treasure"


Question 1(b) [4 marks]

Explain Tuple Built-in functions and methods.

Answer:

Tuple માં limited built-in methods છે કારણ કે તે immutable છે.

Table: Tuple Methods

MethodDescriptionExample
count()Element ની frequency return કરે છેt.count(5)
index()Element નું first index return કરે છેt.index('a')
len()Tuple નું length return કરે છેlen(t)
max()Maximum value return કરે છેmax(t)
min()Minimum value return કરે છેmin(t)
Python
  • Immutable Nature: Methods tuple ને modify નથી કરતા
  • Return Values: બધા methods નવી values return કરે છે
  • Type Conversion: tuple() function થી list ને tuple માં convert કરી શકાય

Mnemonic: "Count Index Length Max Min"


Question 1(c) [7 marks]

Write a python program to demonstrate set operations.

Answer:

Set operations mathematics ના set theory પર આધારિત છે.

Table: Set Operations

OperationSymbolMethodDescription
Union|union()બન્ને sets ના elements
Intersection&intersection()Common elements
Difference-difference()First set માંથી second ને minus
Symmetric Difference^symmetric_difference()Unique elements only
Python
  • Mathematical Operations: Set theory ના operations implement કરે છે
  • Efficient Processing: Duplicate elements automatically remove થાય છે
  • Boolean Results: Subset/superset operations boolean return કરે છે

Mnemonic: "Union Intersection Difference Symmetric"


Question 1(c OR) [7 marks]

Write a python program to demonstrate the dictionaries functions and operations.

Answer:

Dictionary operations data manipulation માટે powerful tools પ્રદાન કરે છે.

Table: Dictionary Methods

MethodDescriptionExample
keys()બધી keys return કરે છેdict.keys()
values()બધા values return કરે છેdict.values()
items()Key-value pairs return કરે છેdict.items()
get()Safe value retrievaldict.get('key')
update()Dictionary merge કરે છેdict.update()
Python
  • Dynamic Operations: Runtime માં keys અને values add/remove કરી શકાય
  • Safe Access: get() method KeyError prevent કરે છે
  • Iteration Support: keys(), values(), items() methods loop માટે useful

Mnemonic: "Get Keys Values Items Update Pop"


Question 2(a) [3 marks]

Distinguish between Tuple and List in Python.

Answer:

Table: Tuple vs List Comparison

FeatureTupleList
MutabilityImmutable (cannot change)Mutable (can change)
SyntaxParentheses ()Square brackets []
PerformanceFasterSlower
MemoryLess memoryMore memory
MethodsLimited (count, index)Many methods available
Use CaseFixed dataDynamic data
  • Immutable Nature: Tuple એકવાર create થયા પછી change થઈ શકતું નથી
  • Performance: Tuple operations list કરતાં fast છે
  • Memory Efficient: Tuple ઓછી memory વાપરે છે

Mnemonic: "Tuple Tight, List Light"


Question 2(b) [4 marks]

What is the dir() function in python? Explain with example.

Answer:

dir() function એ built-in function છે જે object ના attributes અને methods ની list return કરે છે.

Table: dir() Function Features

FeatureDescription
Object InspectionObject ના attributes show કરે છે
Method DiscoveryAvailable methods list કરે છે
Namespace ExplorationCurrent namespace ના variables show કરે છે
Module AnalysisModule ના contents explore કરે છે
Python
  • Interactive Development: Objects ના capabilities જાણવા માટે useful
  • Debugging Tool: Available methods quickly identify કરવા માટે
  • Learning Aid: New libraries explore કરવા માટે helpful

Mnemonic: "Dir = Directory of Methods"


Question 2(c) [7 marks]

Write a program to define a module to find the area and circumference of a circle. Import module to another program.

Answer:

Module approach code reusability અને organization improve કરે છે.

Diagram: Module Structure

goat

File 1: circle.py (Module)

Python

File 2: main.py (Main Program)

Python
  • Modular Design: Functions ને separate file માં organize કરે છે
  • Reusability: Module ને multiple programs માં use કરી શકાય
  • Namespace Management: Module prefix થી function access કરાય છે

Mnemonic: "Import Calculate Display"


Question 2(a OR) [3 marks]

Explain Nested Tuple with example.

Answer:

Nested Tuple એ tuple અંદર બીજા tuples હોય છે, જે hierarchical data structure બનાવે છે.

Table: Nested Tuple Features

FeatureDescription
Multi-dimensional2D અથવા 3D data structure
Immutableબધા levels પર immutable
IndexingMultiple square brackets વાપરીને access
HeterogeneousDifferent data types store કરી શકાય
Python
  • Data Organization: Related data ને group કરવા માટે useful
  • Immutable Structure: એકવાર create થયા પછી structure change થઈ શકતું નથી
  • Efficient Access: Index-based fast access

Mnemonic: "Nested = Tuple Inside Tuple"


Question 2(b OR) [4 marks]

What is PIP? Write the syntax to install and uninstall python packages.

Answer:

PIP (Pip Installs Packages) એ Python package installer છે જે PyPI થી packages download અને install કરે છે.

Table: PIP Commands

CommandSyntaxDescription
Installpip install package_namePackage install કરે છે
Uninstallpip uninstall package_namePackage remove કરે છે
Listpip listInstalled packages show કરે છે
Showpip show package_namePackage info display કરે છે
Upgradepip install --upgrade package_namePackage update કરે છે
Python
  • Package Management: Third-party libraries easily manage કરી શકાય
  • Version Control: Specific versions install કરી શકાય
  • Dependency Resolution: Required dependencies automatically install થાય

Mnemonic: "PIP = Package Install Python"


Question 2(c OR) [7 marks]

Explain different ways of importing package. How are modules and packages connected to each other?

Answer:

Python માં imports ના વિવિધ ways છે જે code organization અને namespace management માટે important છે.

Diagram: Package Structure

goat

Table: Import Methods

MethodSyntaxUsage
Basic Importimport moduleFull module name required
From Importfrom module import functionDirect function access
Alias Importimport module as aliasShort name for module
Star Importfrom module import *Import all functions
Package Importfrom package import moduleImport from package
Python

Module-Package Connection:

  • Modules: Single .py files containing Python code
  • Packages: Directories containing multiple modules with __init__.py
  • Namespace: Packages create hierarchical namespace structure
  • init.py: Makes directory a package and controls imports

Mnemonic: "Import From As Star Package"


Question 3(a) [3 marks]

Describe Runtime Error and Syntax Error. Explain with example.

Answer:

Table: Error Types Comparison

Error TypeWhen OccursDetectionExample
Syntax ErrorCode parsing timeBefore executionMissing colon, brackets
Runtime ErrorDuring executionWhile runningDivision by zero, file not found
Logic ErrorAlwaysAfter executionWrong calculation logic
Python
  • Syntax Errors: Code run થવા પહેલા જ detect થાય છે
  • Runtime Errors: Program execution દરમિયાન થાય છે
  • Prevention: Exception handling runtime errors ને handle કરે છે

Mnemonic: "Syntax Before, Runtime During"


Question 3(b) [4 marks]

What is Exception handling in Python? Explain with example.

Answer:

Exception handling એ mechanism છે જે runtime errors ને gracefully handle કરે છે અને program crash થવાથી prevent કરે છે.

Table: Exception Handling Keywords

KeywordPurposeDescription
tryException માં થઈ શકે એવો codeRisk code block
exceptException handle કરવા માટેError handling block
finallyહંમેશા execute થાયCleanup code
elseException ન આવે તોSuccess code block
raiseManual exception raise કરવાCustom error throwing
Python
  • Error Prevention: Program crash થવાથી prevent કરે છે
  • Graceful Handling: User-friendly error messages provide કરે છે
  • Resource Management: finally block માં cleanup operations

Mnemonic: "Try Except Finally Else Raise"


Question 3(c) [7 marks]

Create a function for division of two numbers, if the value of any argument is non-integer then raise the error or if second argument is 0 then raise the error.

Answer:

Custom exception handling function બનાવવું validation અને error control માટે important છે.

Diagram: Function Flow

Python
  • Input Validation: Arguments ના type અને value check કરે છે
  • Custom Errors: Specific exceptions raise કરે છે
  • Error Messages: Clear અને descriptive error messages

Mnemonic: "Validate Type, Check Zero, Divide Safe"


Question 3(a OR) [3 marks]

Describe any five built-in exceptions in Python.

Answer:

Table: Built-in Exceptions

ExceptionCauseExample
ValueErrorInvalid value for operationint("abc")
TypeErrorWrong data type"hello" + 5
IndexErrorIndex out of rangelist[10] when list has 5 elements
KeyErrorDictionary key not founddict["nonexistent"]
FileNotFoundErrorFile does not existopen("missing.txt")
Python
  • Automatic Detection: Python automatically raises these exceptions
  • Specific Handling: દરેક exception નો specific purpose છે
  • Inheritance: બધા exceptions BaseException class થી inherit થાય છે

Mnemonic: "Value Type Index Key File"


Question 3(b OR) [4 marks]

Explain try, except and finally terms with syntax.

Answer:

Exception handling ના blocks નો specific purpose અને execution order છે.

Table: Exception Handling Blocks

BlockPurposeExecutionMandatory
tryRisky codeFirstYes
exceptError handlingIf exception occursAt least one
elseSuccess codeIf no exceptionNo
finallyCleanup codeAlwaysNo

Syntax Structure:

Python

Practical Example:

Python
  • Exception Flow: try → except/else → finally
  • Multiple Handlers: Multiple except blocks allowed
  • Guaranteed Execution: finally block હંમેશા run થાય છે

Mnemonic: "Try Exception Else Finally"


Question 3(c OR) [7 marks]

Write a user defined exception that could be raised when the text entered by a user consists of less than 10 characters.

Answer:

User-defined exceptions custom validation logic implement કરવા માટે powerful tool છે.

Diagram: Custom Exception Flow

Python

Additional Features:

Python
  • Custom Logic: Application-specific validation rules implement કરી શકાય
  • Inheritance: Exception class ને inherit કરીને custom exceptions બનાવાય
  • Detailed Information: Exception object માં additional data store કરી શકાય

Mnemonic: "Custom Exception = Class Inherit Raise"


Question 4(a) [3 marks]

Write five points on difference between Text File and Binary File.

Answer:

Table: Text File vs Binary File

FeatureText FileBinary File
ContentHuman-readable charactersBinary data (0s and 1s)
EncodingCharacter encoding (UTF-8, ASCII)No character encoding
Opening Mode'r', 'w', 'a''rb', 'wb', 'ab'
File SizeGenerally largerGenerally smaller
PlatformPlatform dependentPlatform independent
Python
  • Readability: Text files editor માં read કરી શકાય, binary files special software જોઈએ
  • Portability: Binary files different platforms પર easily transfer થાય
  • Processing: Text files string operations માટે, binary files exact data storage માટે

Mnemonic: "Text Human, Binary Machine"


Question 4(b) [4 marks]

Write a program to read the data from a file and separate the uppercase character and lowercase character into two separate files.

Answer:

File processing માં character-based operations common requirements છે.

Table: File Operations

OperationMethodPurpose
Readread()Complete file content
Writewrite()Write string to file
Character Checkisupper(), islower()Character case detection
File Handlingwith open()Safe file operations
Python
  • Character Processing: દરેક character ની case individually check કરાય છે
  • File Safety: with statement automatic file closing ensure કરે છે
  • Error Handling: File operations માં proper exception handling

Mnemonic: "Read Separate Write"


Question 4(c) [7 marks]

Describe dump() and load() method. Explain with example.

Answer:

dump() અને load() methods pickle module ના part છે જે object serialization માટે વાપરાય છે.

Table: Pickle Methods

MethodPurposeFile ModeDescription
dump()Serialize object to file'wb'Object ને binary file માં store કરે
load()Deserialize object from file'rb'File માંથી object retrieve કરે
dumps()Serialize to bytesN/AObject ને bytes માં convert કરે
loads()Deserialize from bytesN/ABytes માંથી object બનાવે

Diagram: Serialization Process

Python

Benefits and Limitations:

Python
  • Object Persistence: Python objects ને file માં permanently store કરી શકાય
  • Complete State: Object ની complete state including methods preserve થાય છે
  • Binary Format: Efficient storage પણ human-readable નથી

Mnemonic: "Dump Store, Load Restore"


Question 4(a OR) [3 marks]

List different types of file modes provided by python for file operations and explain their uses.

Answer:

Table: Python File Modes

ModeTypeDescriptionPointer Position
'r'Text ReadRead only, file must existBeginning
'w'Text WriteWrite only, creates/overwritesBeginning
'a'Text AppendWrite only, creates if not existEnd
'x'Text CreateCreate new file, fails if existsBeginning
'rb'Binary ReadRead binary dataBeginning
'wb'Binary WriteWrite binary dataBeginning
'ab'Binary AppendAppend binary dataEnd
'r+'Text Read/WriteRead and write, file must existBeginning
'w+'Text Write/ReadWrite and read, creates/overwritesBeginning
Python
  • Safety: 'x' mode prevents accidental file overwriting
  • Efficiency: Binary modes faster for non-text data
  • Flexibility: Combined modes allow both read and write operations

Mnemonic: "Read Write Append Create Binary Plus"


Question 4(b OR) [4 marks]

Describe readline() and writeline() functions of the file.

Answer:

Note: Python માં writeline() function exist નથી. Correct function writelines() છે.

Table: Line-based File Functions

FunctionPurposeReturn TypeUsage
readline()Read single lineStringSequential line reading
readlines()Read all linesList of stringsComplete file as list
writelines()Write multiple linesNoneWrite list of strings
write()Write single stringNumber of charsBasic writing
Python
  • Sequential Access: readline() sequential manner માં lines read કરે છે
  • Memory Efficient: Large files માટે readline() memory-efficient છે
  • List Operations: writelines() list of strings ને efficiently write કરે છે

Mnemonic: "Read Line, Write Lines"


Question 4(c OR) [7 marks]

Write a python program to demonstrate seek() and tell() methods.

Answer:

seek() અને tell() methods file pointer manipulation માટે વાપરાય છે.

Table: File Pointer Methods

MethodPurposeParametersReturn Value
tell()Current positionNoneInteger (byte position)
seek()Move pointeroffset, whenceNew position
whence=0From beginningDefaultAbsolute position
whence=1From currentRelativeCurrent + offset
whence=2From endEnd relativeEnd + offset

Diagram: File Pointer Movement

goat
Python
  • File Navigation: seek() arbitrary position પર move કરવા માટે વાપરાય છે
  • Position Tracking: tell() current position track કરવા માટે useful છે
  • File Editing: Specific locations પર data modify કરવા માટે જરૂરી

Mnemonic: "Tell Position, Seek Destination"


Question 5(a) [3 marks]

Draw Circle and rectangle shapes using Turtle and fill them with red color.

Answer:

Turtle graphics module માં shapes draw કરવા અને fill કરવા માટે specific methods છે.

Table: Turtle Shape Methods

MethodPurposeExample
circle()Draw circleturtle.circle(50)
forward()Move forwardturtle.forward(100)
right()Turn rightturtle.right(90)
begin_fill()Start fillingturtle.begin_fill()
end_fill()End fillingturtle.end_fill()
fillcolor()Set fill colorturtle.fillcolor("red")
Python
  • Fill Process: begin_fill() અને end_fill() વચ્ચે drawn shape automatically fill થાય છે
  • Color Setting: fillcolor() method fill color set કરે છે
  • Shape Drawing: Geometric shapes માટે specific turtle movements

Mnemonic: "Begin Fill Draw End"


Question 5(b) [4 marks]

Explain the various inbuilt methods to change the direction of the Turtle.

Answer:

Table: Turtle Direction Methods

MethodParametersDescriptionExample
right()angleTurn right by degreesturtle.right(90)
left()angleTurn left by degreesturtle.left(45)
setheading()angleSet absolute directionturtle.setheading(0)
towards()x, yPoint towards coordinatesturtle.towards(100, 50)
home()noneReturn to center, face eastturtle.home()
Python
  • Relative Turns: right() અને left() current direction થી relative turn
  • Absolute Direction: setheading() absolute compass direction set કરે
  • Smart Pointing: towards() specific coordinates તરફ point કરે

Mnemonic: "Right Left Set Towards Home"


Question 5(c) [7 marks]

Write a python program to draw a rainbow using Turtle.

Answer:

Rainbow drawing માં multiple colored arcs અને proper positioning જરૂરી છે.

Diagram: Rainbow Structure

goat
Python
  • Color Sequence: ROYGBIV (Red Orange Yellow Green Blue Indigo Violet) નો proper order
  • Radius Management: દરેક arc નો radius gradually decrease કરાય છે
  • Positioning: Proper positioning માટે penup/pendown અને goto methods

Mnemonic: "ROYGBIV Arc Radius Position"


Question 5(a OR) [3 marks]

Draw a diagram of turtle screen and explain all 4 quadrants of x and y coordinates.

Answer:

Diagram: Turtle Coordinate System

goat

Table: Coordinate Quadrants

QuadrantX ValueY ValueDescriptionExample
IPositive (+)Positive (+)Top-right(100, 50)
IINegative (-)Positive (+)Top-left(-100, 50)
IIINegative (-)Negative (-)Bottom-left(-100, -50)
IVPositive (+)Negative (-)Bottom-right(100, -50)
Python
  • Origin: (0,0) screen ના center પર આવેલું છે
  • Positive Direction: X-axis right તરફ, Y-axis up તરફ positive
  • Navigation: goto(x, y) method specific coordinates પર move કરે છે

Mnemonic: "Right Up Positive, Left Down Negative"


Question 5(b OR) [4 marks]

Describe various turtle screen methods to change the background color, title, screensize and shapesize.

Answer:

Table: Turtle Screen Methods

MethodPurposeParametersExample
bgcolor()Set background colorcolor name/hexscreen.bgcolor("blue")
title()Set window titlestringscreen.title("My Program")
setup()Set screen sizewidth, heightscreen.setup(800, 600)
screensize()Set canvas sizewidth, heightscreen.screensize(400, 300)
shapesize()Set turtle sizestretch_wid, stretch_lenturtle.shapesize(2, 3)
Python
  • Window vs Canvas: setup() window size, screensize() canvas size control કરે છે
  • Color Modes: bgcolor() color names અથવા hex values accept કરે છે
  • Shape Scaling: shapesize() turtle appearance ને scale કરે છે

Mnemonic: "Title Background Setup Size Shape"


Question 5(c OR) [7 marks]

Write a python program to draw a star, triangle and octagon using turtle.

Answer:

Geometric shapes drawing માં angles અને sides ની proper calculation જરૂરી છે.

Table: Shape Properties

ShapeSidesExternal AngleInternal AngleTurn Angle
Triangle3120°60°120°
Star (5-point)5144°36°144°
Octagon845°135°45°

Diagram: Shape Construction

goat
Python
  • Angle Calculation: દરેક shape માટે correct turn angles ની calculation જરૂરી
  • Fill Technique: begin_fill() અને end_fill() વચ્ચે shape automatically fill થાય
  • Mathematical Foundation: Geometry ના principles આધારે shapes construct થાય

Mnemonic: "Triangle 120, Star 144, Octagon 45"