Control Structures Practice Questions
Practice Questions - Python 3 Control Structures
Practice Questions: Python 3 Control Structures
This practice guide is structured to reinforce the control structures concepts covered in Step 1: Control Structures Complete Guide. Solving these exercises will help you master conditional branching (if/elif/else), logical gates (and/or/not), definite loops (for), indefinite loops (while), loop controls (break/continue), and nested matrix loops.
Guidelines for Effective Learning:
- Solve Individually First: Write out your own logical code before reviewing the provided answers.
- Execute Locally: Run each code block in your local terminal to see dynamic outputs.
- Trace Loop States: For nested loops or loop controls, manually trace variable states step-by-step on paper to understand the execution sequence.
Practice Questions Index
- Section 2: Logical Merges (Questions 11-20) — Combining boolean expressions using logical gates.
- Section 3: Definite Iteration (Questions 21-30) — Standard
forloop traversal and range iterations. - Section 4: Indefinite Iteration (Questions 31-40) — Dynamic state loops using
whilelogic. - Section 5: Advanced Flow Control & Nested Loops (Questions 41-50) — Loop interruptions (
break,continue) and nested grid matrices.
1. Basic Branching (Questions 1-10)
Question 1: Adult Check
Task: Write a program that captures an age from the user as an integer. If the age is 18 or older, print "Access granted.". Otherwise, print "Access denied: Minor status."
Answer:
main.pyRunnableage = int(input("Enter age: ")) if age >= 18: print("Access granted.") else: print("Access denied: Minor status.")
Question 2: Two-Number Comparisons
Task: Capture two float values from the terminal. Output which number is larger, or print "Both numbers are equal." if they match.
Answer:
main.pyRunnableval1 = float(input("Enter first value: ")) val2 = float(input("Enter second value: ")) if val1 > val2: print(f"{val1} is larger than {val2}.") elif val2 > val1: print(f"{val2} is larger than {val1}.") else: print("Both numbers are equal.")
Question 3: Even or Odd Checker
Task: Capture a whole number from the user. Use the modulus operator (%) to check if the number is even or odd, and print the result.
Answer:
main.pyRunnablevalue = int(input("Enter integer value: ")) if value % 2 == 0: print("The value is Even.") else: print("The value is Odd.")
Question 4: Login Verification Gate
Task: Store a system password "admin_secure_80" in your script. Capture a password input from the user. Print "System unlocked." if correct, and "Access unauthorized." if incorrect.
Answer:
main.pyRunnablesystem_password = "admin_secure_80" user_guess = input("Enter administrative password: ") if user_guess == system_password: print("System unlocked.") else: print("Access unauthorized.")
Question 5: Climate Range Warnings
Task: Capture a temperature reading as a float.
- If the temperature is above 35.0°C, print
"Extreme heat alert!" - If it is below 0.0°C, print
"Freezing alert!" - Otherwise, print
"Temperature is within standard operational range."
Answer:
main.pyRunnabletemp = float(input("Enter temperature (°C): ")) if temp > 35.0: print("Extreme heat alert!") elif temp < 0.0: print("Freezing alert!") else: print("Temperature is within standard operational range.")
Question 6: Grade Boundary Converter
Task: Convert a numeric grade percentage input (0-100) to a letter grade based on these parameters:
- 90 or higher:
"A" - 80-89:
"B" - 70-79:
"C" - Below 70:
"F"
Answer:
main.pyRunnablescore = float(input("Enter grade percentage: ")) if score >= 90.0: letter = "A" elif score >= 80.0: letter = "B" elif score >= 70.0: letter = "C" else: letter = "F" print("Assigned Grade Letter:", letter)
Question 7: Operational Cost Balance Check
Task: Capture the account balance and transaction cost as floats. If the balance is sufficient, deduct the cost and print the new balance. If insufficient, print "Transaction blocked: Insufficient balance."
Answer:
main.pyRunnablebalance = float(input("Current account balance: $")) cost = float(input("Enter transaction cost: $")) if cost <= balance: balance -= cost print(f"Transaction processed. New Balance: ${balance:.2f}") else: print("Transaction blocked: Insufficient balance.")
Question 8: Age Milestone Verification
Task: Capture an age input. Print "Eligible to drive and vote." if age is 18 or older. If exactly 16 or 17, print "Eligible to drive only." If below 16, print "Ineligible for driving and voting milestones."
Answer:
main.pyRunnableage = int(input("Enter age: ")) if age >= 18: print("Eligible to drive and vote.") elif age >= 16: print("Eligible to drive only.") else: print("Ineligible for driving and voting milestones.")
Question 9: Sign Valuator
Task: Check if a captured float is positive, negative, or exactly zero.
Answer:
main.pyRunnablenumber = float(input("Enter value: ")) if number > 0.0: print("Value is Positive.") elif number < 0.0: print("Value is Negative.") else: print("Value is Zero.")
Question 10: Performance Evaluation Gate
Task: Capture a project completion score (0-100). If the score is 75 or higher, print "Milestone passing criteria met." Otherwise, print "Action Required: Remediation needed."
Answer:
main.pyRunnablecompletion_score = int(input("Enter project completion score: ")) if completion_score >= 75: print("Milestone passing criteria met.") else: print("Action Required: Remediation needed.")
Section Checkup
2. Logical Merges (Questions 11-20)
Question 11: Combined Scholarship Verification
Task: To qualify for an academic grant, a student must have a GPA of 3.8 or higher AND a perfect attendance record (True/False). Capture both inputs and evaluate eligibility.
Answer:
main.pyRunnablegpa = float(input("Enter student GPA: ")) has_perfect_attendance = input("Perfect attendance? (yes/no): ").lower() == "yes" if gpa >= 3.8 and has_perfect_attendance: print("Grant Qualification: Approved.") else: print("Grant Qualification: Criteria unfulfilled.")
Question 12: School Closure Alert
Task: School is closed if the day is a weekend day (Saturday/Sunday) OR if a weather emergency status is set to True. Capture the weekday string and emergency status and print the school status.
Answer:
main.pyRunnableweekday = input("Enter day of week: ").lower() weather_emergency = input("Weather emergency active? (yes/no): ").lower() == "yes" if weekday == "saturday" or weekday == "sunday" or weather_emergency: print("School Status: CLOSED.") else: print("School Status: OPEN.")
Question 13: Mid-Tier Score Filtering
Task: Capture a test score. Print "Score is within range B." if the value is between 80 and 89 (inclusive). Otherwise, print "Score is outside target range."
Answer:
main.pyRunnablescore = int(input("Enter score value: ")) ## Combined range checking if score >= 80 and score <= 89: print("Score is within range B.") else: print("Score is outside target range.")
Question 14: Administrative Entry Gate
Task: To gain entrance to a secure laboratory, a user must enter an ID matching "admin_user" and a security clearance pass matching 4509. Capture both inputs and validate the user.
Answer:
main.pyRunnableuser_id = input("Enter user ID: ") passcode = int(input("Enter clearance passcode: ")) if user_id == "admin_user" and passcode == 4509: print("Access: Granted.") else: print("Access: Denied. Incorrect ID or passcode.")
Question 15: Safety Height and Age Verification
Task: A park ride requires a traveler to be at least 12 years old OR have a height of 140cm or higher. Capture age (integer) and height (float) and print access status.
Answer:
main.pyRunnableage = int(input("Enter age: ")) height = float(input("Enter height (cm): ")) if age >= 12 or height >= 140.0: print("Ride Access: Approved.") else: print("Ride Access: Denied. Safety parameters unfulfilled.")
Question 16: Operational Hours Validation
Task: A system is in off-peak mode if the hour is before 8:00 AM (0-7) or after 8:00 PM (20-23). Capture the hour (0-23) and print peak status using logical gates.
Answer:
main.pyRunnablehour = int(input("Enter active hour (0-23): ")) if hour < 8 or hour >= 20: print("System Mode: OFF-PEAK operational bounds.") else: print("System Mode: PEAK operational bounds.")
Question 17: Leap Year Calculator
Task: A year is a leap year if it is divisible by 4 but NOT by 100, unless it is also divisible by 400. Capture a year and evaluate.
Answer:
main.pyRunnableyear = int(input("Enter year to evaluate: ")) if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print(f"Year {year} is a Leap Year.") else: print(f"Year {year} is a standard 365-day year.")
Question 18: Negative State Check
Task: Use the not logical operator to print a warning only when a system diagnostic status is NOT "active".
Answer:
main.pyRunnablediagnostic_status = input("Enter diagnostic system status: ") if not (diagnostic_status == "active"): print("WARNING: System is not active! Inspection required.") else: print("Status confirmed: System operational.")
Question 19: Valid Coordinate Ranges
Task: A GPS coordinate is valid if the latitude is between -90.0 and 90.0 (inclusive) and the longitude is between -180.0 and 180.0 (inclusive). Capture coordinates and print validity.
Answer:
main.pyRunnablelat = float(input("Enter latitude: ")) lon = float(input("Enter longitude: ")) if lat >= -90.0 and lat <= 90.0 and lon >= -180.0 and lon <= 180.0: print("Coordinate status: VALID.") else: print("Coordinate status: INVALID parameters.")
Question 20: Academic Warning Trigger
Task: A student is placed on warning if their GPA is below 2.0 OR their attendance rate is strictly below 85.0%. Capture GPA and attendance and print status.
Answer:
main.pyRunnablegpa = float(input("Enter GPA: ")) attendance = float(input("Enter attendance rate (%): ")) if gpa < 2.0 or attendance < 85.0: print("Academic Status: WARNING flagged.") else: print("Academic Status: Good standing.")
Section Checkup
3. Definite Iteration (Questions 21-30)
Question 21: Chronological Counting
Task: Use a for loop and the range() function to count and print numbers from 1 to 10 in sequence.
Answer:
main.pyRunnablefor num in range(1, 11): print("Step:", num)
Question 22: Iterating Even Numbers
Task: Write a for loop that prints all even numbers from 2 to 20 (inclusive) using step increments.
Answer:
main.pyRunnablefor even_num in range(2, 21, 2): print("Even Number:", even_num)
Question 23: Backwards Counter
Task: Write a for loop that prints a countdown sequence from 10 to 1 using negative step parameters.
Answer:
main.pyRunnablefor count in range(10, 0, -1): print("Countdown:", count)
Question 24: Running Sum Calculator
Task: Iterate through a list of raw transactional scores [85, 92, 78, 96, 88] using a for loop. Compute and print the cumulative running sum.
Answer:
main.pyRunnablescores = [85, 92, 78, 96, 88] total_sum = 0 for score in scores: total_sum += score print("Cumulative Running Sum:", total_sum)
Question 25: Indexed List Iteration
Task: Loop through a list of systems ["ServerA", "ServerB", "ServerC"]. Print each item along with its 1-indexed count position.
Answer:
main.pyRunnableservers = ["ServerA", "ServerB", "ServerC"] index_counter = 1 for server in servers: print(f"Node #{index_counter}: {server}") index_counter += 1
Question 26: Multiplication Table Generator
Task: Capture a number from the user. Use a for loop from 1 to 10 to generate and print that number's multiplication table.
Answer:
main.pyRunnablemultiplier = int(input("Enter multiplication base: ")) for val in range(1, 11): product = multiplier * val print(f"{multiplier} x {val} = {product}")
Question 27: List Maximum Finder
Task: Write a loop that inspects a list of scores [45, 82, 19, 98, 54] and finds the highest score manually without using max().
Answer:
main.pyRunnablescores = [45, 82, 19, 98, 54] highest_score = scores[0] # Initialize with first element for score in scores: if score > highest_score: highest_score = score print("Manually calculated peak score:", highest_score)
Question 28: Numeric Average Calculator
Task: Take a list of student GPA values. Use a for loop to sum them and divide by the length of the list to calculate the average.
Answer:
main.pyRunnablegpas = [3.2, 3.8, 2.9, 3.5, 4.0] total_gpa = 0.0 for gpa in gpas: total_gpa += gpa average_gpa = total_gpa / len(gpas) print(f"Average Class GPA: {average_gpa:.2f}")
Question 29: Filtering Negatives
Task: Given a list of transactions [100, -25, 50, -10, 80], loop through and print only the negative values representing withdrawals.
Answer:
main.pyRunnabletransactions = [100, -25, 50, -10, 80] print("Detected Account Withdrawals:") for tx in transactions: if tx < 0: print("Withdrawal:", tx)
Question 30: Stepping Index Traverse
Task: Loop through a list of names ["Alice", "Bob", "Charlie", "David", "Emma"] and print every second name.
Answer:
main.pyRunnablenames = ["Alice", "Bob", "Charlie", "David", "Emma"] ## Step through list indices using range steps for i in range(0, len(names), 2): print("Selected Student:", names[i])
Section Checkup
4. Indefinite Iteration (Questions 31-40)
Question 31: Simple Value Countdown
Task: Create a while loop that counts down from 5 to 1, and then prints "Launch complete."
Answer:
main.pyRunnablecounter = 5 while counter > 0: print("Countdown:", counter) counter -= 1 print("Launch complete.")
Question 32: Capturing Inputs Until Terminal Key
Task: Write a while loop that continually prompts the user to enter a name. The loop should terminate only when the user types "done". Print a summary of how many names were captured (excluding "done").
Answer:
main.pyRunnablecaptured_count = 0 active_entry = "" while active_entry != "done": active_entry = input("Enter student name (or 'done' to stop): ") if active_entry != "done": captured_count += 1 print("Total names registered:", captured_count)
Question 33: Password Retries Gate
Task: A system has a secure password "secure_password". Prompt the user for a passcode. Allow them up to 3 attempts inside a while loop. Terminate and print "Access granted." if correct, or print "Account locked." if they run out of attempts.
Answer:
main.pyRunnablecorrect_pass = "secure_password" attempts = 0 validated = False while attempts < 3 and not validated: guess = input("Enter system access password: ") if guess == correct_pass: validated = True else: attempts += 1 print(f"Incorrect passcode. {3 - attempts} attempts remaining.") if validated: print("Access granted.") else: print("Account locked.")
Question 34: Sequential Halving
Task: Take an initial capacity value 100. Inside a while loop, print the capacity, and then divide it by 2 in each iteration. Terminate the loop when the capacity falls below 10.
Answer:
main.pyRunnablecapacity = 100.0 while capacity >= 10.0: print(f"Current Capacity Level: {capacity:.1f}%") capacity /= 2.0 print("Halted: Low capacity boundary reached.")
Question 35: Incremental Interest Compounder
Task: Initialize an investment balance of 1000. Calculate interest growth over time. Using interest rate 0.05 (), execute a while loop that multiplies balance by 1.05 annually. Stop when the balance has doubled to at least 2000, tracking and printing the years required.
Answer:
main.pyRunnablebalance = 1000.0 target = 2000.0 annual_rate = 1.05 years = 0 while balance < target: balance *= annual_rate years += 1 print(f"Balance reached ${balance:.2f} after {years} years of compounded growth.")
Question 36: Interactive Numeric Summation
Task: Write a while loop that continuously asks the user for integers and sums them. The loop terminates when the user enters 0. Output the final combined sum.
Answer:
main.pyRunnablerunning_total = 0 user_value = -1 # Initialize to enter loop while user_value != 0: user_value = int(input("Enter integer to sum (0 to exit): ")) running_total += user_value print("Cumulative Summed Total:", running_total)
Question 37: Numeric Bounds Checker
Task: Prompt the user to enter a rating between 1 and 5. Use a while loop to repeatedly prompt the user for input as long as their entry is outside these boundaries.
Answer:
main.pyRunnablerating = 0 while rating < 1 or rating > 5: rating = int(input("Enter rating value (1-5): ")) if rating < 1 or rating > 5: print("Invalid entry. Rating must be between 1 and 5.") print("Valid rating registered:", rating)
Question 38: Target Value Check
Task: Initialize a variable score = 10. Execute a while loop that increments score by 15 each iteration, printing the updated score. Terminate the loop once the score exceeds 80.
Answer:
main.pyRunnablescore = 10 while score <= 80: score += 15 print("Score Progress:", score)
Question 39: Division Zero Gate
Task: Prompt the user to enter a divisor. If they enter 0, execute a while loop prompting them to enter a non-zero divisor until they provide a valid number. Then divide 100 by the divisor and print the result.
Answer:
main.pyRunnabledivisor = 0.0 while divisor == 0.0: divisor = float(input("Enter non-zero mathematical divisor: ")) if divisor == 0.0: print("Error: Division by zero is undefined.") result = 100.0 / divisor print("Mathematical Quotient:", result)
Question 40: Manual Toggled State Exit
Task: Use a Boolean switch is_active = True and a counter steps = 0. Execute a while loop that increments steps by 1. Once steps reaches 4, update is_active to False to terminate the loop.
Answer:
main.pyRunnableis_active = True steps = 0 while is_active: steps += 1 print("Step Counter:", steps) if steps == 4: is_active = False
Section Checkup
5. Advanced Flow Control & Nested Loops (Questions 41-50)
Question 41: early Exit (break)
Task: Write a for loop that iterates from 1 to 10. Use a break statement to terminate the loop early when the number reaches 6.
Answer:
main.pyRunnablefor num in range(1, 11): if num == 6: break print("Value:", num)
Question 42: Skipping Iterations (continue)
Task: Iterate through a list of scores [85, -5, 92, -10, 78] using a for loop. Use continue to skip calculations for any negative numbers.
Answer:
main.pyRunnablescores = [85, -5, 92, -10, 78] print("Processing clean scores database...") for score in scores: if score < 0: print("Negative value detected. Skipping record.") continue print("Processing Valid Score:", score)
Question 43: Seating Grid Layout Generator (Nested Loop)
Task: Write a nested loop that prints a desk map for a classroom with 3 rows and 2 columns of desks.
Answer:
main.pyRunnablerows = 3 cols = 2 for r in range(1, rows + 1): row_layout = "" for c in range(1, cols + 1): row_layout += f"[R{r}-C{c}] " print(row_layout)
Question 44: Triangle Shape Pattern
Task: Write a nested loop that prints a right-angled triangle pattern made of stars (*), with a base height of 4 rows.
Answer:
main.pyRunnableheight = 4 for r in range(1, height + 1): stars_line = "" for c in range(r): stars_line += "*" print(stars_line)
Output:
* ** *** ****
Question 45: Exit Nested Arrays (Break on Grid)
Task: Iterate through a nested classroom seating grid [["Alice", "Bob"], ["Charlie", "David"]] using nested for loops. Use a break to exit the inner loop when "Charlie" is found.
Answer:
main.pyRunnableclassroom = [ ["Alice", "Bob"], ["Charlie", "David"] ] for row in classroom: print("Checking row...") for student in row: if student == "Charlie": print("Charlie located! Terminating inner search scan.") break print("Checked student:", student)
Question 46: Prime Number Evaluator
Task: Capture a positive integer from the user. Use a for loop to check if it has any divisors other than 1 and itself, using a break to exit early if a divisor is found.
Answer:
main.pyRunnableval = int(input("Enter positive integer: ")) if val < 2: print("Evaluation: Number is not prime.") else: is_prime = True for divisor in range(2, val): if val % divisor == 0: is_prime = False break # Exit loop immediately if a divisor is found if is_prime: print("Evaluation: Number is Prime.") else: print("Evaluation: Number is Not Prime.")
Question 47: Seating Coordinate Allocator
Task: Given a list of students ["Alice", "Bob", "Charlie"] and a classroom grid of 2 rows and 2 columns, write a nested loop to assign students to desk coordinates row-by-row, printing the results.
Answer:
main.pyRunnablestudents = ["Alice", "Bob", "Charlie"] rows = 2 cols = 2 idx = 0 for r in range(1, rows + 1): for c in range(1, cols + 1): if idx < len(students): print(f"Allocating Desk at Row {r}-Column {c} to {students[idx]}.") idx += 1
Question 48: Manual Deduplication Search
Task: Write a nested loop that compares elements of a list [4, 2, 8, 2, 9] against itself to search for duplicate numbers, printing any duplicates found.
Answer:
main.pyRunnableitems = [4, 2, 8, 2, 9] for i in range(len(items)): for j in range(i + 1, len(items)): if items[i] == items[j]: print(f"Duplicate value detected in list: {items[i]}")
Question 49: Element Coordinate Lookup
Task: Write a nested loop that searches the matrix grid [[10, 20], [30, 40]] for the target number 30. Once found, print the row and column indices where it is located.
Answer:
main.pyRunnablematrix = [ [10, 20], [30, 40] ] target = 30 for r_idx in range(len(matrix)): for c_idx in range(len(matrix[r_idx])): if matrix[r_idx][c_idx] == target: print(f"Target found at Grid Coordinate: Row Index {r_idx}, Col Index {c_idx}.")
Question 50: Matrix Column Extraction
Task: Given a 2D matrix representing rows and columns [[1, 2, 3], [4, 5, 6]], write a loop that extracts and prints only the elements of the second column (index 1).
Answer:
main.pyRunnablematrix = [ [1, 2, 3], [4, 5, 6] ] print("Extracting Second Column:") for row in matrix: print("Column Element:", row[1])
Congratulations! 🎓
You have completed all 50 practice questions on Control Structures! You have mastered branching pathways, logical expressions, def/indef loops, loop controls, and nested coordinate grids. Keep up the great work!
Finished this lesson?
Mark it complete to advance your curriculum progress.