Python Programming (1323203) - Winter 2024 Solution

Solution guide for Python Programming (1323203) Winter 2024 exam

Question 1(a) [3 marks]

Define flowchart and list out the any four symbols of flowchart.

Answer: A flowchart is a diagrammatic representation that uses standard symbols to illustrate the sequence of steps in a process, algorithm, or program.

Common Flowchart Symbols:

SymbolNamePurpose
Oval/Rounded RectangleTerminal/Start/EndIndicates start or end of a process
RectangleProcessRepresents computation or data processing
DiamondDecisionShows conditional branching point
ParallelogramInput/OutputRepresents data input or output

Mnemonic: "TP-DI" (Terminal-Process-Decision-Input/Output)

Question 1(b) [4 marks]

List out various data types in python. Explain any three data types with example.

Answer: Python data types categorize different types of data values.

Data TypeDescriptionExample
IntegerWhole numbers without decimalsx = 10
FloatNumbers with decimal pointsy = 3.14
StringSequence of charactersname = "Python"
BooleanTrue or False valuesis_valid = True
ListOrdered, mutable collectioncolors = ["red", "green"]
TupleOrdered, immutable collectionpoint = (5, 10)
DictionaryKey-value pairsperson = {"name": "John"}
SetUnordered collection of unique itemsunique = {1, 2, 3}

Integer: Represents whole numbers without decimal points.

Python

String: Represents sequence of characters enclosed in quotes.

Python

List: Ordered, mutable collection of items that can be of different types.

Python

Mnemonic: "FIBS-LTDS" (Float-Integer-Boolean-String-List-Tuple-Dictionary-Set)

Question 1(c) [7 marks]

Design a flowchart to calculate the sum of first twenty even natural numbers.

Answer:

Explanation:

  • Initialize variables: Set sum=0, count=0 (to track even numbers found), num=2 (first even number)
  • Loop condition: Continue until we've found 20 even numbers
  • Process: Add current even number to sum
  • Update: Increase counter and move to next even number
  • Output: Print the final sum when loop completes

Mnemonic: "SCNL-20" (Sum-Count-Number-Loop until 20)

Question 1(c) OR [7 marks]

Create an algorithm to print odd numbers between 1 to 20.

Answer:

Algorithm:

  1. Initialize a variable num = 1 (starting with first odd number)
  2. While num ≤ 20, do steps 3-5
  3. Print the value of num
  4. Increment num by 2 (to get next odd number)
  5. Repeat from step 2
  6. End

Diagram:

Code Implementation:

Python

Mnemonic: "SOLO-20" (Start Odd Loop Output until 20)

Question 2(a) [3 marks]

Discuss the membership operator of python.

Answer: Membership operators in Python are used to test if a value or variable exists in a sequence.

Table of Membership Operators:

OperatorDescriptionExampleOutput
inReturns True if a value exists in sequence5 in [1,2,5]True
not inReturns True if a value doesn't exist4 not in [1,2,5]True

Common Usage:

  • Checking if an element exists in a list: if item in my_list:
  • Checking if a key exists in dictionary: if key in my_dict:
  • Checking if a substring exists: if "py" in "python":

Mnemonic: "IM-NOT" (In Membership - NOT in Membership)

Question 2(b) [4 marks]

Explain the need for continue and break statements.

Answer:

StatementPurposeUse CaseExample
breakTerminates the loop immediatelyExit loop when a condition is metFinding an element
continueSkips current iteration and jumps to nextSkip processing for certain valuesFiltering values

Break Statement:

  • Purpose: Immediately exits the loop
  • When to use: When the required condition is achieved and further processing is unnecessary
  • Example: Finding a specific element in a list
Python

Continue Statement:

  • Purpose: Skips the current iteration and proceeds to the next
  • When to use: When certain values should be skipped but the loop should continue
  • Example: Skipping even numbers in a loop
Python

Mnemonic: "BS-CE" (Break Stops, Continue Excepts)

Question 2(c) [7 marks]

Create a program to calculate total and average marks based on four subject marks taken as input from user.

Answer:

Python

Diagram:

