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 2024 Solution

·
Study-Material Solutions Python 4311601 2024 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]
#

Define Problem Solving, Algorithm and Pseudo Code.

Answer:

TermDefinition
Problem SolvingSystematic process of finding solutions to complex issues using logical thinking
AlgorithmStep-by-step procedure to solve a problem with finite operations
Pseudo CodeInformal description of program logic using plain English-like syntax
  • Problem Solving: Breaking down complex problems into manageable steps
  • Algorithm: Must be finite, definite, effective, and produce correct output
  • Pseudo Code: Bridge between human language and programming code

Mnemonic: “PAP - Problem, Algorithm, Pseudo”

Question 1(b) [4 marks]
#

Explain various Flowchart Symbols. Design a Flowchart to find maximum number out of two given numbers

Answer:

SymbolShapePurpose
OvalStart/End
RectangleProcess/Action
DiamondDecision
ParallelogramInput/Output

Flowchart for Maximum of Two Numbers:

flowchart TD
    A([Start]) --> B[/Input A, B/]
    B --> C{A > B?}
    C -->|Yes| D[Max = A]
    C -->|No| E[Max = B]
    D --> F[/Display Max/]
    E --> F
    F --> G([End])
  • Start/End: Entry and exit points
  • Input/Output: Data flow operations
  • Decision: Conditional branching
  • Process: Computational steps

Mnemonic: “SIPO - Start, Input, Process, Output”

Question 1(c) [7 marks]
#

List out various arithmetic operators of python. Write Python Code that performs various arithmetic operations.

Answer:

OperatorSymbolExampleResult
Addition+5 + 38
Subtraction-5 - 32
Multiplication*5 * 315
Division/5 / 31.667
Floor Division//5 // 31
Modulus%5 % 32
Exponentiation**5 ** 3125

Code:

a = 10
b = 3
print(f"Addition: {a + b}")
print(f"Subtraction: {a - b}")
print(f"Multiplication: {a * b}")
print(f"Division: {a / b}")
print(f"Floor Division: {a // b}")
print(f"Modulus: {a % b}")
print(f"Power: {a ** b}")

Mnemonic: “Add-Sub-Mul-Div-Floor-Mod-Pow”

Question 1(c OR) [7 marks]
#

List out various comparison operators of python. Write Python Code which performs various comparison operations.

Answer:

OperatorSymbolPurposeExample
Equal==Check equality5 == 3 → False
Not Equal!=Check inequality5 != 3 → True
Greater Than>Check greater5 > 3 → True
Less Than<Check smaller5 < 3 → False
Greater Equal>=Check greater/equal5 >= 3 → True
Less Equal<=Check smaller/equal5 <= 3 → False

Code:

x = 8
y = 5
print(f"Equal: {x == y}")
print(f"Not Equal: {x != y}")
print(f"Greater: {x > y}")
print(f"Less: {x < y}")
print(f"Greater Equal: {x >= y}")
print(f"Less Equal: {x <= y}")

Mnemonic: “Equal-Not-Greater-Less-GreaterEqual-LessEqual”

Question 2(a) [3 marks]
#

Write short note on membership operators.

Answer:

OperatorPurposeExample
inCheck if element exists‘a’ in ‘apple’ → True
not inCheck if element doesn’t exist‘z’ not in ‘apple’ → True
  • in operator: Returns True if element found in sequence
  • not in operator: Returns True if element not found in sequence
  • Usage: Lists, strings, tuples, dictionaries

Mnemonic: “In-Not-In for membership testing”

Question 2(b) [4 marks]
#

Define Python. Write down various applications of Python Programming.

Answer:

Python Definition: High-level, interpreted programming language known for simplicity and readability.

Application AreaExamples
Web DevelopmentDjango, Flask frameworks
Data ScienceNumPy, Pandas, Matplotlib
AI/MLTensorFlow, Scikit-learn
Desktop AppsTkinter, PyQt
Game DevelopmentPygame library
  • Interpreted: No compilation needed
  • Cross-platform: Runs on multiple OS
  • Large libraries: Extensive standard library

