DAY 04 · PRACTICE

5 Questions — Level Up 🚀

📦 Topics: Strings · Functions · Loops · 2D Lists · Exception Handling ⏱ Est: 1.5–2.5 hrs total 🎯 Difficulty: 2 / 5
01
Username Validator 🔐
STRING FUNCTIONS EASY ~20 min
📖 Scenario
Every app — Instagram, GitHub, Twitter — validates your username before allowing signup. Rules: 5–15 characters long, must start with a letter, can only contain letters, digits, or underscores, and no spaces allowed. Write a function that checks all these rules and tells the user exactly what went wrong.
Starter Code
def validate_username(username): pass # check all rules and return a message # Test your function with these print(validate_username("rahul_99")) print(validate_username("hi")) print(validate_username("99abc")) print(validate_username("hello world")) print(validate_username("this_username_is_way_too_long_bro"))
Your Tasks
  • Check if length is between 5 and 15 — if not, return "Too short!" or "Too long!"
  • Check if the first character is a letter — if not, return "Must start with a letter!" Use username[0].isalpha()
  • Check that every character is a letter, digit, or underscore — if not, return "Only letters, digits, underscores allowed!" Loop through each character and use .isalnum() or check char == "_"
  • If all checks pass, return "Valid username! ✓"
Expected Output
Valid username! ✓
Too short!
Must start with a letter!
Only letters, digits, underscores allowed!
Too long!
💡 One Hint
For Task ③, use for char in username: and check not char.isalnum() and char != "_". If any character fails, return immediately — no need to check the rest.
02
Word Frequency Counter 📊
STRING DICT EASY ~25 min
📖 Scenario
Google Docs' word count, plagiarism checkers, and SEO tools all count how often each word appears in text. You'll build the core of that — split a sentence into words, count how many times each appears, and find the most repeated word. This is one of the most common real-world uses of dictionaries!
Starter Code
sentence = "the cat sat on the mat the cat sat" # Write your code below
Your Tasks
  • Split the sentence into a list of words Use sentence.split() — it splits on spaces automatically
  • Build a word frequency dictionary — each word as key, count as value Loop through words. If the word is already in the dict, add 1. If not, set it to 1.
  • Print the full frequency dictionary
  • Find and print the most frequent word and how many times it appears
  • Print all words that appear more than once
Expected Output
Words: ['the', 'cat', 'sat', 'on', 'the', 'mat', 'the', 'cat', 'sat']
Frequency: {'the': 3, 'cat': 2, 'sat': 2, 'on': 1, 'mat': 1}
Most frequent: "the" (3 times)
Repeated words: the, cat, sat
💡 One Hint
For Task ②: if word in freq: freq[word] += 1 else freq[word] = 1. For Task ④, use max(freq, key=freq.get) — this finds the key with the highest value.
03
Number Pattern Printer 🔢
LOOPS FUNCTIONS EASY ~20 min
📖 Scenario
Pattern printing is a classic coding interview warm-up — it tests whether you truly understand how nested loops work. The outer loop controls the number of rows, the inner loop controls what prints on each row. Once you crack the logic, you can print any pattern imaginable.
🧠 Concept
print("* ", end="") — the end="" keeps everything on the same line instead of jumping to a new line. Use print() with nothing to move to the next line.
Starter Code
def print_triangle(n): pass def print_square(n): pass def print_reverse(n): pass print_triangle(5) print() print_square(4) print() print_reverse(5)
Your Tasks
  • Fill print_triangle(n) — prints a right-angled triangle of stars growing from 1 to n Row 1 → 1 star, Row 2 → 2 stars, ... Row n → n stars
  • Fill print_square(n) — prints an n×n square of stars
  • Fill print_reverse(n) — prints the triangle upside down, from n stars down to 1
Expected Output
*
* *
* * *
* * * *
* * * * *

* * * *
* * * *
* * * *
* * * *

* * * * *
* * * *
* * *
* *
*
💡 One Hint
For triangle: outer loop for i in range(1, n+1), inner loop for j in range(i). For reverse: outer loop for i in range(n, 0, -1) — the third argument -1 counts DOWN.
04
Classroom Grade Sheet 📋
2D LIST LOOPS EASY ~25 min
📖 Scenario
School report cards store marks for multiple subjects per student. In code, this is a 2D list — a list where each element is itself a list. Think of it like a table: rows = students, columns = subjects. You'll calculate each student's total, find the class topper, and spot who failed any subject.
Starter Code
# Each inner list: [name, Maths, Science, English] grade_sheet = [ ["Rahul", 78, 85, 72], ["Priya", 92, 88, 95], ["Arjun", 45, 38, 62], ["Sneha", 88, 91, 80], ["Vikram", 55, 48, 70], ] subjects = ["Maths", "Science", "English"] # Write your code below
Your Tasks
  • Print each student's name and total marks (sum of all 3 subjects) row[0] = name, row[1], row[2], row[3] = marks. Use sum(row[1:])
  • Find and print the class topper — student with the highest total
  • Find students who failed any subject (marks < 50 in any one subject) A student fails if ANY of their marks is below 50
  • Calculate the class average for each subject separately Average of all Maths marks, all Science marks, all English marks
