Skip to main content
  1. Resources/
  2. Study Materials/
  3. Information Technology Engineering/
  4. IT Semester 1/
  5. Python Programming (4311601)/

Python Programming (4311601) - Winter 2023 Solution

·
Study-Material Solutions Python 4311601 2023 Winter
Milav Dabgar
Author
Milav Dabgar
Experienced lecturer in the electrical and electronic manufacturing industry. Skilled in Embedded Systems, Image Processing, Data Science, MATLAB, Python, STM32. Strong education professional with a Master’s degree in Communication Systems Engineering from L.D. College of Engineering - Ahmedabad.
Table of Contents

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:

SymbolNamePurpose
OvalTerminalStart/End of program
RectangleProcessProcessing/Calculation steps
DiamondDecisionConditional statements
ParallelogramInput/OutputData input or output
CircleConnectorConnect flowchart parts
ArrowFlow lineDirection 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:

ComponentSyntaxExample
Basicfor variable in sequence:for i in range(5):
Rangerange(start, stop, step)range(1, 10, 2)
Listfor item in list:for x in [1,2,3]:
Stringfor char in string:for c in "hello":

Simple Code Example:

for i in range(3):
    print(i)
# Output: 0, 1, 2

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:

# Get number of terms from user
n = int(input("Enter number of terms: "))

# Initialize first two terms
a, b = 0, 1

# Display first term
if n >= 1:
    print(a, end=" ")
    
# Display second term
if n >= 2:
    print(b, end=" ")

# Generate remaining terms
for i in range(2, n):
    c = a + b
    print(c, end=" ")
    a, b = b, c

Algorithm Flow:

flowchart TD
    A[Start] --> B[Input n]
    B --> C{n >= 1?}
    C -->|Yes| D[Print 0]
    C -->|No| H[End]
    D --> E{n >= 2?}
    E -->|Yes| F[Print 1]
    E -->|No| H
    F --> G[Loop i=2 to n-1]
    G --> I[c = a + b]
    I --> J[Print c]
    J --> K[a = b, b = c]
    K --> L{i < n-1?}
    L -->|Yes| G
    L -->|No| H[End]

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:

flowchart TD
    A[Start] --> B[i = 1]
    B --> C{i <= 100?}
    C -->|Yes| D{i % 2 != 0?}
    D -->|Yes| E[Print i]
    D -->|No| F[i = i + 1]
    E --> F
    F --> C
    C -->|No| G[End]

Corresponding Python Code:

for i in range(1, 101):
    if i % 2 != 0:
        print(i, end=" ")

Alternative Method:

for i in range(1, 101, 2):
    print(i, end=" ")

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:

# Input number
num = int(input("Enter a number: "))
temp = num
reverse = 0

# Reverse the number
while temp > 0:
    reverse = reverse * 10 + temp % 10
    temp = temp // 10

# Check palindrome
if num == reverse:
    print(f"{num} is palindrome")
else:
    print(f"{num} is not palindrome")

Algorithm Table:

StepOperationExample (121)
1Get last digit121 % 10 = 1
2Build reverse0*10 + 1 = 1
3Remove last digit121 // 10 = 12
4Repeat until 0Continue 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:

FeatureDescriptionBenefit
Easy SyntaxSimple, readable codeFaster development
InterpretedNo compilation neededQuick testing
Object-OrientedClasses and objects supportCode reusability
Open SourceFree to useNo licensing cost
Cross-PlatformRuns on multiple OSWide compatibility
Large LibrariesExtensive built-in modulesRich 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:

#!/usr/bin/env python3
# Shebang line (optional)

"""
Documentation string (docstring)
Describes program purpose
"""

# Import statements
import math
from datetime import date

# Global variables
PI = 3.14159
count = 0

# Function definitions
def calculate_area(radius):
    """Calculate circle area"""
    return PI * radius * radius

# Class definitions
class Calculator:
    def __init__(self):
        self.result = 0

# Main program execution
if __name__ == "__main__":
    # Program logic here
    radius = 5
    area = calculate_area(radius)
    print(f"Area: {area}")

Structure Components Table:

