Python Programming (4311601) - Winter 2023 Solution
Solution guide for Python Programming (4311601) Winter 2023 exam
Question 1(a) [3 marks]
What is Flow chart? List out symbols used in Flow chart.
Answer:
A flowchart is a graphical representation of an algorithm that shows the sequence of steps and decision points in a process using standardized symbols.
Flowchart Symbols Table:
| Symbol | Name | Purpose |
|---|---|---|
| Oval | Terminal | Start/End of program |
| Rectangle | Process | Processing/Calculation steps |
| Diamond | Decision | Conditional statements |
| Parallelogram | Input/Output | Data input or output |
| Circle | Connector | Connect flowchart parts |
| Arrow | Flow line | Direction of flow |
Key Points:
- Visual representation: Shows program logic graphically
- Step-by-step: Displays sequential flow of operations
- Decision making: Diamond symbols show conditional branches
Mnemonic: "Flow Charts Show Program Steps Visually"
Question 1(b) [4 marks]
Write a short note on for loop.
Answer:
The for loop is used to iterate over a sequence (list, tuple, string, range) in Python.
For Loop Table:
| Component | Syntax | Example |
|---|---|---|
| Basic | for variable in sequence: | for i in range(5): |
| Range | range(start, stop, step) | range(1, 10, 2) |
| List | for item in list: | for x in [1,2,3]: |
| String | for char in string: | for c in "hello": |
Simple Code Example:
Python
Key Features:
- Automatic iteration: No manual counter needed
- Sequence traversal: Works with any iterable object
- Range function: Creates number sequences easily
Mnemonic: "For Loops Iterate Through Sequences"
Question 1(c) [7 marks]
Write a program to display Fibonacci series up to nth term where n is provided by the user.
Answer:
Fibonacci Series Program:
Python
Algorithm Flow:
Key Concepts:
- Sequential generation: Each term = sum of previous two
- Variable swapping: Update a, b values efficiently
- User input: Dynamic series length
Mnemonic: "Fibonacci: Add Previous Two Numbers"
Question 1(c OR) [7 marks]
Draw a flow chart to print ODD numbers from 1 to 100.
Answer:
Flowchart for ODD Numbers 1 to 100:
Corresponding Python Code:
Python
Alternative Method:
Python
Key Elements:
- Loop control: i from 1 to 100
- Odd check: i % 2 != 0 condition
- Step increment: Move to next number
Mnemonic: "Odd Numbers: Remainder 1 When Divided by 2"
Question 2(a) [3 marks]
Write a Program to find whether a number is Palindrome or not.
Answer:
Palindrome Check Program:
Python
Algorithm Table:
| Step | Operation | Example (121) |
|---|---|---|
| 1 | Get last digit | 121 % 10 = 1 |
| 2 | Build reverse | 0*10 + 1 = 1 |
| 3 | Remove last digit | 121 // 10 = 12 |
| 4 | Repeat until 0 | Continue process |
Key Points:
- Digit extraction: Use modulo (%) operator
- Reverse building: Multiply by 10 and add digit
- Comparison: Original equals reversed
Mnemonic: "Palindrome Reads Same Forward Backward"
Question 2(b) [4 marks]
Explain features of Python Programming.
Answer:
Python Features Table:
| Feature | Description | Benefit |
|---|---|---|
| Easy Syntax | Simple, readable code | Faster development |
| Interpreted | No compilation needed | Quick testing |
| Object-Oriented | Classes and objects support | Code reusability |
| Open Source | Free to use | No licensing cost |
| Cross-Platform | Runs on multiple OS | Wide compatibility |
| Large Libraries | Extensive built-in modules | Rich functionality |
Key Advantages:
- Beginner-friendly: Easy to learn and understand
- Versatile: Web development, AI, data science
- Community support: Large developer community
- Dynamic typing: No variable type declaration needed
Mnemonic: "Python: Easy, Powerful, Popular Programming"
Question 2(c) [7 marks]
Explain basic structure of Python Program.
Answer:
Python Program Structure:
Python
Structure Components Table:
| Component | Purpose | Example |
|---|---|---|
| Shebang | System interpreter | #!/usr/bin/env python3 |
| Docstring | Program documentation | """Program description""" |
| Imports | External modules | import math |
| Variables | Global data storage | PI = 3.14159 |
| Functions | Reusable code blocks | def function_name(): |
| Classes | Object templates | class ClassName: |
| Main block | Program execution | if __name__ == "__main__": |
Key Principles:
- Indentation: Defines code blocks (4 spaces recommended)
- Comments: Use # for single line, """ """ for multi-line
- Modularity: Organize code in functions and classes
Mnemonic: "Structure: Import, Define, Execute"
Question 2(a OR) [3 marks]
Write a Program to reverse a string.
Answer:
String Reversal Program:
Python
Reversal Methods Table:
| Method | Syntax | Example |
|---|---|---|
| Slicing | string[::-1] | "hello" → "olleh" |
| Loop | Build character by character | Add each char to front |
| Built-in | "".join(reversed(string)) | Join reversed sequence |
Key Concepts:
- Slicing: Most efficient method
- Concatenation: Build string character by character
- Indexing: Access string positions
Mnemonic: "Reverse: Last Character First"
Question 2(b OR) [4 marks]
Explain Logical Operators with example.
Answer:
Python Logical Operators:
| Operator | Symbol | Description | Example | Result |
|---|---|---|---|---|
| AND | and | Both conditions true | True and False | False |
| OR | or | At least one condition true | True or False | True |
| NOT | not | Opposite of condition | not True | False |
Example Code:
Python
Truth Table:
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| T | T | T | T | F |
| T | F | F | T | F |
| F | T | F | T | T |
| F | F | F | F | T |
Key Uses:
- Complex conditions: Combine multiple checks
- Decision making: Control program flow
- Boolean logic: True/False operations
Mnemonic: "AND needs All, OR needs One, NOT reverses"
Question 2(c OR) [7 marks]
Explain different Data Types in Python Programming language
Answer:
Python Data Types Classification:
Data Types Table:
| Type | Example | Description | Mutable |
|---|---|---|---|
| int | 42 | Whole numbers | No |
| float | 3.14 | Decimal numbers | No |
| str | "hello" | Text data | No |
| list | [1,2,3] | Ordered collection | Yes |
| tuple | (1,2,3) | Ordered immutable | No |
| dict | {"a":1} | Key-value pairs | Yes |
| bool | True/False | Boolean values | No |
| set | {1,2,3} | Unique elements | Yes |
Example Code:
Python
Key Features:
- Dynamic typing: No need to declare variable types
- Type conversion: Convert between compatible types
- Built-in functions:
type(),isinstance()for checking types
Mnemonic: "Python Types: Numbers, Sequences, Collections"
Question 3(a) [3 marks]
What is flow control in Python? Explain with example
Answer:
Flow control manages the execution order of program statements using conditional and loop structures.
Flow Control Types Table:
| Type | Statement | Purpose | Example |
|---|---|---|---|
| Sequential | Normal execution | Line by line | print("Hello") |
| Selection | if, elif, else | Decision making | if x > 0: |
| Iteration | for, while | Repetition | for i in range(5): |
| Jump | break, continue | Loop control | break |
Example Code:
Python
Key Concepts:
- Conditional execution: Code runs based on conditions
- Loop structures: Repeat code blocks
- Program flow: Control execution path
Mnemonic: "Flow Control: Decide, Repeat, Jump"
Question 3(b) [4 marks]
Write a program to explain nested if statement.
Answer:
Nested If Statement Program:
Python
Nested Structure Diagram:
goat
Key Features:
- Multiple levels: if inside if statements
- Complex conditions: Handle multiple criteria
- Logical structure: Organize decision trees
Mnemonic: "Nested If: Decisions Within Decisions"
Question 3(c) [7 marks]
Write a program to Explain types of Arguments and Parameters.
Answer:
Types of Arguments and Parameters:
Python
Parameters Types Table:
| Type | Syntax | Example | Description |
|---|---|---|---|
| Positional | def func(a, b): | func(1, 2) | Order matters |
| Keyword | def func(a, b): | func(b=2, a=1) | Name specified |
| Default | def func(a, b=10): | func(5) | Default value |
| *args | def func(*args): | func(1,2,3) | Variable positional |
| **kwargs | def func(**kwargs): | func(a=1, b=2) | Variable keyword |
Function Call Examples:
Python
Key Concepts:
- Flexibility: Different ways to pass data
- Order importance: Positional vs keyword
- Variable arguments: Handle unknown number of inputs
Mnemonic: "Parameters: Position, Keywords, Defaults, Variables"
Question 3(a OR) [3 marks]
Explain break and continue statement with example.
Answer:
Break and Continue Statements:
Break Statement:
Python
Continue Statement:
Python
Comparison Table:
| Statement | Purpose | Action | Example Use |
|---|---|---|---|
| break | Exit loop | Terminates entire loop | Exit on condition |
| continue | Skip iteration | Jump to next iteration | Skip specific values |
Key Differences:
- Break: Completely exits loop
- Continue: Skips current iteration only
- Flow control: Manage loop execution
Mnemonic: "Break Exits, Continue Skips"
Question 3(b OR) [4 marks]
Create a program to display the following pattern
1
12
123
1234
12345
Answer:
Number Pattern Program:
Python
Pattern Logic Table:
| Row | Numbers | Range | Output |
|---|---|---|---|
| 1 | 1 | 1 to 1 | 1 |
| 2 | 1,2 | 1 to 2 | 12 |
| 3 | 1,2,3 | 1 to 3 | 123 |
| 4 | 1,2,3,4 | 1 to 4 | 1234 |
| 5 | 1,2,3,4,5 | 1 to 5 | 12345 |
Key Concepts:
- Nested loops: Outer for rows, inner for numbers
- Range function: Generate number sequences
- Print control: Use end="" to avoid newlines
Mnemonic: "Pattern: Row Number Determines Column Count"
Question 3(c OR) [7 marks]
Explain the following mathematical functions by writing a code for each: 1. abs() 2. max() 3. pow() 4. sum()
Answer:
Mathematical Functions in Python:
Python
Functions Summary Table:
| Function | Syntax | Purpose | Example | Result |
|---|---|---|---|---|
| abs() | abs(x) | Absolute value | abs(-5) | 5 |
| max() | max(iterable) | Maximum value | max([1,5,3]) | 5 |
| pow() | pow(x, y) | x raised to power y | pow(2, 3) | 8 |
| sum() | sum(iterable) | Sum of values | sum([1,2,3]) | 6 |
Detailed Examples:
Python
Key Applications:
- abs(): Distance calculations, error handling
- max(): Finding extremes, competition results
- pow(): Scientific calculations, compound interest
- sum(): Total calculations, statistics
Mnemonic: "Math Functions: Absolute, Maximum, Power, Sum"
Question 4(a) [3 marks]
Explain scope of variables.
Answer:
Variable Scope refers to the region where a variable can be accessed in a program.
Scope Types Table:
| Scope | Description | Lifetime | Access |
|---|---|---|---|
| Local | Inside function | Function execution | Function only |
| Global | Outside functions | Program execution | Entire program |
| Built-in | Python keywords | Python session | Everywhere |
Example Code:
Python
Key Rules:
- Local variables: Created inside functions
- Global variables: Accessible throughout program
- LEGB rule: Local → Enclosing → Global → Built-in
Mnemonic: "Scope: Local Lives in Functions, Global Lives Everywhere"
Question 4(b) [4 marks]
Develop a program to create nested LOOP and display numbers.
Answer:
Nested Loop Program:
Python
Nested Loop Structure:
goat
Key Concepts:
- Outer loop: Controls rows/major iterations
- Inner loop: Controls columns/minor iterations
- Execution flow: Inner completes before outer increments
Mnemonic: "Nested Loops: Outer Controls Inner"
Question 4(c) [7 marks]
Write a program to create a list of ODD and EVEN numbers in range of 1 to 50.
Answer:
ODD and EVEN Numbers Program:
Python
Number Classification Table:
| Type | Condition | Range 1-10 | Count (1-50) |
|---|---|---|---|
| ODD | n % 2 != 0 | 1,3,5,7,9 | 25 |
| EVEN | n % 2 == 0 | 2,4,6,8,10 | 25 |
Statistical Analysis:
Python
Key Techniques:
- Modulo operator:
%for remainder check - List comprehension: Concise list creation
- Range function: Generate sequences efficiently
Mnemonic: "Odd/Even: Remainder 1/0 When Divided by 2"
Question 4(a OR) [3 marks]
Explain String Slicing with example.
Answer:
String Slicing extracts parts of a string using [start:stop:step] syntax.
Slicing Syntax Table:
| Syntax | Description | Example | Result |
|---|---|---|---|
s[start:stop] | From start to stop-1 | "hello"[1:4] | "ell" |
s[start:] | From start to end | "hello"[2:] | "llo" |
s[:stop] | From beginning to stop-1 | "hello"[:3] | "hel" |
s[::step] | Every step character | "hello"[::2] | "hlo" |
s[::-1] | Reverse string | "hello"[::-1] | "olleh" |
Example Code:
Python
Key Features:
- Zero-based indexing: Start from 0
- Negative indexing: Count from end (-1)
- Immutable: Original string unchanged
Mnemonic: "Slice: Start, Stop, Step"
Question 4(b OR) [4 marks]
Write a program using user defined function to find the factorial of a given number.
Answer:
Factorial Function Program:
Python
Factorial Table:
| n | Factorial | Calculation |
|---|---|---|
| 0 | 1 | Base case |
| 1 | 1 | Base case |
| 3 | 6 | 3 × 2 × 1 |
| 5 | 120 | 5 × 4 × 3 × 2 × 1 |
Key Concepts:
- Recursion: Function calls itself
- Base case: Stops recursive calls
- User-defined: Custom function creation
Mnemonic: "Factorial: Multiply All Numbers Below"
Question 4(c OR) [7 marks]
Write a user defined function to check whether a sub string is present in a given string.
Answer:
Substring Check Function:
Python
String Methods Table:
| Method | Purpose | Example | Result |
|---|---|---|---|
find() | Find first position | "hello".find("ll") | 2 |
count() | Count occurrences | "hello".count("l") | 2 |
in | Check existence | "ll" in "hello" | True |
index() | Find position (error if not found) | "hello".index("e") | 1 |
Key Features:
- Multiple methods: Different ways to search
- Position tracking: Return index of found substring
- Error handling: Check before processing
Mnemonic: "Substring: Search, Find, Count, Position"
Question 5(a) [3 marks]
Explain how to create and access a List with example.
Answer:
List Creation and Access:
Python
List Access Methods:
| Method | Syntax | Example | Result |
|---|---|---|---|
| Index | list[i] | [1,2,3][1] | 2 |
| Negative | list[-i] | [1,2,3][-1] | 3 |
| Slice | list[start:stop] | [1,2,3,4][1:3] | [2,3] |
Key Features:
- Ordered collection: Elements have positions
- Mutable: Can be modified after creation
- Mixed types: Different data types allowed
Mnemonic: "Lists: Create, Index, Access"
Question 5(b) [4 marks]
List out the operations that can be performed on a LIST. Write a program to create and copy one List into another List.
Answer:
List Operations and Copy Program:
Python
List Operations Table:
| Operation | Method | Example | Result |
|---|---|---|---|
| Add | append() | [1,2].append(3) | [1,2,3] |
| Insert | insert() | [1,3].insert(1,2) | [1,2,3] |
| Remove | remove() | [1,2,3].remove(2) | [1,3] |
| Pop | pop() | [1,2,3].pop() | [1,2] |
Key Concepts:
- Shallow copy: Independent list with same elements
- Deep copy: Needed for nested structures
- Multiple methods: Different copying techniques
Mnemonic: "List Operations: Add, Insert, Remove, Pop, Copy"
Question 5(c) [7 marks]
List and give use of various Built in methods of LIST
Answer:
Built-in List Methods:
Python
List Methods Summary:
| Category | Method | Purpose | Returns | Modifies Original |
|---|---|---|---|---|
| Add | append(x) | Add item to end | None | Yes |
| Add | insert(i,x) | Insert at position | None | Yes |
| Add | extend(list) | Add multiple items | None | Yes |
| Remove | remove(x) | Remove first x | None | Yes |
| Remove | pop(i) | Remove at index | Removed item | Yes |
| Remove | clear() | Remove all | None | Yes |
| Search | index(x) | Find position | Index | No |
| Search | count(x) | Count occurrences | Count | No |
| Sort | sort() | Sort in place | None | Yes |
| Sort | reverse() | Reverse order | None | Yes |
| Copy | copy() | Shallow copy | New list | No |
Practical Examples:
Python
Key Applications:
- Data management: Add, remove, organize items
- Search operations: Find and count elements
- Sorting: Organize data in order
Mnemonic: "List Methods: Add, Remove, Search, Sort, Copy"
Question 5(a OR) [3 marks]
Explain how to create and traverse a string by giving an example.
Answer:
String Creation and Traversal:
Python
Traversal Methods Table:
| Method | Syntax | Use Case |
|---|---|---|
| Direct | for char in string: | Simple character access |
| Index | for i in range(len(s)): | Need position info |
| Enumerate | for i, char in enumerate(s): | Both index and character |
Key Concepts:
- Immutable: Strings cannot be changed
- Iterable: Can loop through characters
- Indexing: Access individual characters
Mnemonic: "Strings: Create, Loop, Access"
Question 5(b OR) [4 marks]
List out the operations that can be performed on a String. Write a code for any 2 operations
Answer:
String Operations:
Python
String Operations Table:
| Category | Operation | Example | Result |
|---|---|---|---|
| Join | Concatenation | "Hello" + " World" | "Hello World" |
| Case | upper() | "hello".upper() | "HELLO" |
| Case | lower() | "HELLO".lower() | "hello" |
| Case | title() | "hello world".title() | "Hello World" |
| Split | split() | "a,b,c".split(",") | ['a','b','c'] |
| Replace | replace() | "hello".replace("l","x") | "hexxo" |
| Strip | strip() | " hello ".strip() | "hello" |
| Find | find() | "hello".find("e") | 1 |
Key Features:
- Immutable: Operations return new strings
- Method chaining: Combine multiple operations
- Flexible: Many built-in operations available
Mnemonic: "String Operations: Join, Case, Split, Find"
Question 5(c OR) [7 marks]
List and give use of various built – in methods of String.
Answer:
Built-in String Methods:
Python
String Methods Classification:
| Category | Methods | Purpose | Example |
|---|---|---|---|
| Case | upper(), lower(), title(), capitalize() | Change case | "hello".upper() → "HELLO" |
| Whitespace | strip(), lstrip(), rstrip() | Remove spaces | " hi ".strip() → "hi" |
| Search | find(), index(), count() | Find substrings | "hello".find("e") → 1 |
| Check | startswith(), endswith() | Test string ends | "hello".startswith("h") → True |
| Type Check | isalpha(), isdigit(), isalnum() | Character types | "123".isdigit() → True |
| Split/Join | split(), join() | Break/combine | "a-b".split("-") → ['a','b'] |
| Replace | replace() | Substitute text | "hi".replace("i","o") → "ho" |
Real-world Examples:
Python
Key Applications:
- Data cleaning: Remove unwanted spaces, fix case
- Text processing: Search, replace, split content
- Validation: Check string format and content
- Formatting: Prepare text for display
Mnemonic: "String Methods: Case, Clean, Check, Change"