Expected Output
Rahul: 235 | Priya: 275 | Arjun: 145 | Sneha: 259 | Vikram: 173
Class topper: Priya (275)
Failed students: Arjun, Vikram
Subject averages → Maths: 71.6 | Science: 70.0 | English: 75.8
💡 One Hint
For Task ③, use any(mark < 50 for mark in row[1:]) — this checks if ANY mark in the row is below 50. It's the Pythonic way of saying "if at least one mark fails".
05
Safe ATM Machine 🏧
EXCEPTION FUNCTIONS MEDIUM ~30 min
📖 Scenario
A real ATM handles errors gracefully — it doesn't crash when you type letters instead of a number, or try to withdraw more than your balance. This is Exception Handling: wrapping risky code in try so that if it breaks, the except block catches it and shows a friendly message instead of crashing the whole program.
🧠 New Concept: try / except
try: → put the risky code here
except ValueError: → runs if int("abc") fails
except Exception as e: → catches anything else
Without this, one bad input crashes your entire program!
Starter Code
def withdraw(balance, amount): pass # handle all error cases, return new balance def atm_session(): balance = 5000 print(f"Welcome! Your balance: ₹{balance}") # Test these cases one by one balance = withdraw(balance, 1000) # normal withdrawal balance = withdraw(balance, 9999) # more than balance balance = withdraw(balance, -500) # negative amount balance = withdraw(balance, 0) # zero withdrawal atm_session()
Your Tasks
  • In withdraw(), if amount <= 0, print "Invalid amount!" and return balance unchanged
  • If amount > balance, print "Insufficient funds!" and return balance unchanged
  • Otherwise, deduct the amount, print "Withdrew ₹X. New balance: ₹Y", and return new balance
  • Wrap the entire body of withdraw() in a try/except block — if any unexpected error occurs, catch it and print "Transaction error!" Use except Exception as e: to catch any error type