Explanation:

  • Input: Get marks for four subjects from user
  • Process: Calculate total by adding all subject marks and average by dividing total by number of subjects
  • Output: Display total and average marks

Mnemonic: "IAPO" (Input-Add-Process-Output)

Question 2(a) OR [3 marks]

Write a short note on assignment operator.

Answer: The assignment operator in Python is used to assign values to variables.

OperatorNameDescriptionExample
=Simple AssignmentAssigns right operand value to left operandx = 10
+=Add ANDAdds right operand to left and assigns resultx += 5 (same as x = x + 5)
-=Subtract ANDSubtracts right operand from left and assignsx -= 3 (same as x = x - 3)
*=Multiply ANDMultiplies left by right and assigns resultx *= 2 (same as x = x * 2)
/=Divide ANDDivides left by right and assigns resultx /= 4 (same as x = x / 4)

Compound assignment operators combine an arithmetic operation with assignment, making code more concise and readable.

Mnemonic: "SAME" (Simple Assignment Makes Easy)

Question 2(b) OR [4 marks]

Explain the use of for loop by giving syntax, flowchart and example.

Answer:

Syntax of For Loop:

Python

Flowchart:

Example:

Python

The for loop in Python is used for definite iteration over a sequence (list, tuple, string, etc.) or other iterable objects. It's particularly useful when you know the number of iterations in advance.

Mnemonic: "SIFE" (Sequence Iteration For Each item)

Question 2(c) OR [7 marks]

Develop a code to find the square and cube of a given number from user.

Answer:

Python

Diagram:

Explanation:

  • Input: Get a number from user
  • Process: Calculate square by raising to power 2, cube by raising to power 3
  • Output: Display the input number, its square and cube

Mnemonic: "ISCO" (Input-Square-Cube-Output)

Question 3(a) [3 marks]

Explain if-elif-else statement with flowchart and suitable example.

Answer: The if-elif-else statement in Python allows for conditional execution where multiple expressions are evaluated.

Flowchart:

Example:

Python

Mnemonic: "CITE" (Check If Then Else)

Question 3(b) [4 marks]

Explain how to define and call user defined function by giving suitable example.

Answer:

Function Definition and Calling:

AspectSyntaxPurpose
Definitiondef function_name(parameters):Creates a reusable block of code
Function BodyIndented code blockContains the function's logic
Return Statementreturn [expression]Sends a value back to the caller
Function Callfunction_name(arguments)Executes the function code

Example of Defining and Calling a Function:

Python

Explanation:

  • Function Definition: Use def keyword followed by function name and parameters
  • Documentation: Optional docstring describing the function
  • Function Body: Code that performs the task
  • Return Statement: Sends result back to caller
  • Function Call: Pass arguments to execute the function

Mnemonic: "DBRCA" (Define-Body-Return-Call-Arguments)

Question 3(c) [7 marks]

Develop a code to find the factorial of a given number.

Answer:

Python

Diagram:

Explanation:

  • Input: Get a number from user
  • Check: Validate if number is negative (factorial not defined), zero (factorial is 1), or positive
  • Process: For positive numbers, multiply factorial by each number from 1 to num
  • Output: Display the factorial result

Mnemonic: "MICE" (Multiply Incrementally, Check Edge-cases)

Question 3(a) OR [3 marks]

Explain nested loop using suitable example.

Answer: A nested loop is a loop inside another loop. The inner loop completes all its iterations for each iteration of the outer loop.

Diagram:

Example:

Python

Mnemonic: "LOFI" (Loop Outside, Finish Inside)

Question 3(b) OR [4 marks]

Explain return statement in function handling.

Answer:

AspectDescriptionExample
PurposeSend value back to callerreturn result
Multiple ReturnsReturn multiple values as tuplereturn x, y, z
Early ExitExit function before endif error: return None
No ReturnFunction returns None by defaultdef show(): print("Hi")

The return statement in Python functions:

  1. Terminates the function execution
  2. Passes a value back to the function caller
  3. Can return multiple values (as tuple)
  4. Is optional (if omitted, function returns None)

Example:

Python