Mnemonic: “Web-Data-AI-Desktop-Games”

Question 2(c) [7 marks]
#

Write python program which calculates electricity bill using following details.

Answer:

Table of Rates:

Unit RangeRate per Unit
≤ 100Rs 5.00
101-200Rs 7.50
201-300Rs 10.00
≥ 301Rs 15.00

Code:

units = int(input("Enter consumed units: "))

if units <= 100:
    bill = units * 5.00
elif units <= 200:
    bill = units * 7.50
elif units <= 300:
    bill = units * 10.00
else:
    bill = units * 15.00

print(f"Total Bill: Rs {bill}")
  • Conditional logic: if-elif-else structure
  • Rate calculation: Based on unit slabs
  • User input: Interactive billing system

Mnemonic: “Input-Check-Calculate-Display”

Question 2(a OR) [3 marks]
#

Write short note on identity operators.

Answer:

OperatorPurposeExample
isCheck same objecta is b
is notCheck different objecta is not b
  • is operator: Compares object identity, not values
  • is not operator: Checks if objects are different
  • Memory comparison: Checks same memory location

Mnemonic: “Is-IsNot for object identity”

Question 2(b OR) [4 marks]
#

What is indentation in Python? Explain various features of Python.

Answer:

Indentation: Whitespace at line beginning to define code blocks.

FeatureDescription
Simple SyntaxEasy to read and write
InterpretedNo compilation step
Object-OrientedSupports OOP concepts
Cross-PlatformRuns on multiple OS
Large LibraryExtensive standard library
  • Indentation: Replaces curly braces {}
  • Consistent: Usually 4 spaces per level
  • Mandatory: Creates code structure

Mnemonic: “Simple-Interpreted-Object-Cross-Large”

Question 2(c OR) [7 marks]
#

Write a python program that calculates Student’s class/grade using following details.

Answer:

Grading Table:

PercentageGrade
≥ 70Distinction
60-69First Class
50-59Second Class
35-49Pass Class
< 35Fail

Code:

percentage = float(input("Enter percentage: "))

if percentage >= 70:
    grade = "Distinction"
elif percentage >= 60:
    grade = "First Class"
elif percentage >= 50:
    grade = "Second Class"
elif percentage >= 35:
    grade = "Pass Class"
else:
    grade = "Fail"

print(f"Grade: {grade}")
  • Multiple conditions: Nested if-elif structure
  • Grade assignment: Based on percentage ranges
  • Float input: Handles decimal percentages

Mnemonic: “Distinction-First-Second-Pass-Fail”

Question 3(a) [3 marks]
#

What is Selection Control Statement? List it out.

Answer:

Statement TypePurpose
ifSingle condition check
if-elseTwo-way branching
if-elif-elseMulti-way branching
nested ifConditions within conditions
  • Selection statements: Control program flow based on conditions
  • Boolean evaluation: Uses True/False logic
  • Branching: Different paths of execution

Mnemonic: “If-IfElse-IfElif-Nested”

Question 3(b) [4 marks]
#

Write short note on nested loops.

Answer:

Loop TypeStructure
Outer LoopControls iterations
Inner LoopExecutes completely for each outer iteration
Total IterationsOuter × Inner
  • Nested structure: Loop inside another loop
  • Complete execution: Inner loop finishes before outer continues
  • Pattern creation: Useful for 2D structures

Code Example:

for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")

Mnemonic: “Outer-Inner-Complete-Pattern”

Question 3(c) [7 marks]
#

Write a user-define function that displays all numbers, which are divisible by 4 from 1 to 100.

Answer:

Code:

def display_divisible_by_4():
    print("Numbers divisible by 4 from 1 to 100:")
    for num in range(1, 101):
        if num % 4 == 0:
            print(num, end=" ")
    print()

# Function call
display_divisible_by_4()

Alternative with return:

def get_divisible_by_4():
    return [num for num in range(1, 101) if num % 4 == 0]

