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
| Property | Description |
|---|---|
| Mutable | Values ને change કરી શકાય છે |
| Ordered | Python 3.7+ માં insertion order maintain રહે છે |
| Indexed | Keys દ્વારા access કરાય છે |
| No Duplicates | Duplicate 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
| Method | Description | Example |
|---|---|---|
| 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
| Operation | Symbol | Method | Description |
|---|---|---|---|
| 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
| Method | Description | Example |
|---|---|---|
| keys() | બધી keys return કરે છે | dict.keys() |
| values() | બધા values return કરે છે | dict.values() |
| items() | Key-value pairs return કરે છે | dict.items() |
| get() | Safe value retrieval | dict.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
| Feature | Tuple | List |
|---|---|---|
| Mutability | Immutable (cannot change) | Mutable (can change) |
| Syntax | Parentheses () | Square brackets [] |
| Performance | Faster | Slower |
| Memory | Less memory | More memory |
| Methods | Limited (count, index) | Many methods available |
| Use Case | Fixed data | Dynamic 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
| Feature | Description |
|---|---|
| Object Inspection | Object ના attributes show કરે છે |
| Method Discovery | Available methods list કરે છે |
| Namespace Exploration | Current namespace ના variables show કરે છે |
| Module Analysis | Module ના 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
| Feature | Description |
|---|---|
| Multi-dimensional | 2D અથવા 3D data structure |
| Immutable | બધા levels પર immutable |
| Indexing | Multiple square brackets વાપરીને access |
| Heterogeneous | Different 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
| Command | Syntax | Description |
|---|---|---|
| Install | pip install package_name | Package install કરે છે |
| Uninstall | pip uninstall package_name | Package remove કરે છે |
| List | pip list | Installed packages show કરે છે |
| Show | pip show package_name | Package info display કરે છે |
| Upgrade | pip install --upgrade package_name | Package 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
| Method | Syntax | Usage |
|---|---|---|
| Basic Import | import module | Full module name required |
| From Import | from module import function | Direct function access |
| Alias Import | import module as alias | Short name for module |
| Star Import | from module import * | Import all functions |
| Package Import | from package import module | Import 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 Type | When Occurs | Detection | Example |
|---|---|---|---|
| Syntax Error | Code parsing time | Before execution | Missing colon, brackets |
| Runtime Error | During execution | While running | Division by zero, file not found |
| Logic Error | Always | After execution | Wrong 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
| Keyword | Purpose | Description |
|---|---|---|
| try | Exception માં થઈ શકે એવો code | Risk code block |
| except | Exception handle કરવા માટે | Error handling block |
| finally | હંમેશા execute થાય | Cleanup code |
| else | Exception ન આવે તો | Success code block |
| raise | Manual 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
| Exception | Cause | Example |
|---|---|---|
| ValueError | Invalid value for operation | int("abc") |
| TypeError | Wrong data type | "hello" + 5 |
| IndexError | Index out of range | list[10] when list has 5 elements |
| KeyError | Dictionary key not found | dict["nonexistent"] |
| FileNotFoundError | File does not exist | open("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
| Block | Purpose | Execution | Mandatory |
|---|---|---|---|
| try | Risky code | First | Yes |
| except | Error handling | If exception occurs | At least one |
| else | Success code | If no exception | No |
| finally | Cleanup code | Always | No |
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
| Feature | Text File | Binary File |
|---|---|---|
| Content | Human-readable characters | Binary data (0s and 1s) |
| Encoding | Character encoding (UTF-8, ASCII) | No character encoding |
| Opening Mode | 'r', 'w', 'a' | 'rb', 'wb', 'ab' |
| File Size | Generally larger | Generally smaller |
| Platform | Platform dependent | Platform 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
| Operation | Method | Purpose |
|---|---|---|
| Read | read() | Complete file content |
| Write | write() | Write string to file |
| Character Check | isupper(), islower() | Character case detection |
| File Handling | with 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
| Method | Purpose | File Mode | Description |
|---|---|---|---|
| dump() | Serialize object to file | 'wb' | Object ને binary file માં store કરે |
| load() | Deserialize object from file | 'rb' | File માંથી object retrieve કરે |
| dumps() | Serialize to bytes | N/A | Object ને bytes માં convert કરે |
| loads() | Deserialize from bytes | N/A | Bytes માંથી 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
| Mode | Type | Description | Pointer Position |
|---|---|---|---|
| 'r' | Text Read | Read only, file must exist | Beginning |
| 'w' | Text Write | Write only, creates/overwrites | Beginning |
| 'a' | Text Append | Write only, creates if not exist | End |
| 'x' | Text Create | Create new file, fails if exists | Beginning |
| 'rb' | Binary Read | Read binary data | Beginning |
| 'wb' | Binary Write | Write binary data | Beginning |
| 'ab' | Binary Append | Append binary data | End |
| 'r+' | Text Read/Write | Read and write, file must exist | Beginning |
| 'w+' | Text Write/Read | Write and read, creates/overwrites | Beginning |
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
| Function | Purpose | Return Type | Usage |
|---|---|---|---|
| readline() | Read single line | String | Sequential line reading |
| readlines() | Read all lines | List of strings | Complete file as list |
| writelines() | Write multiple lines | None | Write list of strings |
| write() | Write single string | Number of chars | Basic 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
| Method | Purpose | Parameters | Return Value |
|---|---|---|---|
| tell() | Current position | None | Integer (byte position) |
| seek() | Move pointer | offset, whence | New position |
| whence=0 | From beginning | Default | Absolute position |
| whence=1 | From current | Relative | Current + offset |
| whence=2 | From end | End relative | End + 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
| Method | Purpose | Example |
|---|---|---|
| circle() | Draw circle | turtle.circle(50) |
| forward() | Move forward | turtle.forward(100) |
| right() | Turn right | turtle.right(90) |
| begin_fill() | Start filling | turtle.begin_fill() |
| end_fill() | End filling | turtle.end_fill() |
| fillcolor() | Set fill color | turtle.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
| Method | Parameters | Description | Example |
|---|---|---|---|
| right() | angle | Turn right by degrees | turtle.right(90) |
| left() | angle | Turn left by degrees | turtle.left(45) |
| setheading() | angle | Set absolute direction | turtle.setheading(0) |
| towards() | x, y | Point towards coordinates | turtle.towards(100, 50) |
| home() | none | Return to center, face east | turtle.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
| Quadrant | X Value | Y Value | Description | Example |
|---|---|---|---|---|
| I | Positive (+) | Positive (+) | Top-right | (100, 50) |
| II | Negative (-) | Positive (+) | Top-left | (-100, 50) |
| III | Negative (-) | Negative (-) | Bottom-left | (-100, -50) |
| IV | Positive (+) | 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
| Method | Purpose | Parameters | Example |
|---|---|---|---|
| bgcolor() | Set background color | color name/hex | screen.bgcolor("blue") |
| title() | Set window title | string | screen.title("My Program") |
| setup() | Set screen size | width, height | screen.setup(800, 600) |
| screensize() | Set canvas size | width, height | screen.screensize(400, 300) |
| shapesize() | Set turtle size | stretch_wid, stretch_len | turtle.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
| Shape | Sides | External Angle | Internal Angle | Turn Angle |
|---|---|---|---|---|
| Triangle | 3 | 120° | 60° | 120° |
| Star (5-point) | 5 | 144° | 36° | 144° |
| Octagon | 8 | 45° | 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"