Advanced Python Programming (4321602) - Summer 2024 Solution
Solution guide for Advanced Python Programming (4321602) Summer 2024 exam
Question 1(a) [3 marks]
Give the difference between Tuple and List in python.
Answer:
| Feature | Tuple | List |
|---|---|---|
| Mutability | Immutable (cannot be changed) | Mutable (can be changed) |
| Syntax | Created using () | Created using [] |
| Performance | Faster | Slower |
| Methods | Limited methods (count, index) | Many methods (append, remove, etc.) |
- Memory efficient: Tuples use less memory than lists
- Use case: Tuples for fixed data, lists for dynamic data
Mnemonic: "Tuples are Tight, Lists are Loose"
Question 1(b) [4 marks]
Define Set and how is it created in python?
Answer:
Set is an unordered collection of unique elements in Python.
Creating Sets:
Python
- Unique elements: No duplicates allowed
- Unordered: Elements have no specific order
- Operations: Union, intersection, difference supported
Mnemonic: "Sets are Special - Unique and Unordered"
Question 1(c) [7 marks]
What is Dictionary in Python? Write a program to concatenate two dictionary into new one.
Answer:
Dictionary is an ordered collection of key-value pairs in Python.
Program:
Python
- Key-value pairs: Each element has a key and value
- Mutable: Can be modified after creation
- Fast access: O(1) average time complexity
Mnemonic: "Dictionaries are Dynamic Key-Value stores"
Question 1(c) OR [7 marks]
What is a list in python? Write a program that finds maximum and minimum numbers from a list.
Answer:
List is an ordered, mutable collection of elements in Python.
Program:
Python
- Ordered: Elements maintain insertion order
- Indexing: Accessed using index [0, 1, 2...]
- Built-in functions: min(), max(), len() available
Mnemonic: "Lists are Linear and Indexed"
Question 2(a) [3 marks]
Explain Nested Tuple with example.
Answer:
Nested Tuple is a tuple containing other tuples as elements.
Example:
Python
- Multi-dimensional: Tuples within tuples
- Indexing: Use multiple indices [i][j]
- Immutable: Cannot change nested elements
Mnemonic: "Nested means Tuples inside Tuples"
Question 2(b) [4 marks]
What is random module? Explain with example.
Answer:
Random module generates random numbers and performs random operations.
Example:
Python
- Import required: import random
- Various functions: randint(), choice(), random()
- Useful for: Games, simulations, testing
Mnemonic: "Random makes things Unpredictable"
Question 2(c) [7 marks]
Explain different ways of importing package. Give one example of it.
Answer:
Import Methods:
| Method | Syntax | Usage |
|---|---|---|
| Normal import | import package | package.function() |
| From import | from package import function | function() |
| Import all | from package import * | function() |
| Alias import | import package as alias | alias.function() |
Example:
Python
- Namespace: Normal import keeps separate namespace
- Direct access: From import allows direct function call
- Alias: Shorter names for convenience
Mnemonic: "Import methods: Normal, From, All, Alias"
Question 2(a) OR [3 marks]
Write down the properties of dictionary in python.
Answer:
Dictionary Properties:
| Property | Description |
|---|---|
| Ordered | Maintains insertion order (Python 3.7+) |
| Mutable | Can be modified after creation |
| Key-unique | No duplicate keys allowed |
| Heterogeneous | Keys and values can be different types |
- Fast access: O(1) average lookup time
- Dynamic size: Can grow or shrink
- Key restrictions: Keys must be immutable
Mnemonic: "Dictionaries are Ordered, Mutable, Unique, Heterogeneous"
Question 2(b) OR [4 marks]
What is the dir() function in python. Explain with example.
Answer:
dir() function returns all attributes and methods of an object.
Example:
Python
- Introspection: Examines object properties
- Debugging: Helps find available methods
- All objects: Works with any Python object
Mnemonic: "dir() shows Directory of object attributes"
Question 2(c) OR [7 marks]
Write a program to define module to find sum of two numbers. Import module to another program.
Answer:
Module file (calculator.py):
Python
Main program:
Python
- Module creation: Save functions in .py file
- Import: Use import statement to access
- Code reusability: Use same module in multiple programs
Mnemonic: "Modules make code Reusable and Organized"
Question 3(a) [3 marks]
What is Runtime error and Logical error. Explain with example.
Answer:
| Error Type | Definition | Example |
|---|---|---|
| Runtime Error | Occurs during program execution | Division by zero, file not found |
| Logical Error | Program runs but gives wrong output | Wrong formula, incorrect condition |
Examples:
Python
- Runtime: Crashes program execution
- Logical: Program continues but wrong result
Mnemonic: "Runtime Crashes, Logical Confuses"
Question 3(b) [4 marks]
Write points on Except and explaining it.
Answer:
Except clause handles specific exceptions in try-except block.
Key Points:
| Feature | Description |
|---|---|
| Syntax | except ExceptionType: |
| Multiple | Can have multiple except blocks |
| Generic | except: catches all exceptions |
| Variable | except Exception as e: stores error |
Python
- Specific handling: Different exceptions handled differently
- Error recovery: Program continues after handling
Mnemonic: "Except Catches and Handles errors"
Question 3(c) [7 marks]
Write a program to catch Divide by zero Exception. Also use finally block.
Answer:
Python
- Try block: Contains risky code
- Except: Handles ZeroDivisionError specifically
- Finally: Always executes regardless of exception
Mnemonic: "Try risky code, Except handles errors, Finally always runs"
Question 3(a) OR [3 marks]
What are the built-in exceptions and gives its types.
Answer:
Built-in Exception Types:
| Type | Description | Example |
|---|---|---|
| ValueError | Invalid value for operation | int("abc") |
| TypeError | Wrong data type | "5" + 5 |
| IndexError | Index out of range | list[10] for 5-element list |
| KeyError | Key not found in dictionary | dict["missing_key"] |
| FileNotFoundError | File doesn't exist | open("missing.txt") |
Python
Mnemonic: "Value, Type, Index, Key, File - common error types"
Question 3(b) OR [4 marks]
Explain Syntax error and how do we identify it? Give an example.
Answer:
Syntax Error occurs when Python cannot parse the code due to incorrect syntax.
Identification:
| Method | Description |
|---|---|
| Python interpreter | Shows error message with line number |
| IDE highlighting | Code editors highlight syntax errors |
| Error message | Points to exact location of error |
Examples:
Python
- Detection: Before program execution
- Error message: Shows line and character position
- Common causes: Missing colons, brackets, wrong indentation
Mnemonic: "Syntax errors Stop code from Starting"
Question 3(c) OR [7 marks]
What is Exception handling in python? Explain with proper example.
Answer:
Exception Handling is a mechanism to handle runtime errors gracefully without crashing the program.
Structure:
Python
Complete Example:
Python
- Graceful handling: Program continues after error
- Multiple exceptions: Different error types handled separately
- Else clause: Runs only if no exception occurs
- Finally clause: Always executes for cleanup
Mnemonic: "Try-Except-Else-Finally: Complete error handling"
Question 4(a) [3 marks]
What kind of different operations we can perform in a file?
Answer:
File Operations:
| Operation | Description | Method |
|---|---|---|
| Read | Read file content | read(), readline(), readlines() |
| Write | Write data to file | write(), writelines() |
| Append | Add data to end | open with 'a' mode |
| Create | Create new file | open with 'w' or 'x' mode |
| Delete | Remove file | os.remove() |
| Seek | Move file pointer | seek() |
Python
Mnemonic: "Read, Write, Append, Create, Delete, Seek"
Question 4(b) [4 marks]
Give list of file modes. Write Description of any four mode.
Answer:
File Modes:
| Mode | Description | Purpose |
|---|---|---|
| 'r' | Read mode (default) | Read existing file |
| 'w' | Write mode | Create new or overwrite existing |
| 'a' | Append mode | Add to end of existing file |
| 'x' | Exclusive creation | Create new file, fail if exists |
| 'b' | Binary mode | Handle binary files |
| 't' | Text mode (default) | Handle text files |
| '+' | Read and write | Both operations allowed |
Four Mode Descriptions:
- 'r' (Read): Opens file for reading only, file pointer at beginning
- 'w' (Write): Opens for writing, truncates file or creates new one
- 'a' (Append): Opens for writing, file pointer at end of file
- 'r+' (Read/Write): Opens for both reading and writing
Mnemonic: "Read, Write, Append, eXclusive - main file modes"
Question 4(c) [7 marks]
Write a program to sort all the words in a file and put it in list.
Answer:
Python
- File reading: Read entire file content
- Word processing: Split, clean, and sort words
- List creation: Store sorted words in list
Mnemonic: "Read, Split, Clean, Sort, Save"
Question 4(a) OR [3 marks]
What is file handling? List files handling operation and explain it.
Answer:
File Handling is the process of working with files to store and retrieve data permanently.
File Handling Operations:
| Operation | Function | Description |
|---|---|---|
| Open | open() | Opens file in specified mode |
| Read | read(), readline() | Reads data from file |
| Write | write(), writelines() | Writes data to file |
| Close | close() | Closes file and frees resources |
| Seek | seek() | Moves file pointer position |
| Tell | tell() | Returns current file pointer position |
Python
Mnemonic: "Open, Read, Write, Close - basic file cycle"
Question 4(b) OR [4 marks]
Explain load() method with example.
Answer:
load() method is used to deserialize data from a file (usually with pickle module).
Pickle load() Example:
Python
JSON load() Example:
Python
- Deserialization: Converts file data back to Python objects
- Binary mode: Use 'rb' mode for pickle files
- Error handling: Handle FileNotFoundError
Mnemonic: "load() brings file data back to Python objects"
Question 4(c) OR [7 marks]
Write a program that inputs a text file. The program should print all of the unique words in the file in alphabetical order.
Answer:
Python
- Regular expressions: Extract only alphabetic words
- Set data structure: Automatically removes duplicates
- Sorted function: Arranges words alphabetically
- File output: Saves results for future reference
Mnemonic: "Read, Extract, Unique, Sort, Display"
Question 5(a) [3 marks]
Explain the use of the following turtle function with an appropriate example. (a) turn() (b) move().
Answer:
Note: Standard turtle module uses left(), right() instead of turn(), and forward(), backward() instead of move().
Turtle Movement Functions:
| Function | Purpose | Example |
|---|---|---|
| left(angle) | Turn left by degrees | turtle.left(90) |
| right(angle) | Turn right by degrees | turtle.right(45) |
| forward(distance) | Move forward | turtle.forward(100) |
| backward(distance) | Move backward | turtle.backward(50) |
Python
Mnemonic: "Turn changes direction, Move changes position"
Question 5(b) [4 marks]
Explain the various inbuilt methods to change the direction of the turtle.
Answer:
Direction Control Methods:
| Method | Description | Example |
|---|---|---|
| left(angle) | Turn counterclockwise | turtle.left(90) |
| right(angle) | Turn clockwise | turtle.right(45) |
| setheading(angle) | Set absolute direction | turtle.setheading(0) |
| towards(x, y) | Point towards coordinates | turtle.setheading(turtle.towards(100, 100)) |
Python
- Relative: left() and right() change current direction
- Absolute: setheading() sets exact direction
- Coordinate-based: towards() calculates direction to point
Mnemonic: "Left-Right relative, Heading absolute, Towards calculates"
Question 5(c) [7 marks]
Write a program to draw square, rectangle and circle using turtle.
Answer:
Python
- Square: 4 equal sides with 90° turns
- Rectangle: 2 pairs of equal sides
- Circle: Built-in circle() method with radius
Mnemonic: "Square: 4 equal sides, Rectangle: 2 pairs, Circle: radius method"
Question 5(a) OR [3 marks]
What are the various types of pen command in turtle? Explain them all.
Answer:
Pen Control Commands:
| Command | Purpose | Example |
|---|---|---|
| penup() | Lift pen (no drawing) | turtle.penup() |
| pendown() | Put pen down (start drawing) | turtle.pendown() |
| pensize(width) | Set pen thickness | turtle.pensize(5) |
| pencolor(color) | Set pen color | turtle.pencolor("red") |
| fillcolor(color) | Set fill color | turtle.fillcolor("blue") |
| begin_fill() | Start filling shape | turtle.begin_fill() |
| end_fill() | End filling shape | turtle.end_fill() |
Python
Mnemonic: "Up-Down controls drawing, Size-Color controls appearance"
Question 5(b) OR [4 marks]
Draw circle and star shapes using turtle and fill them with red color.
Answer:
Python
Key Points:
- begin_fill(): Start filling the shape
- end_fill(): Complete the fill
- color(): Set both pen and fill colors
- Star angle: 144° for 5-pointed star
Mnemonic: "Begin fill, Draw shape, End fill = Filled shape"
Question 5(c) OR [7 marks]
Write a program to draw Indian Flag using turtle.
Answer:
Python
Flag Components:
- Saffron: Courage and sacrifice (top)
- White: Truth and peace (middle)
- Green: Faith and chivalry (bottom)
- Ashoka Chakra: 24-spoke wheel in navy blue
Mnemonic: "Saffron-White-Green stripes with 24-spoke Chakra"