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:

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:

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:

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:

Python

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:

Python

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:

Python

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:

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:

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:

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

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:

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:

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:

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:

Python

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:

Python

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:

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:

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

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:

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

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:

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:

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:

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:

Python

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:

Python

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:

Python

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:

Python

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:

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:

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:

Python

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:

Python

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:

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"