result = get_divisible_by_4()
print(result)
  • Function definition: def keyword usage
  • Range function: 1 to 100 iteration
  • Modulus check: num % 4 == 0 condition
  • List comprehension: Alternative approach

Mnemonic: “Define-Range-Check-Display”

Question 3(a OR) [3 marks]
#

What is Repetition Control Statement? List it out.

Answer:

Statement TypePurpose
for loopKnown number of iterations
while loopCondition-based repetition
nested loopLoop within loop
  • Repetition statements: Execute code blocks repeatedly
  • Iteration control: Different methods of looping
  • Loop variables: Track iteration progress

Mnemonic: “For-While-Nested”

Question 3(b OR) [4 marks]
#

Differentiate break and continue statements.

Answer:

Aspectbreakcontinue
PurposeExit loop completelySkip current iteration
ExecutionJumps out of loopJumps to next iteration
UsageTerminate loop earlySkip specific conditions
EffectLoop endsLoop continues

Code Example:

# break example
for i in range(5):
    if i == 3:
        break
    print(i)  # Output: 0, 1, 2

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

Mnemonic: “Break-Exit, Continue-Skip”

Question 3(c OR) [7 marks]
#

Write a user-define function which displays all even numbers from 1 to 100.

Answer:

Code:

def display_even_numbers():
    print("Even numbers from 1 to 100:")
    for num in range(2, 101, 2):
        print(num, end=" ")
    print()

# Alternative method
def display_even_alt():
    even_nums = []
    for num in range(1, 101):
        if num % 2 == 0:
            even_nums.append(num)
    print(even_nums)

# Function call
display_even_numbers()
  • Efficient range: range(2, 101, 2) for even numbers
  • Modulus method: Alternative checking with % 2 == 0
  • Function design: Reusable code block

Mnemonic: “Range-Step-Even-Display”

Question 4(a) [3 marks]
#

Define Function. List out various types of Functions available in Python.

Answer:

Function: Reusable block of code that performs specific task.

Function TypeDescription
Built-inPre-defined functions (print, len)
User-definedCreated by programmer
LambdaAnonymous single-line functions
RecursiveFunctions calling themselves
  • Code reusability: Write once, use many times
  • Modularity: Breaking complex problems into smaller parts
  • Parameters: Input values to functions

Mnemonic: “Built-User-Lambda-Recursive”

Question 4(b) [4 marks]
#

Write short note on Scope of a variable.

Answer:

Scope TypeDescriptionExample
LocalInside function onlyFunction variables
GlobalThroughout programModule-level variables
Built-inPython keywordsprint, len, type

Code Example:

x = 10  # Global variable

def my_function():
    y = 20  # Local variable
    print(x)  # Access global
    print(y)  # Access local

my_function()
# print(y)  # Error: y not accessible
  • Variable accessibility: Where variables can be used
  • LEGB rule: Local, Enclosing, Global, Built-in

Mnemonic: “Local-Global-Builtin”

Question 4(c) [7 marks]
#

Write Python code which asks user for Main string and Substring and checks membership of a Substring in the Main String.

Answer:

Code:

def check_substring():
    main_string = input("Enter main string: ")
    substring = input("Enter substring: ")
    
    if substring in main_string:
        print(f"'{substring}' found in '{main_string}'")
        print(f"Position: {main_string.find(substring)}")
    else:
        print(f"'{substring}' not found in '{main_string}'")

# Enhanced version with case handling
def check_substring_enhanced():
    main_string = input("Enter main string: ")
    substring = input("Enter substring: ")
    
    if substring.lower() in main_string.lower():
        print("Substring found (case-insensitive)")
    else:
        print("Substring not found")

check_substring()
  • User interaction: input() for string collection
  • Membership testing: ‘in’ operator usage
  • Case sensitivity: Optional case handling

Mnemonic: “Input-Check-Report-Position”

Question 4(a OR) [3 marks]
#

What is Local variable and Global variable?

Answer:

Variable TypeScopeLifetimeAccess
LocalFunction onlyFunction executionLimited
GlobalEntire programProgram executionWidespread

Example:

global_var = 100  # Global