Expected Output
Welcome! Your balance: ₹5000
Withdrew ₹1000. New balance: ₹4000
Insufficient funds!
Invalid amount!
Invalid amount!
💡 One Hint
Structure: try: → check conditions first (amount <= 0, amount > balance) then do the deduction. except Exception as e: → print "Transaction error!". The checks inside try are just normal if/else — exception handling is the outer safety net.
01
Username Validator 🔐
STRING METHODS EASY ~20 min
📖 Scenario
Every app validates usernames before signup. Rules: 5–15 characters long, must start with a letter, can only contain letters, digits, or underscores, no spaces allowed. Write a method that checks all rules and returns exactly what went wrong.
Starter Code
public class Validator { static String validateUsername(String username) { return ""; // replace with your logic } public static void main(String[] args) { System.out.println(validateUsername("rahul_99")); System.out.println(validateUsername("hi")); System.out.println(validateUsername("99abc")); System.out.println(validateUsername("hello world")); System.out.println(validateUsername("this_username_is_way_too_long_bro")); } }
Your Tasks
  • Check length between 5 and 15 using username.length() — return "Too short!" or "Too long!"
  • Check if first character is a letter — return "Must start with a letter!" Use Character.isLetter(username.charAt(0))
  • Loop through every character — if not letter, digit, or underscore, return "Only letters, digits, underscores allowed!" Use Character.isLetterOrDigit(c) or c == '_'
  • If all checks pass, return "Valid username! ✓"
Expected Output
Valid username! ✓
Too short!
Must start with a letter!
Only letters, digits, underscores allowed!
Too long!
💡 One Hint
Use for (char c : username.toCharArray()) to loop through each character. Check !Character.isLetterOrDigit(c) && c != '_'. If true, return the error immediately — Java exits the method the moment it hits return.
02
Word Frequency Counter 📊
STRING HASHMAP EASY ~25 min
📖 Scenario
Word frequency counting powers Google Docs word count, plagiarism checkers, and SEO tools. Split a sentence into words, count how often each appears in a HashMap, and find the most repeated word. This is one of the most common interview problems too!
Starter Code
import java.util.*; public class WordFrequency { public static void main(String[] args) { String sentence = "the cat sat on the mat the cat sat"; // Write your code below } }
Your Tasks
  • Split the sentence into a String array of words Use sentence.split(" ") — splits on every space
  • Build a HashMap<String, Integer> — word → count Use getOrDefault(word, 0) + 1 to cleanly increment the count
  • Print the full frequency map
  • Find and print the most frequent word and how many times it appears
  • Print all words that appear more than once
Expected Output
Frequency: {the=3, cat=2, sat=2, on=1, mat=1}
Most frequent: "the" (3 times)
Repeated words: the, cat, sat
💡 One Hint
For Task ②: freq.put(word, freq.getOrDefault(word, 0) + 1) — this is the cleanest Java one-liner for counting. For Task ④, loop through freq.entrySet() and track the entry with the highest .getValue().
03
Number Pattern Printer 🔢
LOOPS METHODS EASY ~20 min
📖 Scenario
Pattern printing is a classic Java interview warm-up. The outer loop controls the number of rows, the inner loop controls what prints on each row. Mastering nested loops here means you can handle 2D arrays, matrices, and grid-based problems with confidence.
🧠 Concept
System.out.print("* ") — stays on the same line.
System.out.println() — moves to the next line (empty println).
Starter Code
public class Patterns { static void printTriangle(int n) { // TODO } static void printSquare(int n) { // TODO } static void printReverse(int n) { // TODO } public static void main(String[] args) { printTriangle(5); System.out.println(); printSquare(4); System.out.println(); printReverse(5); } }
Your Tasks
  • Fill printTriangle(n) — right-angled triangle growing from 1 star to n stars
  • Fill printSquare(n) — n rows each with n stars
  • Fill printReverse(n) — triangle upside-down, from n stars down to 1 Outer loop: for (int i = n; i >= 1; i--) — counts down
Expected Output
*
* *
* * *
* * * *
* * * * *

* * * *
* * * *
* * * *
* * * *

* * * * *
* * * *
* * *
* *
*
💡 One Hint
For triangle: for (int i = 1; i <= n; i++) outer, for (int j = 0; j < i; j++) inner. After the inner loop ends, call System.out.println() to move to the next row.
04
Classroom Grade Sheet 📋
2D ARRAY LOOPS EASY ~25 min
📖 Scenario
School report cards store marks for multiple subjects per student. In Java this is a 2D int array for marks and a parallel String array for names. Think of it like a table: rows = students, columns = subjects. You'll process both arrays together using the same index.
Starter Code
public class GradeSheet { public static void main(String[] args) { String[] names = {"Rahul", "Priya", "Arjun", "Sneha", "Vikram"}; String[] subjects = {"Maths", "Science", "English"}; // marks[i][j] = student i's marks in subject j int[][] marks = { {78, 85, 72}, {92, 88, 95}, {45, 38, 62}, {88, 91, 80}, {55, 48, 70}, }; // Write your code below } }
Your Tasks
  • Print each student's name and total marks (sum of all 3 subjects) marks[i][0] + marks[i][1] + marks[i][2] for student i
  • Find and print the class topper — student with the highest total
  • Find students who failed any subject (any mark < 50) Inner loop through marks[i][j] — if any j has marks < 50, student failed
  • Calculate class average per subject using the column index For subject j, sum marks[0][j] + marks[1][j] + ... and divide by number of students
Expected Output
Rahul: 235 | Priya: 275 | Arjun: 145 | Sneha: 259 | Vikram: 173
Class topper: Priya (275)
Failed students: Arjun, Vikram
Maths avg: 71.6 | Science avg: 70.0 | English avg: 75.8
💡 One Hint
For Task ③, use a boolean flag: boolean failed = false; inside the student loop. Inner loop through subjects: if any mark < 50, set failed = true; break;. After the inner loop, check if (failed) to print the student's name.
05
Safe ATM Machine 🏧
EXCEPTION TRY-CATCH MEDIUM ~30 min
📖 Scenario
A real ATM doesn't crash when you type something wrong — it handles errors gracefully. In Java, this is try-catch: wrap risky code in try{} and if it throws an exception, the catch block handles it cleanly. You'll also learn to throw your own exceptions for custom error conditions.
🧠 New Concept: try / catch / throw
try { ... } → put the risky code here
catch (IllegalArgumentException e) { ... } → catches invalid input
throw new IllegalArgumentException("msg") → you raise the error yourself
Without this, one bad operation crashes the whole program!
Starter Code
public class ATM { static int withdraw(int balance, int amount) { return balance; // replace with your logic } public static void main(String[] args) { int balance = 5000; System.out.println("Welcome! Balance: ₹" + balance); balance = withdraw(balance, 1000); // normal balance = withdraw(balance, 9999); // over balance balance = withdraw(balance, -500); // negative balance = withdraw(balance, 0); // zero } }
Your Tasks
  • Wrap the method body in try { } and add catch (IllegalArgumentException e) that prints the error message and returns balance unchanged
  • Inside try, if amount <= 0 → throw new IllegalArgumentException("Invalid amount!")
  • If amount > balance → throw new IllegalArgumentException("Insufficient funds!")
  • Otherwise, deduct the amount, print "Withdrew ₹X. New balance: ₹Y", and return the new balance
Expected Output
Welcome! Balance: ₹5000
Withdrew ₹1000. New balance: ₹4000
Insufficient funds!
Invalid amount!
Invalid amount!
💡 One Hint
The flow: throw immediately jumps out of try and lands in catch. So your try block has the checks first (throw for bad input), then the deduction at the bottom. catch receives the message via e.getMessage() and prints it.