ComponentPurposeExample
ShebangSystem interpreter#!/usr/bin/env python3
DocstringProgram documentation"""Program description"""
ImportsExternal modulesimport math
VariablesGlobal data storagePI = 3.14159
FunctionsReusable code blocksdef function_name():
ClassesObject templatesclass ClassName:
Main blockProgram executionif __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:

# Method 1: Using slicing
string = input("Enter a string: ")
reversed_string = string[::-1]
print(f"Reversed: {reversed_string}")

# Method 2: Using loop
string = input("Enter a string: ")
reversed_string = ""
for char in string:
    reversed_string = char + reversed_string
print(f"Reversed: {reversed_string}")

Reversal Methods Table:

MethodSyntaxExample
Slicingstring[::-1]“hello” → “olleh”
LoopBuild character by characterAdd 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:

OperatorSymbolDescriptionExampleResult
ANDandBoth conditions trueTrue and FalseFalse
ORorAt least one condition trueTrue or FalseTrue
NOTnotOpposite of conditionnot TrueFalse

Example Code:

a = 10
b = 5

# AND operator
if a > 5 and b < 10:
    print("Both conditions true")

# OR operator  
if a > 15 or b < 10:
    print("At least one condition true")

# NOT operator
if not (a < 5):
    print("a is not less than 5")

Truth Table:

ABA and BA or Bnot A
TTTTF
TFFTF
FTFTT
FFFFT

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:

graph TD
    A[Python Data Types] --> B[Numeric]
    A --> C[Sequence]
    A --> D[Boolean]
    A --> E[Set]
    A --> F[Dictionary]
    B --> G[int]
    B --> H[float]
    B --> I[complex]
    C --> J[str]
    C --> K[list]
    C --> L[tuple]

Data Types Table:

TypeExampleDescriptionMutable
int42Whole numbersNo
float3.14Decimal numbersNo
str"hello"Text dataNo
list[1,2,3]Ordered collectionYes
tuple(1,2,3)Ordered immutableNo
dict{"a":1}Key-value pairsYes
boolTrue/FalseBoolean valuesNo
set{1,2,3}Unique elementsYes

Example Code:

# Numeric types
age = 25          # int
price = 99.99     # float
complex_num = 3+4j # complex

# Sequence types
name = "Python"         # string
numbers = [1,2,3,4]     # list
coordinates = (10,20)   # tuple

# Other types
is_active = True        # boolean
unique_items = {1,2,3}  # set
student = {"name":"John", "age":20}  # dict

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:

TypeStatementPurposeExample
SequentialNormal executionLine by lineprint("Hello")
Selectionif, elif, elseDecision makingif x > 0:
Iterationfor, whileRepetitionfor i in range(5):
Jumpbreak, continueLoop controlbreak

Example Code:

# Selection example
age = 18
if age >= 18:
    print("Adult")
else:
    print("Minor")

# Iteration example
for i in range(3):
    print(f"Count: {i}")

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:

# Grade calculation using nested if
marks = int(input("Enter marks: "))

if marks >= 0 and marks <= 100:
    if marks >= 90:
        grade = "A+"
    elif marks >= 80:
        if marks >= 85:
            grade = "A"
        else:
            grade = "B+"
    elif marks >= 70:
        grade = "B"
    elif marks >= 60:
        grade = "C"
    else:
        grade = "F"
    print(f"Grade: {grade}")
else:
    print("Invalid marks")

Nested Structure Diagram:

marAk+s>=T9r0uem0a<r=kmsa.r.ik.nsp<u=t100FalsIenvalid

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:

# 1. Positional Arguments
def greet(name, age):
    print(f"Hello {name}, you are {age} years old")

greet("John", 25)  # Positional arguments

# 2. Keyword Arguments  
greet(age=30, name="Alice")  # Keyword arguments

# 3. Default Parameters
def introduce(name, city="Unknown"):
    print(f"{name} lives in {city}")

introduce("Bob")  # Uses default value
introduce("Carol", "NYC")  # Override default

# 4. Variable-length Arguments (*args)
def sum_all(*numbers):
    return sum(numbers)

result = sum_all(1, 2, 3, 4, 5)
print(f"Sum: {result}")

# 5. Keyword Variable Arguments (**kwargs)
def display_info(**info):
    for key, value in info.items():
        print(f"{key}: {value}")