Mnemonic: "TERM" (Terminate Execution, Return Multiple values)

Question 3(c) OR [7 marks]

Create a program to display the following patterns using loop concept

A
AB
ABC
ABCD
ABCDE

Answer:

Python

Diagram:

Explanation:

  • Outer loop: Controls the number of rows (1 to 5)
  • Inner loop: For each row i, prints i characters starting from 'A'
  • Character generation: Using ASCII value conversion (chr(65+j) gives 'A', 'B', etc.)
  • Output formatting: Using end="" to print characters in same line for each row

Mnemonic: "OICE" (Outer-Inner-Character-Endline)

Question 4(a) [3 marks]

Describe following built-in functions with suitable example. i) max() ii) input() iii) pow()

Answer:

FunctionPurposeSyntaxExample
max()Returns largest item in an iterable or largest of two or more argumentsmax(iterable) or max(arg1, arg2, ...)max([1, 5, 3]) returns 5
input()Reads a line from input and returns as stringinput([prompt])input("Enter name: ")
pow()Returns x to power ypow(x, y)pow(2, 3) returns 8

Examples in code:

Python

Mnemonic: "MIP" (Max-Input-Power)

Question 4(b) [4 marks]

Explain slicing of string by giving suitable example.

Answer:

String slicing in Python is used to extract a substring from a string.

Syntax: string[start:end:step]

ParameterDescriptionDefaultExample
startStarting index (inclusive)0"Python"[1:]"ython"
endEnding index (exclusive)Length of string"Python"[:3]"Pyt"
stepIncrement between characters1"Python"[::2]"Pto"

Examples:

Python

Mnemonic: "SES" (Start-End-Step)

Question 4(c) [7 marks]

Create a user defined function which prints cube of all the odd numbers between 1 to 7.

Answer:

Python

Diagram:

Explanation:

  • Function Definition: Create a function to process odd numbers in a range
  • Loop: Iterate through numbers from start to end
  • Condition: Check if number is odd using modulo operator
  • Processing: Calculate cube of odd numbers
  • Output: Display each odd number and its cube

Mnemonic: "FLOOP" (Function-Loop-Odd-Output-Power)

Question 4(a) OR [3 marks]

Explain random module with various functions.

Answer:

The random module in Python provides functions for generating random numbers and making random selections.

FunctionDescriptionExampleResult
random()Returns random float between 0 and 1random.random()0.7134346335849448
randint(a, b)Returns random integer between a and b (inclusive)random.randint(1, 10)7
choice(seq)Returns random element from sequencerandom.choice(['red', 'green', 'blue'])'green'
shuffle(seq)Shuffles a sequence in-placerandom.shuffle(my_list)No return value
sample(seq, k)Returns k unique random elements from sequencerandom.sample(range(1, 30), 5)[3, 12, 21, 7, 25]

Example:

Python

Mnemonic: "RICES" (Random-Integer-Choice-Elements-Shuffle)

Question 4(b) OR [4 marks]

Discuss the following list functions. i. len() ii. sum() iii. sort() iv. index()

Answer:

FunctionPurposeSyntaxExampleOutput
len()Returns number of items in listlen(list)len([1, 2, 3])3
sum()Returns sum of all items in listsum(list)sum([1, 2, 3])6
sort()Sorts list in-placelist.sort()[3, 1, 2].sort()None (modifies original)
index()Returns index of first occurrencelist.index(value)[10, 20, 30].index(20)1

Examples:

Python

Mnemonic: "LSSI" (Length-Sum-Sort-Index)

Question 4(c) OR [7 marks]

Create a user-defined function to print the Fibonacci series of 0 to N numbers. (Where N is an integer number and passed as an argument)

Answer:

Python

Diagram:

Explanation:

  • Input Validation: Check if N is a valid positive integer
  • Initialize Variables: Set first two Fibonacci terms
  • Print Series: Loop to print Fibonacci numbers
  • Update Terms: Calculate next term and shift values for next iteration
  • Termination: Stop when count reaches N

Mnemonic: "FIST" (Fibonacci-Initialize-Shift-Terminate)

