Unit 2: Control Flow, Functions, and Problem-Solving - Subjective Questions
CSR101 — Python Programming • Practice Questions with Detailed Answers
20 questions
Explain the use of conditional statements in Python. Describe the syntax and working of if, if-else, and if-elif-else statements with suitable examples.
Conditional statements allow a program to make decisions based on whether a condition is true or false.
- The
ifstatement executes a block only when its condition is true. - The
if-elsestatement selects one of two blocks. - The
if-elif-elsestructure tests multiple conditions in sequence.
Example:
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
In an if-elif-else statement, Python evaluates conditions from top to bottom and executes the first true block. Indentation is essential because it defines the statement block.
Compare for loops and while loops in Python. Explain when each type of loop is appropriate and provide an example of both.
Comparison of loops:
- A
forloop is generally used when iterating over a sequence or when the number of iterations is known. - A
whileloop is used when repetition should continue until a condition becomes false. - A
forloop automatically obtains values from an iterable. - A
whileloop requires explicit initialization and updating of the control variable.
Example of a for loop:
for number in range(1, 4):
print(number)
Example of a while loop:
count = 1
while count <= 3:
print(count)
count += 1
The loop condition in a while loop must eventually become false to avoid an infinite loop.
Explain nested loops in Python. Develop a program using nested loops to print a rectangular pattern of stars and describe how the program works.
A nested loop is a loop placed inside another loop. The inner loop completes all its iterations for each iteration of the outer loop.
Example:
rows = 3
columns = 4
for i in range(rows):
for j in range(columns):
print("*", end=" ")
print()
Output:
* * * *
* * * *
* * * *
The outer loop controls the number of rows. The inner loop controls the number of stars in each row. Nested loops are useful for processing tables, matrices, patterns, and combinations of values.
Distinguish between the break and continue statements in Python. Illustrate both using a suitable loop example.
The break statement immediately terminates the nearest enclosing loop. Program execution continues with the statement after the loop.
The continue statement skips the remaining statements in the current iteration and begins the next iteration of the loop.
Example:
for number in range(1, 6):
if number == 3:
continue
if number == 5:
break
print(number)
Output:
1
2
4
Here, continue skips printing 3, while break stops the loop when number becomes 5. Both statements should be used carefully because excessive use can make program logic difficult to follow.
Explain the range() function in Python. Describe its different forms and show how it can be used for counting in ascending and descending order.
The range() function generates a sequence of integers, commonly used with for loops. Its general forms are:
range(stop)generates values from0tostop - 1.range(start, stop)generates values fromstarttostop - 1.range(start, stop, step)changes the difference between consecutive values.
Examples:
for i in range(5):
print(i)
This prints 0 through 4.
for i in range(2, 7):
print(i)
This prints 2 through 6.
for i in range(10, 0, -2):
print(i)
This prints 10, 8, 6, 4, and 2. The stop value is never included, and a zero step is invalid.
Design an algorithm and write Python code to count the number of vowels, consonants, digits, and spaces in a given string.
An algorithm for this problem is:
- Read the input string.
- Initialize counters for vowels, consonants, digits, and spaces to zero.
- Examine each character using a loop.
- If the character is a vowel, increment the vowel counter.
- Otherwise, if it is an alphabetic character, count it as a consonant.
- If it is a digit or space, update the corresponding counter.
- Display all counters.
Python implementation:
text = input("Enter a string: ")
vowels = 0
consonants = 0
digits = 0
spaces = 0
for char in text.lower():
if char in "aeiou":
vowels += 1
elif char.isalpha():
consonants += 1
elif char.isdigit():
digits += 1
elif char.isspace():
spaces += 1
print(vowels, consonants, digits, spaces)
The algorithm takes time, where is the length of the string.
Define a function in Python and explain its advantages. Describe parameters, arguments, local variables, and the role of the return statement with examples.
A function is a named, reusable block of code that performs a specific task. It is defined using the def keyword.
Example:
def calculate_area(length, width):
area = length * width
return area
result = calculate_area(5, 3)
In this example:
lengthandwidthare parameters.5and3are arguments supplied during the function call.areais a local variable because it is created inside the function.returnsends a result back to the calling code.
Functions improve modularity, code reuse, readability, testing, and maintenance. A function without an explicit return statement returns None by default.
Explain positional arguments, keyword arguments, default arguments, and variable-length arguments in Python functions with suitable examples.
Python supports several ways to pass arguments to functions.
-
Positional arguments: Values are matched according to their order.
def subtract(a, b):
return a - b
subtract(10, 3) -
Keyword arguments: Values are passed using parameter names.
subtract(a=10, b=3)
-
Default arguments: A parameter has a predefined value.
def greet(name, message="Welcome"):
return message + ", " + name -
Variable-length positional arguments:
*argscollects extra positional arguments into a tuple.def total(*numbers):
return sum(numbers) -
Variable-length keyword arguments:
**kwargscollects extra keyword arguments into a dictionary.def show_details(**details):
return details
These mechanisms make functions flexible and reusable.
Explain recursion in Python. Write a recursive function to calculate the factorial of a non-negative integer and identify its base case and recursive case.
Recursion is a technique in which a function calls itself to solve a smaller version of the same problem. Every recursive function must contain:
- A base case, which stops further calls.
- A recursive case, which reduces the problem toward the base case.
The factorial of a non-negative integer is defined as , with .
Python implementation:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
For factorial(4), the calls are evaluated as .
The condition n == 0 is the base case. The expression n * factorial(n - 1) is the recursive case. Without a valid base case, recursion can continue until a recursion error occurs.
What is a lambda function in Python? Compare lambda functions with ordinary functions and demonstrate their use with a sorting or mapping operation.
A lambda function is a small anonymous function written using the lambda keyword. It can contain any number of arguments but only one expression.
Syntax:
lambda arguments: expression
Example:
square = lambda x: x * x
print(square(5))
The same operation using an ordinary function is:
def square(x):
return x * x
Lambda functions are often used as short callback functions. For example:
students = [("Ana", 82), ("Ben", 75), ("Cara", 91)]
students.sort(key=lambda item: item[1])
Here, the list is sorted according to each student's score. Ordinary functions are generally preferable when logic is long, complex, or needs documentation.
Explain string indexing and slicing in Python. Describe positive and negative indices and write expressions to extract substrings, reverse a string, and select characters at intervals.
Strings are sequences of characters, and each character has an index. Positive indexing starts at 0 from the left, while negative indexing starts at -1 from the right.
For text = "Python":
text[0]gives"P".text[-1]gives"n".text[1:4]gives"yth".text[:3]gives"Pyt".text[2:]gives"thon".text[::2]selects every second character.text[::-1]reverses the string.
The general slicing form is sequence[start:stop:step]. The start index is included, but the stop index is excluded. Slicing normally creates a new string and does not modify the original string because strings are immutable.
Describe important Python string methods. Explain the purpose of methods such as lower(), upper(), strip(), replace(), find(), startswith(), and endswith() with examples.
Python provides many methods for processing strings.
lower()converts letters to lowercase:"Hello".lower()gives"hello".upper()converts letters to uppercase.strip()removes leading and trailing whitespace.replace(old, new)substitutes one substring for another.find(sub)returns the first index of a substring, or-1if it is absent.startswith(prefix)tests whether a string begins with a specified prefix.endswith(suffix)tests whether a string ends with a specified suffix.
Example:
value = " Python Programming "
cleaned = value.strip().lower()
changed = cleaned.replace("python", "java")
String methods generally return a new string because strings are immutable. Methods such as startswith() and endswith() return Boolean values.
Explain how strings are split and joined in Python. Write a program that accepts a comma-separated list of names, removes extra spaces, and produces a hyphen-separated string.
The split() method divides a string into a list using a separator. If no separator is specified, whitespace is used.
The join() method combines the elements of an iterable into one string using the calling string as the separator.
Program:
data = input("Enter names separated by commas: ")
names = data.split(",")
cleaned_names = []
for name in names:
cleaned_names.append(name.strip())
result = "-".join(cleaned_names)
print(result)
For input " Ana, Ben, Cara ", the output is "Ana-Ben-Cara".
split() is useful for parsing input, while join() is useful for constructing formatted output. The elements passed to join() must be strings.
Explain advanced string formatting in Python using f-strings and the format() method. Include examples involving alignment, decimal precision, and formatted expressions.
Python supports flexible string formatting through f-strings and the format() method.
An f-string places expressions inside braces:
name = "Ravi"
score = 87.456
print(f"{name} scored {score:.2f} marks")
The output is Ravi scored 87.46 marks because .2f formats the number to two decimal places.
Alignment and width can also be specified:
print(f"{name:<10} | {score:>8.2f}")
Here, < aligns text to the left and > aligns it to the right.
The format() method provides another approach:
message = "Student: {}, Score: {:.1f}".format(name, score)
Formatting improves readability and is useful for reports, tables, currency values, percentages, and numerical output.
Differentiate between string concatenation, f-string formatting, and the format() method. Discuss the advantages and limitations of each approach.
String concatenation combines strings using the + operator:
message = "Hello, " + name
It is simple but can become difficult to read when many values or conversions are required.
F-strings use expressions inside braces:
message = f"Hello, {name}. You are {age} years old."
They are concise, readable, and support formatting expressions directly.
The format() method uses placeholders:
message = "Hello, {}. You are {} years old.".format(name, age)
It is flexible and remains useful in code that supports older Python versions.
Concatenation may require explicit conversion using str(). F-strings require a modern Python version, while format() can be more verbose. All three approaches create a new string rather than modifying the original.
What are regular expressions? Explain the roles of the re module, character classes, quantifiers, anchors, and the search() and findall() functions with examples.
A regular expression, or regex, is a pattern used to search, validate, and extract parts of text. Python provides regex support through the re module.
Important regex components include:
- Character classes such as
[A-Z],[0-9], and\\d. - Quantifiers such as
*,+,?, and{m,n}. - Anchors such as
^for the beginning and$for the end. re.search()to find the first matching location.re.findall()to return all non-overlapping matches.
Example:
import re
text = "Order numbers: 125, 340, and 78"
numbers = re.findall(r"\\d+", text)
print(numbers)
The result is ['125', '340', '78']. Raw strings such as r"\\d+" are commonly used so that backslashes in patterns are handled clearly.
Develop a regular expression-based Python program to validate a simple email address. Explain the pattern and discuss why regular expressions alone may not guarantee that an email address is fully valid.
A simple email validation program can be written as follows:
import re
pattern = r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
email = input("Enter an email address: ")
if re.fullmatch(pattern, email):
print("Valid format")
else:
print("Invalid format")
Explanation of the pattern:
^and$require the pattern to cover the entire string.[A-Za-z0-9._%+-]+matches the username part.@matches the separator.[A-Za-z0-9.-]+matches the domain.\\.matches a literal dot.[A-Za-z]{2,}requires a domain suffix of at least two letters.
This checks a common format, but real email validation is more complex. A syntactically matching address may not exist, and only confirmation through email communication can establish that it is usable.
Explain algorithmic thinking and describe how decomposition, pattern recognition, abstraction, and step-by-step algorithm design help solve programming problems.
Algorithmic thinking is the systematic process of developing a precise solution to a problem before or while writing code.
Its main components are:
- Decomposition: Break a large problem into smaller, manageable tasks.
- Pattern recognition: Identify similarities with previously solved problems.
- Abstraction: Ignore irrelevant details and focus on important information.
- Algorithm design: Write an ordered sequence of unambiguous steps.
- Evaluation: Test the solution using normal, boundary, and invalid inputs.
For example, to find the largest value in a list, initialize the first element as the largest, compare each remaining element with it, update when a larger value is found, and finally return the stored value. This approach converts an informal problem into clear operations that can be implemented and tested.
Write and explain a Python program to find the largest, smallest, and average values in a list of numbers without using built-in max(), min(), or sum() functions.
The algorithm maintains running values while traversing the list once.
numbers = [12, 5, 18, 7, 10]
largest = numbers[0]
smallest = numbers[0]
total = 0
count = 0
for number in numbers:
if number > largest:
largest = number
if number < smallest:
smallest = number
total += number
count += 1
average = total / count
print(f"Largest: {largest}")
print(f"Smallest: {smallest}")
print(f"Average: {average:.2f}")
The first element initializes the largest and smallest values. Each later element is compared with them. The variables total and count are used to calculate the average. The time complexity is and the additional space complexity is , excluding the input list.
Design an algorithm and write a Python function to determine whether a given string is a palindrome. Explain how string slicing and a loop-based approach can both solve the problem.
A palindrome reads the same from left to right and right to left, ignoring or including case and spaces according to the problem requirements.
Using slicing:
def is_palindrome(text):
cleaned = text.lower().replace(" ", "")
return cleaned == cleaned[::-1]
print(is_palindrome("Never odd or even"))
A loop-based approach compares characters at opposite ends:
def is_palindrome_loop(text):
cleaned = text.lower().replace(" ", "")
left = 0
right = len(cleaned) - 1
while left < right:
if cleaned[left] != cleaned[right]:
return False
left += 1
right -= 1
return True
The slicing method is concise but creates a reversed copy. The loop-based method can stop early when a mismatch is found and uses constant additional space.
Explain the use of conditional statements in Python. Describe the syntax and working of if, if-else, and if-elif-else statements with suitable examples.
Conditional statements allow a program to make decisions based on whether a condition is true or false.
- The
ifstatement executes a block only when its condition is true. - The
if-elsestatement selects one of two blocks. - The
if-elif-elsestructure tests multiple conditions in sequence.
Example:
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
In an if-elif-else statement, Python evaluates conditions from top to bottom and executes the first true block. Indentation is essential because it defines the statement block.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →