Unit 2: Conditionals and Iterations; Functions and Recursion - Subjective Questions
ECE181 — Introduction To Python • Practice Questions with Detailed Answers
20 questions
Define a conditional expression in Python. Explain how the ternary conditional operator works with a suitable example.
A conditional expression (also called a ternary operator) is a compact way to evaluate a condition and return one of two values based on whether the condition is True or False.
Syntax:
python
value_if_true if condition else value_if_false
Key points:
- It is a single-line alternative to the
if-elsestatement. - It always returns a value, making it useful in assignments.
Example:
python
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status) # Output: Adult
Here, since age >= 18 is True, the expression evaluates to "Adult". This makes code concise compared to writing a full multi-line if-else block.
Explain the if statement in Python. Describe its syntax and illustrate with a flowchart-like explanation and an example.
The if statement is used to execute a block of code only when a specified condition evaluates to True.
Syntax:
python
if condition:
statements to execute
Working:
- The condition is evaluated first.
- If it is
True, the indented block runs. - If it is
False, the block is skipped.
Flow of control:
- Start Evaluate condition if True, run block End
- if False, skip block End
Example:
python
num = 10
if num > 0:
print("Positive number")
Output: Positive number
Indentation is crucial in Python as it defines the block of code belonging to the if statement.
Distinguish between a two-way if-else statement and a multi-way if-elif-else statement with examples.
Two-way if-else statement:
- Chooses between exactly two alternatives.
- If the condition is
True, theifblock runs; otherwise theelseblock runs.
num = 7
if num % 2 == 0:
print("Even")
else:
print("Odd")Multi-way if-elif-else statement:
- Handles more than two possible outcomes.
- Conditions are checked sequentially; the first
Truecondition's block runs.
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 60:
print("Grade C")
else:
print("Fail")Key differences:
| Aspect | if-else | if-elif-else |
|---|---|---|
| Branches | Two | Multiple |
| Conditions | One | Several |
| Use case | Binary decisions | Range/category decisions |
What is a nested if statement? Explain with an example where nested conditions are necessary.
A nested if statement is an if (or if-else) statement placed inside another if or else block. It is used when a decision depends on the outcome of a previous decision.
Syntax:
python
if condition1:
if condition2:
statements
else:
# statements
else:
statements
Example: Checking if a number is positive and then whether it is even or odd:
python
num = 8
if num > 0:
if num % 2 == 0:
print("Positive Even")
else:
print("Positive Odd")
else:
print("Not positive")
Output: Positive Even
Key points:
- Inner conditions are only checked if the outer condition is
True. - Proper indentation is essential to define nesting levels.
- Deep nesting reduces readability, so it should be used judiciously.
Explain the for loop in Python. Describe the use of the range() function with examples.
The for loop is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each element.
Syntax:
python
for variable in sequence:
statements
The range() function generates a sequence of numbers and is commonly used with for loops.
range(stop)— from 0 to stop-1range(start, stop)— from start to stop-1range(start, stop, step)— with a specified step
Examples:
python
Iterating over a range
for i in range(1, 6):
print(i, end=" ") # Output: 1 2 3 4 5
Iterating over a string
for ch in "Hi":
print(ch) # Output: H then i
Using step
for i in range(0, 10, 2):
print(i, end=" ") # Output: 0 2 4 6 8
The for loop is ideal when the number of iterations is known in advance.
Describe the while loop in Python. How does it differ from the for loop? Provide an example of each.
The while loop repeatedly executes a block of code as long as a given condition remains True.
Syntax:
python
while condition:
statements
Example (while loop):
python
i = 1
while i <= 5:
print(i, end=" ")
i += 1 # Output: 1 2 3 4 5
Example (for loop):
python
for i in range(1, 6):
print(i, end=" ") # Output: 1 2 3 4 5
Differences:
| Aspect | for loop | while loop |
|---|---|---|
| Use case | Known number of iterations | Unknown iterations, condition-based |
| Counter | Automatic via sequence | Manually updated |
| Risk | Less prone to infinite loop | Can cause infinite loop if condition never becomes False |
Note: In a while loop, forgetting to update the loop variable (e.g., i += 1) leads to an infinite loop.
What are nested loops? Write a program to print the following pattern using nested loops and explain its working.
*
- *
-
- *
-
A nested loop is a loop placed inside the body of another loop. For each iteration of the outer loop, the inner loop executes completely.
Program:
python
rows = 4
for i in range(1, rows + 1):
for j in range(i):
print("*", end=" ")
print() # move to next line
Explanation:
- The outer loop (
i) controls the number of rows, running from 1 to 4. - The inner loop (
j) controls the number of stars printed in each row; it runsitimes. print()after the inner loop moves the cursor to a new line.
Iteration trace:
- Row 1: prints 1 star
- Row 2: prints 2 stars
- Row 3: prints 3 stars
- Row 4: prints 4 stars
Nested loops are commonly used for working with grids, matrices, and pattern printing.
Explain the break and continue statements in Python with suitable examples. How do they alter the flow of loops?
The break and continue statements are loop control statements that change the normal flow of loop execution.
break statement:
- Immediately terminates the loop.
- Control passes to the statement following the loop.
for i in range(1, 10):
if i == 5:
break
print(i, end=" ") # Output: 1 2 3 4continue statement:
- Skips the rest of the current iteration and moves to the next iteration.
for i in range(1, 6):
if i == 3:
continue
print(i, end=" ") # Output: 1 2 4 5Summary:
| Statement | Effect |
|---|---|
break |
Exits the loop entirely |
continue |
Skips to the next iteration |
Both statements are typically used with conditional checks inside loops to handle special cases.
Explain how random numbers are generated in Python using the random module. Describe at least four useful functions with examples.
Python provides the built-in random module to generate pseudo-random numbers, useful in games, simulations, and testing.
Importing the module:
python
import random
Useful functions:
-
random.random()— returns a float in the range .
python
print(random.random()) # e.g., 0.4567 -
random.randint(a, b)— returns a random integer such that .
python
print(random.randint(1, 6)) # e.g., dice roll: 4 -
random.uniform(a, b)— returns a random float betweenaandb.
python
print(random.uniform(1, 10)) # e.g., 6.732 -
random.choice(sequence)— returns a random element from a sequence.
python
print(random.choice(["red", "green", "blue"])) # e.g., green -
random.shuffle(list)— shuffles a list in place.
Note: These are pseudo-random numbers; using random.seed(value) produces reproducible sequences.
What is a function call in Python? Explain the process of calling a function and how values are returned, with an example.
A function call is the process of invoking a defined function by using its name followed by parentheses containing any required arguments.
Syntax:
python
function_name(arguments)
Process:
- The function is defined using the
defkeyword. - When called, control transfers to the function body.
- Arguments are passed to the parameters.
- The function executes its statements.
- A value may be returned using the
returnstatement, and control returns to the calling point.
Example:
python
def add(a, b):
return a + b
result = add(5, 3) # function call
print(result) # Output: 8
Key points:
- If no
returnis specified, the function returnsNone. - Function calls promote code reusability and modularity.
- The returned value can be stored, printed, or used in expressions.
Explain type conversion and type coercion in Python. Distinguish between implicit and explicit type conversion with examples.
Type conversion is the process of converting a value from one data type to another. It is of two kinds:
1. Implicit Type Conversion (Coercion):
- Performed automatically by the Python interpreter.
- Occurs when combining different data types in an operation, converting to the higher (wider) type to avoid data loss.
x = 5 # int
y = 2.0 # float
result = x + y
print(result) # Output: 7.0 (int coerced to float)
print(type(result)) # <class 'float'>2. Explicit Type Conversion (Type Casting):
- Performed manually by the programmer using built-in functions like
int(),float(),str().
a = "100"
b = int(a) # string to integer
print(b + 5) # Output: 105
c = 3.99
print(int(c)) # Output: 3 (truncated)Difference:
| Aspect | Implicit (Coercion) | Explicit (Casting) |
|---|---|---|
| Performed by | Interpreter | Programmer |
| Data loss | Avoided | Possible |
| Functions | None needed | int(), float(), str(), etc. |
Describe the math module in Python. List and explain at least five commonly used math functions with examples.
The math module provides access to mathematical functions and constants defined by the C standard.
Importing:
python
import math
Common functions:
-
math.sqrt(x)— returns the square root of .
python
print(math.sqrt(25)) # Output: 5.0 -
math.pow(x, y)— returns as a float.
python
print(math.pow(2, 3)) # Output: 8.0 -
math.factorial(n)— returns .
python
print(math.factorial(5)) # Output: 120 -
math.ceil(x)andmath.floor(x)— round up and down respectively.
python
print(math.ceil(4.1)) # Output: 5
print(math.floor(4.9)) # Output: 4 -
math.log(x)/math.log10(x)— natural and base-10 logarithms.
python
print(math.log10(1000)) # Output: 3.0
Useful constants:
math.pimath.e
Explain the steps of adding a new function in Python. What are the advantages of using functions in a program?
Adding a new function involves defining it using the def keyword and then calling it wherever needed.
Steps:
- Function definition using
def, a name, and parameters. - Write the function body (indented block).
- Optionally return a value.
- Call the function to use it.
Example:
python
Step 1-3: Define the function
def greet(name):
return "Hello, " + name + "!"
Step 4: Call the function
message = greet("Alice")
print(message) # Output: Hello, Alice!
Advantages of using functions:
- Reusability — write once, use many times.
- Modularity — breaks a large program into smaller, manageable parts.
- Readability — makes code cleaner and easier to understand.
- Easier debugging and maintenance — errors can be isolated.
- Avoids code duplication — reduces redundancy.
Functions are a fundamental building block of structured and organized programming.
Distinguish between parameters and arguments in Python functions. Explain different types of arguments with examples.
Parameters are the variables listed inside the parentheses in the function definition. Arguments are the actual values passed to the function during the function call.
def add(a, b): # a, b are parameters
return a + b
add(5, 3) # 5, 3 are argumentsTypes of arguments:
-
Positional arguments — matched by position/order.
python
def info(name, age):
print(name, age)
info("Tom", 25) # Tom 25 -
Keyword arguments — passed using parameter names.
python
info(age=25, name="Tom") # order doesn't matter -
Default arguments — parameters with default values.
python
def greet(name, msg="Hello"):
print(msg, name)
greet("Sam") # Hello Sam
greet("Sam", "Hi") # Hi Sam -
Variable-length arguments —
*args(tuple) and**kwargs(dictionary).
python
def total(*nums):
return sum(nums)
print(total(1, 2, 3)) # Output: 6
Summary: Parameters are placeholders; arguments are the real data supplied to them.
What is recursion? Explain its key components. Write a recursive function to compute the factorial of a number and explain its working.
Recursion is a programming technique in which a function calls itself to solve a problem by breaking it into smaller subproblems.
Key components of recursion:
- Base case — the condition under which the recursion stops (prevents infinite recursion).
- Recursive case — the part where the function calls itself with a smaller input.
Factorial using recursion:
The factorial is defined mathematically as:
def factorial(n):
if n == 0 or n == 1: # base case
return 1
else: # recursive case
return n * factorial(n - 1)
print(factorial(5)) # Output: 120Working (for n = 5):
factorial(5) = 5 * factorial(4)factorial(4) = 4 * factorial(3)factorial(3) = 3 * factorial(2)factorial(2) = 2 * factorial(1)factorial(1) = 1(base case)
The results are then multiplied back: .
Compare recursion and iteration. Discuss the advantages and disadvantages of recursion, and mention where recursion is preferred.
Recursion solves a problem by having a function call itself, while iteration uses loops (for/while) to repeat a block of code.
Comparison:
| Aspect | Recursion | Iteration |
|---|---|---|
| Definition | Function calls itself | Loop repeats code |
| Memory | Uses call stack (more memory) | Uses less memory |
| Speed | Generally slower (overhead) | Generally faster |
| Termination | Base case | Loop condition |
| Code size | Often shorter, elegant | May be longer |
| Risk | Stack overflow if too deep | Infinite loop if condition fails |
Advantages of recursion:
- Produces clean and elegant code for problems with recursive structure.
- Naturally suited to problems like tree traversal, factorial, Fibonacci, and Tower of Hanoi.
Disadvantages of recursion:
- Consumes more memory due to stack usage.
- Can be slower due to repeated function-call overhead.
- Risk of stack overflow for deep recursion.
Where recursion is preferred:
- Problems that are inherently recursive, such as tree/graph traversal, divide-and-conquer algorithms (merge sort, quick sort), and mathematical definitions like factorials and Fibonacci sequences.
Write a Python program using a while loop to check whether a given number is a prime number. Explain the logic used.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Program:
python
num = int(input("Enter a number: "))
is_prime = True
if num <= 1:
is_prime = False
else:
i = 2
while i <= num // 2:
if num % i == 0:
is_prime = False
break
i += 1
if is_prime:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Logic explanation:
- Numbers less than or equal to 1 are not prime.
- We check for divisors from 2 up to
num // 2. - If any number divides
numevenly (num % i == 0), it is not prime, and webreak. - If no divisor is found, the number is prime.
Optimization: We can loop only up to instead of to make it faster, since a larger factor would pair with a smaller one.
Explain the concept of variable scope in the context of functions. Distinguish between local and global variables with examples.
Variable scope determines the region of a program where a variable is accessible. In functions, scope is mainly classified as local and global.
Local variable:
- Declared inside a function.
- Accessible only within that function.
def my_func():
x = 10 # local variable
print(x)
my_func() # Output: 10
# print(x) # Error: x is not defined outsideGlobal variable:
- Declared outside all functions.
- Accessible throughout the program.
y = 20 # global variable
def show():
print(y) # can read global
show() # Output: 20Using the global keyword to modify a global variable inside a function:
python
count = 0
def increment():
global count
count += 1
increment()
print(count) # Output: 1
Summary:
| Aspect | Local | Global |
|---|---|---|
| Declared | Inside function | Outside functions |
| Scope | Within function | Entire program |
| Lifetime | During function execution | Throughout program |
Write a Python program to generate the Fibonacci series up to terms using recursion, and explain the recursive relation used.
The Fibonacci series is a sequence where each term is the sum of the two preceding terms, starting with 0 and 1:
Recursive relation:
with base cases and .
Program:
python
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
terms = 7
for i in range(terms):
print(fibonacci(i), end=" ")
Output: 0 1 1 2 3 5 8
Explanation:
- The base cases return 0 and 1 for the first two terms.
- For any other term, the function calls itself twice with
n-1andn-2and adds the results. - The loop prints Fibonacci numbers for indices 0 to 6.
Note: This recursive approach has exponential time complexity due to repeated calculations; using memoization or iteration is more efficient.
Explain how logical operators (and, or, not) are used in conditional expressions. Illustrate with a program that uses multiple conditions.
Logical operators are used to combine multiple conditions in if statements and other conditional expressions. Python provides three logical operators:
and— returnsTrueonly if both conditions areTrue.or— returnsTrueif at least one condition isTrue.not— reverses the boolean value of a condition.
Truth table summary:
| A | B | A and B | A or B |
|---|---|---|---|
| T | T | T | T |
| T | F | F | T |
| F | T | F | T |
| F | F | F | F |
Example program: Checking eligibility for voting and driving:
python
age = 20
has_license = True
if age >= 18 and has_license:
print("Eligible to drive")
if age >= 18 or age == 17:
print("Eligible to vote soon or now")
if not has_license:
print("Cannot drive")
else:
print("Has a valid license")
Output:
Eligible to drive
Eligible to vote soon or now
Has a valid license
Logical operators enable building complex decision-making conditions in a concise way.
Define a conditional expression in Python. Explain how the ternary conditional operator works with a suitable example.
A conditional expression (also called a ternary operator) is a compact way to evaluate a condition and return one of two values based on whether the condition is True or False.
Syntax:
python
value_if_true if condition else value_if_false
Key points:
- It is a single-line alternative to the
if-elsestatement. - It always returns a value, making it useful in assignments.
Example:
python
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status) # Output: Adult
Here, since age >= 18 is True, the expression evaluates to "Adult". This makes code concise compared to writing a full multi-line if-else 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 →