Question 5(a) [3 marks]

Explain given string methods: i. count() ii. upper() iii. replace()

Answer:

MethodPurposeSyntaxExampleOutput
count()Counts occurrences of substringstr.count(substring)"hello".count("l")2
upper()Converts string to uppercasestr.upper()"hello".upper()"HELLO"
replace()Replaces all occurrences of a substringstr.replace(old, new)"hello".replace("l", "r")"herro"

Examples:

Python

Mnemonic: "CUR" (Count-Upper-Replace)

Question 5(b) [4 marks]

Explain tuple operation with example.

Answer:

Tuples in Python are ordered, immutable collections enclosed in parentheses.

OperationDescriptionExampleResult
CreationDefine tuple with valuest = (1, 2, 3)Tuple with 3 items
IndexingAccess item by positiont[0]1
SlicingExtract portion of tuplet[1:3](2, 3)
ConcatenationJoin two tuplest1 + t2Combined tuple
RepetitionRepeat tuple elementst * 2Duplicated elements

Examples:

Python

Mnemonic: "ICSM" (Immutable-Create-Slice-Merge)

Question 5(c) [7 marks]

Develop a code to create two set and perform given operations with those created set: i) Union Operation on Sets ii) Intersection Operation on Sets iii) Difference Operation on Sets iv) Symmetric Difference of Two Sets

Answer:

Python

Diagram:

Explanation:

  • Union: All elements from both sets without duplicates (1, 2, 3, 4, 5, 6, 7, 8)
  • Intersection: Common elements in both sets (4, 5)
  • Difference (A-B): Elements in A but not in B (1, 2, 3)
  • Difference (B-A): Elements in B but not in A (6, 7, 8)
  • Symmetric Difference: Elements in either A or B but not in both (1, 2, 3, 6, 7, 8)

Mnemonic: "UIDS" (Union-Intersection-Difference-Symmetric)

Question 5(a) OR [3 marks]

Define list and how it is created in python?

Answer: A list in Python is an ordered, mutable collection of items that can be of different data types, enclosed in square brackets.

Table of List Creation Methods:

MethodDescriptionExample
LiteralCreate using square bracketsmy_list = [1, 2, 3]
ConstructorCreate using list() functionmy_list = list((1, 2, 3))
ComprehensionCreate using a single line expressionmy_list = [x for x in range(5)]
From iterableConvert other iterables to listmy_list = list("abc")
Empty listCreate empty list and append latermy_list = []

Examples:

Python

Mnemonic: "LCMIE" (Literal-Constructor-Mixed-Iterable-Empty)

Question 5(b) OR [4 marks]

Explain dictionary built-in function and methods.

Answer:

Dictionary is a collection of key-value pairs enclosed in curly braces {}.

Function/MethodDescriptionExampleResult
dict()Creates a dictionarydict(name='John', age=25){'name': 'John', 'age': 25}
len()Returns number of itemslen(my_dict)Integer count
keys()Returns view of all keysmy_dict.keys()Dictionary view object
values()Returns view of all valuesmy_dict.values()Dictionary view object
items()Returns view of (key, value) pairsmy_dict.items()Dictionary view object
get()Returns value for key, or defaultmy_dict.get('key', 'default')Value or default
update()Updates dict with keys/values from anothermy_dict.update(other_dict)None (updates in-place)
pop()Removes item with key and returns valuemy_dict.pop('key')Value of removed item

Examples:

Python

Mnemonic: "LKVIGUP" (Length-Keys-Values-Items-Get-Update-Pop)

Question 5(c) OR [7 marks]

Develop python code to create list of prime and non-prime numbers in range 1 to 50.

Answer:

Python

Diagram:

Explanation:

  • Helper Function: is_prime() efficiently checks if a number is prime
  • Optimization: Only checks divisibility up to square root of number
  • Classification: Sort numbers into prime or non-prime lists
  • Output: Display both lists at the end

Prime numbers (from 1 to 50): 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 Non-prime numbers (from 1 to 50): 1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50

Mnemonic: "POEMS" (Prime-Optimization-Efficient-Modulo-Sorting)