display_info(name="David", age=28, city="Boston")

Parameters Types Table:

TypeSyntaxExampleDescription
Positionaldef func(a, b):func(1, 2)Order matters
Keyworddef func(a, b):func(b=2, a=1)Name specified
Defaultdef func(a, b=10):func(5)Default value
*argsdef func(*args):func(1,2,3)Variable positional
**kwargsdef func(**kwargs):func(a=1, b=2)Variable keyword

Function Call Examples:

def example(pos1, pos2, default=100, *args, **kwargs):
    print(f"pos1: {pos1}")
    print(f"pos2: {pos2}")  
    print(f"default: {default}")
    print(f"args: {args}")
    print(f"kwargs: {kwargs}")

example(1, 2, 3, 4, 5, name="test", value=42)

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:

# Break example - exit loop
for i in range(10):
    if i == 5:
        break
    print(i)
# Output: 0, 1, 2, 3, 4

Continue Statement:

# Continue example - skip iteration
for i in range(5):
    if i == 2:
        continue
    print(i)
# Output: 0, 1, 3, 4

Comparison Table:

StatementPurposeActionExample Use
breakExit loopTerminates entire loopExit on condition
continueSkip iterationJump to next iterationSkip 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:

# Method 1: Using nested loops
rows = 5
for i in range(1, rows + 1):
    for j in range(1, i + 1):
        print(j, end="")
    print()  # New line

# Method 2: Using string manipulation
for i in range(1, 6):
    line = ""
    for j in range(1, i + 1):
        line += str(j)
    print(line)

# Method 3: Using join
for i in range(1, 6):
    numbers = [str(j) for j in range(1, i + 1)]
    print("".join(numbers))

Pattern Logic Table:

RowNumbersRangeOutput
111 to 11
21,21 to 212
31,2,31 to 3123
41,2,3,41 to 41234
51,2,3,4,51 to 512345

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:

# 1. abs() - Absolute value
numbers = [-5, 3.7, -10.2, 0]
print("abs() function examples:")
for num in numbers:
    print(f"abs({num}) = {abs(num)}")

# 2. max() - Maximum value
list1 = [4, 7, 2, 9, 1]
print(f"\nmax() function examples:")
print(f"max({list1}) = {max(list1)}")
print(f"max(10, 25, 5) = {max(10, 25, 5)}")
print(f"max('hello') = {max('hello')}")  # Alphabetically

# 3. pow() - Power function
print(f"\npow() function examples:")
print(f"pow(2, 3) = {pow(2, 3)}")      # 2^3 = 8
print(f"pow(5, 2) = {pow(5, 2)}")      # 5^2 = 25
print(f"pow(8, 1/3) = {pow(8, 1/3)}")  # Cube root of 8

# 4. sum() - Sum of sequence
numbers = [1, 2, 3, 4, 5]
print(f"\nsum() function examples:")
print(f"sum({numbers}) = {sum(numbers)}")
print(f"sum({numbers}, 10) = {sum(numbers, 10)}")  # With start value

Functions Summary Table:

FunctionSyntaxPurposeExampleResult
abs()abs(x)Absolute valueabs(-5)5
max()max(iterable)Maximum valuemax([1,5,3])5
pow()pow(x, y)x raised to power ypow(2, 3)8
sum()sum(iterable)Sum of valuessum([1,2,3])6

Detailed Examples:

# Real-world usage
distances = [-10, 15, -8, 12]  # Signed distances
actual_distances = [abs(d) for d in distances]
print(f"Actual distances: {actual_distances}")

scores = [85, 92, 78, 96, 88]
highest_score = max(scores)
total_score = sum(scores)
print(f"Highest: {highest_score}, Total: {total_score}")

# Calculate compound interest
principal = 1000
rate = 0.05
time = 3
amount = principal * pow(1 + rate, time)
print(f"Compound Interest Amount: {amount}")

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:

ScopeDescriptionLifetimeAccess
LocalInside functionFunction executionFunction only
GlobalOutside functionsProgram executionEntire program
Built-inPython keywordsPython sessionEverywhere

Example Code:

x = 10  # Global variable

def my_function():
    y = 20  # Local variable
    print(f"Local y: {y}")
    print(f"Global x: {x}")

my_function()
print(f"Global x: {x}")
# print(y)  # Error: y not accessible here

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:

# Example 1: Number grid
print("Number Grid Pattern:")
for i in range(1, 4):
    for j in range(1, 5):
        print(f"{i}{j}", end=" ")
    print()  # New line after each row

# Example 2: Multiplication table
print("\nMultiplication Table:")
for i in range(1, 4):
    for j in range(1, 6):
        result = i * j
        print(f"{result:3}", end=" ")
    print()

# Example 3: Number pyramid
print("\nNumber Pyramid:")
for i in range(1, 5):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()

Nested Loop Structure:

OIunjtn=eie1irr,=2=LL,o1o32oo,pp4((ij))

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:

# Method 1: Using loops and conditions
odd_numbers = []
even_numbers = []

for i in range(1, 51):
    if i % 2 == 0:
        even_numbers.append(i)
    else:
        odd_numbers.append(i)

print("ODD Numbers (1-50):")
print(odd_numbers)
print(f"Count: {len(odd_numbers)}")

print("\nEVEN Numbers (1-50):")
print(even_numbers)
print(f"Count: {len(even_numbers)}")

# Method 2: Using list comprehension
odd_list = [i for i in range(1, 51) if i % 2 != 0]
even_list = [i for i in range(1, 51) if i % 2 == 0]

print(f"\nOdd (List Comprehension): {odd_list[:10]}...")  # First 10
print(f"Even (List Comprehension): {even_list[:10]}...")  # First 10

# Method 3: Using range with step
odd_range = list(range(1, 51, 2))   # Start 1, step 2
even_range = list(range(2, 51, 2))  # Start 2, step 2

print(f"\nOdd (Range method): {odd_range[:10]}...")
print(f"Even (Range method): {even_range[:10]}...")

Number Classification Table:

TypeConditionRange 1-10Count (1-50)
ODDn % 2 != 01,3,5,7,925
EVENn % 2 == 02,4,6,8,1025

Statistical Analysis:

# Analysis of generated lists
print(f"\nStatistical Analysis:")
print(f"Total numbers: {len(odd_numbers) + len(even_numbers)}")
print(f"Odd percentage: {len(odd_numbers)/50*100}%")
print(f"Even percentage: {len(even_numbers)/50*100}%")
print(f"Largest odd: {max(odd_numbers)}")
print(f"Largest even: {max(even_numbers)}")

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:

SyntaxDescriptionExampleResult
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:

text = "Python Programming"

# Basic slicing
print(f"First 6 chars: {text[:6]}")      # "Python"
print(f"Last 11 chars: {text[7:]}")      # "Programming"
print(f"Middle part: {text[2:8]}")       # "thon P"

# Step slicing
print(f"Every 2nd char: {text[::2]}")    # "Pto rgamn"

# Negative indexing:**
print(f"Last character: {text[-1]}")     # "g"
print(f"Reverse: {text[::-1]}")          # "gnimmargorP nohtyP"

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:

def factorial(n):
    """Calculate factorial using recursion"""
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

def factorial_iterative(n):
    """Calculate factorial using loop"""
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

# Main program
number = int(input("Enter a number: "))
if number < 0:
    print("Factorial not defined for negative numbers")
else:
    result1 = factorial(number)
    result2 = factorial_iterative(number)
    print(f"Factorial of {number} = {result1}")

Factorial Table:

nFactorialCalculation
01Base case
11Base case
363 × 2 × 1
51205 × 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:

def find_substring(main_string, sub_string):
    """Check if substring exists in main string"""
    if sub_string in main_string:
        index = main_string.find(sub_string)
        return True, index
    else:
        return False, -1

def count_substring(main_string, sub_string):
    """Count occurrences of substring"""
    return main_string.count(sub_string)

def find_all_positions(main_string, sub_string):
    """Find all positions of substring"""
    positions = []
    start = 0
    while True:
        pos = main_string.find(sub_string, start)
        if pos == -1:
            break
        positions.append(pos)
        start = pos + 1
    return positions

# Main program
text = input("Enter main string: ")
search = input("Enter substring to search: ")