def function():
    local_var = 50  # Local
    print(global_var)  # ✓ Accessible
    print(local_var)   # ✓ Accessible

print(global_var)  # ✓ Accessible
# print(local_var)  # ✗ Error
  • Local variables: Created inside functions
  • Global variables: Created outside functions

Mnemonic: “Local-Limited, Global-Everywhere”

Question 4(b OR) [4 marks]
#

Explain any four built-in functions of Python.

Answer:

FunctionPurposeExample
len()Returns lengthlen(“hello”) → 5
type()Returns data typetype(10) → <class ‘int’>
input()Gets user inputname = input(“Name: “)
print()Displays outputprint(“Hello”)

Additional Examples:

# len() function
print(len([1, 2, 3, 4]))  # Output: 4

# type() function  
print(type(3.14))  # Output: <class 'float'>

# input() function
age = input("Enter age: ")

# print() function
print("Your age is:", age)

Mnemonic: “Length-Type-Input-Print”

Question 4(c OR) [7 marks]
#

Write Python code which locates a substring in a given string.

Answer:

Code:

def locate_substring():
    main_string = input("Enter main string: ")
    substring = input("Enter substring to find: ")
    
    # Method 1: Using find()
    position = main_string.find(substring)
    if position != -1:
        print(f"Found at index: {position}")
    else:
        print("Substring not found")
    
    # Method 2: Using index() with exception handling
    try:
        position = main_string.index(substring)
        print(f"Located at index: {position}")
    except ValueError:
        print("Substring not found")
    
    # Method 3: Find all occurrences
    positions = []
    start = 0
    while True:
        pos = main_string.find(substring, start)
        if pos == -1:
            break
        positions.append(pos)
        start = pos + 1
    
    if positions:
        print(f"All positions: {positions}")

locate_substring()
  • find() method: Returns index or -1
  • index() method: Returns index or raises exception
  • Multiple occurrences: Loop to find all positions

Mnemonic: “Find-Index-Exception-Multiple”

Question 5(a) [3 marks]
#

Define String. List out various string operations.

Answer:

String: Sequence of characters enclosed in quotes.

OperationMethodExample
Concatenation+“Hello” + “World”
Repetition*“Hi” * 3
Slicing[start:end]“Hello”[1:4]
Lengthlen()len(“Hello”)
Caseupper(), lower()“hello”.upper()
  • Immutable: Strings cannot be changed after creation
  • Indexing: Access individual characters
  • Methods: Built-in functions for manipulation

Mnemonic: “Concat-Repeat-Slice-Length-Case”

Question 5(b) [4 marks]
#

How can we identify whether an element is a member of a list or not? Explain with a suitable example.

Answer:

MethodOperatorReturns
inelement in listTrue/False
not inelement not in listTrue/False
count()list.count(element)Number of occurrences

Example:

fruits = ["apple", "banana", "orange", "mango"]

# Using 'in' operator
if "apple" in fruits:
    print("Apple is available")

# Using 'not in' operator  
if "grapes" not in fruits:
    print("Grapes not available")

# Using count() method
count = fruits.count("apple")
if count > 0:
    print(f"Apple found {count} times")
  • Boolean result: True if found, False otherwise
  • Case sensitive: “Apple” ≠ “apple”
  • Efficiency: ‘in’ operator is most common

Mnemonic: “In-NotIn-Count for membership”

Question 5(c) [7 marks]
#

Write Python code that replaces a substring with another substring of a given string. Consider the given string as ‘Welcome to GTU’ and replace the substring ‘GTU’ with ‘Gujarat Technological University’.

Answer:

Code:

def replace_substring():
    # Given string
    original = "Welcome to GTU"
    old_substring = "GTU"
    new_substring = "Gujarat Technological University"
    
    # Method 1: Using replace()
    result1 = original.replace(old_substring, new_substring)
    print(f"Original: {original}")
    print(f"Modified: {result1}")
    
    # Method 2: Manual replacement
    if old_substring in original:
        index = original.find(old_substring)
        result2 = original[:index] + new_substring + original[index + len(old_substring):]
        print(f"Manual method: {result2}")
    
    # Method 3: Replace all occurrences
    test_string = "GTU offers GTU degree from GTU"
    result3 = test_string.replace("GTU", "Gujarat Technological University")
    print(f"Multiple replacements: {result3}")

