PYTHON PROGRAMMING (BCC402)
Unit 2 Important Question Bank & Complete Solutions
Q1. Explore the working of while and for loops with examples.
Loops are control flow structures used to repeatedly execute blocks of code:
• for Loop: Iterates over a sequence (list, string, tuple, range) automatically step-by-step until the
sequence is fully exhausted.
• while Loop: Executes continuously as long as a specified test condition evaluates to True .
Requires manual loop variable modification inside the block to avoid infinite execution.
# for loop example
for fruit in ["apple", "banana"]:
print("Fruit:", fruit)
# while loop example
count = 1
while count <= 2:
print("Count:", count)
count += 1
Q2. Describe the behavior of range(start, stop) in Python.
The built-in range(start, stop) generates an immutable sequence of integers:
• start (Inclusive): The starting number of the sequence. Defaults to 0 if only a single argument is
passed.
• stop (Exclusive): The boundary value where the loop terminates. The actual value of stop is never
included in the sequence.
# Generates numbers from 5 to 9 (10 is excluded)
for i in range(5, 10):
print(i, end=" ") # Output: 5 6 7 8 9
Python Programming (BCC402) | Unit 2 Question Bank Page 1 of 9
Q3. Explain the role of precedence with an example.
Operator Precedence dictates the specific execution order in expressions containing multiple operators.
Operators with higher precedence are evaluated before lower ones.
# Evaluated as: 2 + (3 * 4) = 14
result1 = 2 + 3 * 4
# Parentheses override precedence: (2 + 3) * 4 = 20
result2 = (2 + 3) * 4
print("Result 1:", result1)
print("Result 2:", result2)
Q4. Demonstrate five different built-in functions used in string operations. Write a
program to check whether a string is a palindrome.
Five String Functions:
1. upper() : Converts all characters to uppercase.
2. lower() : Converts all characters to lowercase.
3. strip() : Removes leading/trailing whitespaces.
4. replace(old, new) : Replaces substrings.
5. split(sep) : Splits a string into a list of substrings.
def is_palindrome(text):
cleaned = [Link](" ", "").lower()
return cleaned == cleaned[::-1] # Slicing step -1 reverses it
print(is_palindrome("radar")) # True
Python Programming (BCC402) | Unit 2 Question Bank Page 2 of 9
Q5. Explain for and while loops with flow diagrams and examples.
for loop logic: Initializes iteration pointing to a sequence index. Evaluates if the index bounds are
completed. If yes, it exits; otherwise, it executes code, increments the index, and repeats.
for num in [1, 2, 3]:
print(num)
while loop logic: Evaluates entry expression conditions. If True , loop statements run, and control loops
back to evaluate the conditional expression again. When it evaluates to False , execution jumps outside.
val = 3
while val > 0:
print(val)
val -= 1
Q6. Explain continue, break, and pass statements with examples.
• break : Terminates the active loop completely and jumps directly out.
• continue : Skips all remaining lines in the current loop iteration and proceeds immediately to the next
cycle.
• pass : A null placeholder that does absolutely nothing; used to construct syntactically valid empty
code blocks.
# break example
for i in range(1, 10):
if i == 4: break
print(i, end=" ") # Output: 1 2 3
# continue example
for i in range(1, 4):
if i == 2: continue
print(i, end=" ") # Output: 1 3
Python Programming (BCC402) | Unit 2 Question Bank Page 3 of 9
Q7. Develop a program to calculate the reverse of an entered number.
def reverse_number(num):
reverse = 0
temp = num
while temp > 0:
remainder = temp % 10
reverse = (reverse * 10) + remainder
temp //= 10
return reverse
print("Reversed:", reverse_number(1234)) # Output: 4321
Q8. Write the structure of if-else statements in Python.
In Python, scopes are defined strictly using colons ( : ) and indentation levels:
if condition_1:
# Runs if condition_1 is True
statement_block_1
elif condition_2:
# Runs if condition_1 is False AND condition_2 is True
statement_block_2
else:
# Runs if all preceding conditions are False
statement_block_3
Q9. Describe recursion. Write a program to generate the Fibonacci series.
Recursion is an algorithmic concept where a function solves a problem by calling copies of itself with
smaller parameters, continuing until it triggers a terminating base case.
def fibonacci(n):
if n == 0: return 0
elif n == 1: return 1
else: return fibonacci(n - 1) + fibonacci(n - 2)
# Print first 5 terms
for i in range(5):
print(fibonacci(i), end=" ") # Output: 0 1 1 2 3
Python Programming (BCC402) | Unit 2 Question Bank Page 4 of 9
Q10. Write a Python program using a for loop to print the multiplication table of a number
entered by the user.
def print_table(num):
print(f"Table of {num}:")
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
print_table(5)
Q11. Develop a Python program that prints all prime numbers between 1 and 100 using
for and else clauses.
The loop else executes only if the loop reaches completion naturally without hitting any break
statement.
print("Prime numbers (1-100):")
for num in range(2, 101):
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
break
else:
print(num, end=" ") # Prints if no divisor was found
Python Programming (BCC402) | Unit 2 Question Bank Page 5 of 9
Q12. Write a Python program that calculates the factorial of a number using both while
loop and for loop separately.
# 1. Using a for loop
def fact_for(n):
res = 1
for i in range(1, n + 1):
res *= i
return res
# 2. Using a while loop
def fact_while(n):
res = 1
temp = n
while temp > 0:
res *= temp
temp -= 1
return res
print("Fact (For):", fact_for(5)) # 120
print("Fact (While):", fact_while(5)) # 120
Q13. Write a Python program to check if the given string is a palindrome using while loop
(without slicing or reverse methods).
def is_pal_while(text):
cleaned = [Link]().replace(" ", "")
left = 0
right = len(cleaned) - 1
while left < right:
if cleaned[left] != cleaned[right]:
return False
left += 1
right -= 1
return True
print(is_pal_while("My gym")) # True
Python Programming (BCC402) | Unit 2 Question Bank Page 6 of 9
Q14. Explain how the pass statement works inside loops. Write a Python code where the
pass statement is used inside an empty if block within a for loop.
The pass statement acts as a syntactic placeholder when a branch structure is required but no
implementation is currently needed. This keeps empty sections valid.
for i in range(1, 5):
if i % 2 == 0:
pass # Placeholder: do nothing for even numbers
else:
print(f"Odd: {i}")
Q15. Write a Python program using nested for loops to print the following pattern:
rows = 4
for i in range(1, rows + 1):
for j in range(i):
print(i, end=" ")
print()
Output:
1
2 2
3 3 3
4 4 4 4
Q16. Develop a Python program to find the sum of all odd numbers between 1 to N using
a while loop.
def sum_odd(N):
total = 0
curr = 1
while curr <= N:
total += curr
curr += 2 # Increment by 2 to jump to the next odd number
return total
print("Sum of odds up to 10:", sum_odd(10)) # 1 + 3 + 5 + 7 + 9 = 25
Python Programming (BCC402) | Unit 2 Question Bank Page 7 of 9
Q17. Explain the difference between while and do-while loop constructs. Write a Python
equivalent to simulate a do-while loop to accept numbers until a positive number is
entered.
• while loop (Entry-controlled): Tests the condition first. If initially False, the loop body never runs.
• do-while loop (Exit-controlled): Runs the loop body at least once, testing the conditions at the end
of each iteration. Python simulates this with while True and a break statement.
# Simulate do-while
while True:
num = int(input("Enter a positive number to exit: "))
if num > 0:
print("Positive number accepted!")
break
Q18. Write a Python program to demonstrate the use of nested if-else for determining the
largest of three numbers.
def find_largest(a, b, c):
if a >= b:
if a >= c:
return a
else:
return c
else:
if b >= c:
return b
else:
return c
print("Largest of (10, 45, 23):", find_largest(10, 45, 23)) # 45
Python Programming (BCC402) | Unit 2 Question Bank Page 8 of 9
Q19. Write a Python program to count the number of vowels and consonants in a given
string using a for loop and if-else conditions.
def count_v_c(text):
vowels = "aeiou"
v_count = 0
c_count = 0
for char in [Link]():
if [Link]():
if char in vowels:
v_count += 1
else:
c_count += 1
print(f"Vowels: {v_count} | Consonants: {c_count}")
count_v_c("Hello World") # Vowels: 3 | Consonants: 7
Python Programming (BCC402) | Unit 2 Question Bank Page 9 of 9