found, position = find_substring(text, search)
if found:
    print(f"Substring '{search}' found at position {position}")
    count = count_substring(text, search)
    all_pos = find_all_positions(text, search)
    print(f"Total occurrences: {count}")
    print(f"All positions: {all_pos}")
else:
    print(f"Substring '{search}' not found")

String Methods Table:

MethodPurposeExampleResult
find()Find first position"hello".find("ll")2
count()Count occurrences"hello".count("l")2
inCheck 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:

# Creating lists
empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
nested = [[1, 2], [3, 4], [5, 6]]

# Accessing elements
print(f"First element: {numbers[0]}")      # 1
print(f"Last element: {numbers[-1]}")      # 5
print(f"Slice: {numbers[1:4]}")           # [2, 3, 4]

List Access Methods:

MethodSyntaxExampleResult
Indexlist[i][1,2,3][1]2
Negativelist[-i][1,2,3][-1]3
Slicelist[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:

# Original list
original = [1, 2, 3, 4, 5]
print(f"Original list: {original}")

# Copying methods
shallow_copy = original.copy()
slice_copy = original[:]
list_copy = list(original)

# Modify original
original.append(6)
print(f"After append: {original}")
print(f"Shallow copy: {shallow_copy}")

# List operations demonstration
numbers = [10, 20, 30]
numbers.append(40)          # Add to end
numbers.insert(1, 15)       # Insert at position
numbers.remove(20)          # Remove specific value
popped = numbers.pop()      # Remove and return last

List Operations Table:

OperationMethodExampleResult
Addappend()[1,2].append(3)[1,2,3]
Insertinsert()[1,3].insert(1,2)[1,2,3]
Removeremove()[1,2,3].remove(2)[1,3]
Poppop()[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:

# Sample list for demonstrations
fruits = ['apple', 'banana', 'cherry', 'apple']
numbers = [3, 1, 4, 1, 5, 9, 2]

# Modification methods
fruits.append('date')              # Add to end
fruits.insert(1, 'avocado')       # Insert at index
fruits.remove('apple')            # Remove first occurrence
last_fruit = fruits.pop()         # Remove and return last
fruits.clear()                    # Remove all elements

# Search and count methods
fruits = ['apple', 'banana', 'apple', 'cherry']
count = fruits.count('apple')     # Count occurrences
index = fruits.index('banana')    # Find first index

# Sorting and reversing
numbers.sort()                    # Sort in place
numbers.reverse()                 # Reverse in place
sorted_copy = sorted(fruits)      # Return sorted copy

# Extension
more_fruits = ['grape', 'orange']
fruits.extend(more_fruits)        # Add multiple items

List Methods Summary:

CategoryMethodPurposeReturnsModifies Original
Addappend(x)Add item to endNoneYes
Addinsert(i,x)Insert at positionNoneYes
Addextend(list)Add multiple itemsNoneYes
Removeremove(x)Remove first xNoneYes
Removepop(i)Remove at indexRemoved itemYes
Removeclear()Remove allNoneYes
Searchindex(x)Find positionIndexNo
Searchcount(x)Count occurrencesCountNo
Sortsort()Sort in placeNoneYes
Sortreverse()Reverse orderNoneYes
Copycopy()Shallow copyNew listNo

Practical Examples:

# Shopping cart example
cart = []
cart.append('milk')
cart.extend(['bread', 'eggs', 'butter'])
print(f"Items in cart: {len(cart)}")

if 'milk' in cart:
    cart.remove('milk')
    print("Milk removed from cart")

cart.sort()
print(f"Sorted cart: {cart}")

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:

# String creation methods
string1 = "Hello World"        # Double quotes
string2 = 'Python Programming' # Single quotes
string3 = """Multi-line
string example"""              # Triple quotes

# String traversal methods
text = "Python"

# Method 1: Using for loop
for char in text:
    print(char, end=" ")
print()

# Method 2: Using index
for i in range(len(text)):
    print(f"{text[i]} at index {i}")

# Method 3: Using enumerate
for index, char in enumerate(text):
    print(f"Index {index}: {char}")

Traversal Methods Table:

MethodSyntaxUse Case
Directfor char in string:Simple character access
Indexfor i in range(len(s)):Need position info
Enumeratefor 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:

# String operations examples
text = "Python Programming"

# Operation 1: String concatenation and formatting
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
formatted = f"Hello, {full_name}!"
print(f"Concatenation: {full_name}")
print(f"Formatting: {formatted}")

# Operation 2: String case conversion and splitting
sentence = "learn python programming easily"
title_case = sentence.title()
upper_case = sentence.upper()
words = sentence.split()
print(f"Title case: {title_case}")
print(f"Upper case: {upper_case}")
print(f"Split words: {words}")

String Operations Table:

CategoryOperationExampleResult
JoinConcatenation"Hello" + " World"“Hello World”
Caseupper()"hello".upper()“HELLO”
Caselower()"HELLO".lower()“hello”
Casetitle()"hello world".title()“Hello World”
Splitsplit()"a,b,c".split(",")[‘a’,‘b’,‘c’]
Replacereplace()"hello".replace("l","x")“hexxo”
Stripstrip()" hello ".strip()“hello”
Findfind()"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:

# Sample string for demonstration
text = "  Python Programming Language  "
sample = "Hello World Programming"

# Case conversion methods
print(f"Original: '{text}'")
print(f"upper(): {text.upper()}")
print(f"lower(): {text.lower()}")
print(f"title(): {text.title()}")
print(f"capitalize(): {text.capitalize()}")
print(f"swapcase(): 'Hello'.swapcase()}")

# Whitespace methods
print(f"strip(): '{text.strip()}'")
print(f"lstrip(): '{text.lstrip()}'")
print(f"rstrip(): '{text.rstrip()}'")

# Search and check methods
print(f"find('Python'): {text.find('Python')}")
print(f"count('o'): {sample.count('o')}")
print(f"startswith('  Py'): {text.startswith('  Py')}")
print(f"endswith('ge  '): {text.endswith('ge  ')}")

# Character type checking
test_string = "Python123"
print(f"isalpha(): {'Python'.isalpha()}")
print(f"isdigit(): {'123'.isdigit()}")
print(f"isalnum(): {test_string.isalnum()}")

# Split and join methods
words = sample.split()
joined = "-".join(words)
print(f"split(): {words}")
print(f"join(): {joined}")

# Replace method
replaced = sample.replace("World", "Universe")
print(f"replace(): {replaced}")

String Methods Classification:

CategoryMethodsPurposeExample
Caseupper(), lower(), title(), capitalize()Change case"hello".upper() → “HELLO”
Whitespacestrip(), lstrip(), rstrip()Remove spaces" hi ".strip() → “hi”
Searchfind(), index(), count()Find substrings"hello".find("e") → 1
Checkstartswith(), endswith()Test string ends"hello".startswith("h") → True
Type Checkisalpha(), isdigit(), isalnum()Character types"123".isdigit() → True
Split/Joinsplit(), join()Break/combine"a-b".split("-") → [‘a’,‘b’]
Replacereplace()Substitute text"hi".replace("i","o") → “ho”

Real-world Examples:

# Email validation example
email = "  USER@EXAMPLE.COM  "
clean_email = email.strip().lower()
is_valid = "@" in clean_email and "." in clean_email
print(f"Clean email: {clean_email}")
print(f"Valid format: {is_valid}")

# Text processing example
user_input = "python programming"
formatted_title = user_input.title()
word_count = len(user_input.split())
print(f"Formatted: {formatted_title}")
print(f"Word count: {word_count}")

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”

Related

Data Structure with Python (4331601) - Winter 2023 Solution
Study-Material Solutions Data-Structure Python 4331601 2023 Winter
OOPS & Python Programming (4351108) - Winter 2023 Solution
Study-Material Solutions Python Oop 4351108 2023 Winter
Python Programming (4311601) - Summer 2023 Solution
Study-Material Solutions Python 4311601 2023 Summer
Database Management System (1333204) - Winter 2023 Solution
15 mins
Study-Material Solutions Database 1333204 2023 Winter
Fundamentals of Software Development (4331604) - Winter 2023 Solution
Study-Material Solutions Software-Development 4331604 2023 Winter
Digital Communication (4341102) - Winter 2023 Solution
18 mins
Study-Material Solutions Digital-Communication 4341102 2023 Winter