replace_substring()

Output:

Original: Welcome to GTU
Modified: Welcome to Gujarat Technological University
  • replace() method: Built-in string function
  • Slicing method: Manual string manipulation
  • All occurrences: Replaces every instance

Mnemonic: “Find-Replace-Slice-All”

Question 5(a OR) [3 marks]
#

Define List. List out various list operations.

Answer:

List: Ordered collection of items that can be modified.

OperationMethodExample
Addappend(), insert()list.append(item)
Removeremove(), pop()list.remove(item)
Access[index]list[0]
Slice[start:end]list[1:3]
Sortsort()list.sort()
  • Mutable: Lists can be changed after creation
  • Indexed: Elements accessed by position
  • Dynamic: Size can grow or shrink

Mnemonic: “Add-Remove-Access-Slice-Sort”

Question 5(b OR) [4 marks]
#

Write short note on String Slicing. Explain with suitable example.

Answer:

String Slicing: Extracting parts of string using [start🔚step].

SyntaxDescriptionExample
[start:]From start to end“Hello”[1:] → “ello”
[:end]From beginning to end“Hello”[:3] → “Hel”
[start:end]Specific range“Hello”[1:4] → “ell”
[::-1]Reverse string“Hello”[::-1] → “olleH”

Example:

text = "Python Programming"

print(text[0:6])    # "Python"
print(text[7:])     # "Programming"  
print(text[:6])     # "Python"
print(text[::2])    # "Pto rgamn"
print(text[::-1])   # "gnimmargorP nohtyP"
  • Negative indexing: -1 for last character
  • Step parameter: Controls increment

Mnemonic: “Start-End-Step for slicing”

Question 5(c OR) [7 marks]
#

Write Python code which counts the number of times the specified element appears in the list.

Answer:

Code:

def count_element_occurrences():
    # Create a sample list
    numbers = [1, 2, 3, 2, 4, 2, 5, 2, 6]
    element = int(input("Enter element to count: "))
    
    # Method 1: Using count() method
    count1 = numbers.count(element)
    print(f"Using count(): {element} appears {count1} times")
    
    # Method 2: Manual counting
    count2 = 0
    for num in numbers:
        if num == element:
            count2 += 1
    print(f"Manual count: {element} appears {count2} times")
    
    # Method 3: List comprehension
    count3 = len([x for x in numbers if x == element])
    print(f"List comprehension: {element} appears {count3} times")
    
    # Method 4: For any type of list
    mixed_list = [1, "hello", 3.14, "hello", True, "hello"]
    element_str = input("Enter element to search in mixed list: ")
    count4 = mixed_list.count(element_str)
    print(f"In mixed list: '{element_str}' appears {count4} times")

count_element_occurrences()
  • count() method: Built-in list function
  • Manual iteration: Using loops for counting
  • List comprehension: Pythonic way of counting
  • Type flexibility: Works with any data type

Mnemonic: “Count-Manual-Comprehension-Flexible”

Related

Data Structure with Python (4331601) - Winter 2024 Solution
Study-Material Solutions Data-Structure Python 4331601 2024 Winter
OOPS & Python Programming (4351108) - Winter 2024 Solution
Study-Material Solutions Python Oops 4351108 2024 Winter
Python Programming (4311601) - Summer 2024 Solution
Study-Material Solutions Python 4311601 2024 Summer
Python Programming (4311601) - Winter 2023 Solution
Study-Material Solutions Python 4311601 2023 Winter
Fundamentals of Electrical Engineering (DI01000101) - Winter 2024 Solution
17 mins
Study-Material Solutions Electrical-Engineering DI01000101 2024 Winter
Digital Electronics (4321102) - Winter 2024 Solution
21 mins
Study-Material Solutions Digital-Electronics 4321102 2024 Winter