TryBugHunt

Logic errors: code that runs perfectly and answers wrongly

The wrong operator, an inverted condition, a formula the right way round but backwards.

117 free challenges73 Python44 JavaScript

What is a logic error?

The program does exactly what you wrote, and what you wrote is not what you meant. There is no error message and no crash — only a wrong answer, which is why these are the hardest to spot and the most likely to reach production.

Why it happens

Boolean logic and arithmetic are easy to invert without it looking wrong. || instead of && lets either side pass. any() instead of all() accepts one match instead of requiring every one. A reversed subtraction flips the sign of every result while the magnitude stays plausible. Short-circuit guards placed after the thing they guard read as safe while doing nothing.

How to recognise it

  • The magnitude is right but the sign is wrong.
  • It is correct for uniform input and wrong for mixed input.
  • A guard clause exists but the crash it prevents still happens.
  • Boundary values are handled inconsistently at each end.

Error guides caused by this pattern

All error guides →

In-depth guides for common exceptions and runtime errors triggered by logic errors, with working fixes and real-world examples:

How to fix it

Build a small truth table for any condition with more than one term, and test each branch. Check one case per direction for signed results. Read guards in evaluation order, not reading order — `and` short-circuits left to right, so a guard on the right protects nothing.

Breaks vs Works Example

Breaks

// JavaScript: inverted Boolean condition
if (role !== 'admin' || role !== 'editor') {
  denyAccess(); // Bug: Always true! An admin is not an editor.
}

Works

// JavaScript: conjunction ensures user is neither
if (role !== 'admin' && role !== 'editor') {
  denyAccess(); // Correctly allows admins and editors
}

💡 Remember De Morgan's laws: !(A && B) is !A || !B; to exclude both options, use AND (&&).

Practise logic errors

Working code with one bug in it. Find it, fix it in the browser, and see the explanation. No account needed.

pythonEasy
Word filter finds "cat" inside "cats"

has_word(text, word) returns True only when word appears as a whole word. Example: has_word("cat nap", "cat") → True, has_word("I love cats", "cat") → False.

Logic error

javascriptEasy
Stock check can't find the first product

inStock(items, name) returns true if the product is in the list. Example: inStock(["pen", "ink"], "pen") → true.

Logic error

javascriptEasy
Removing dashes from phone number leaves trailing hyphens

sanitize_phone_number(phone) strips all hyphens from a phone number string. Example: sanitize_phone_number("123-456-7890") → "1234567890".

Logic error

pythonEasy
Zipping uneven lists silently drops unmatched trailing items

pair_users_and_badges(users, badges) pairs users with badges, filling missing values with "none". Example: pair_users_and_badges(["a", "b"], [1]) → [["a", 1], ["b", "none"]].

Logic error

pythonEasy
Cart total adds up positions, not prices

total_price(prices) adds up every price. Example: total_price([10, 20, 30]) → 60.

Logic error

pythonEasy
Reading keeps going after the stop marker

sum_until_stop(readings) adds readings until it meets -1, which means "stop". Anything after -1 is ignored. Example: sum_until_stop([3, 4, -1, 10]) → 7.

Logic error

javascriptEasy
Padding invoice number with padEnd appends trailing zeroes

format_invoice_number(numStr) pads a number string with leading zeroes to a length of 5. Example: format_invoice_number("42") → "00042".

Logic error

javascriptEasy
Highest price comes back as NaN

highestPrice(prices) returns the biggest price. Example: highestPrice([3, 7, 2]) → 7.

Logic error

javascriptEasy
Sorting numbers puts 100 before 25 and alters original array

sort_prices_ascending(prices) returns a new array with numbers sorted in ascending numerical order without modifying the original array. Example: sort_prices_ascending([100, 25, 5]) → [5, 25, 100].

Logic error

javascriptEasy
Helper dropping first item returns deleted item with splice

drop_first_item(items) returns a new array containing all elements except the first. Example: drop_first_item(["a", "b", "c"]) → ["b", "c"].

Logic error

javascriptEasy
Array find returning zero treated as not found

find_status_code(codes, target) returns the matching number from codes, or -1 if target is not in the array. Example: find_status_code([10, 0, 20], 0) → 0.

Logic error

pythonEasy
String split on newline retains empty trailing element unlike splitlines

count_file_lines(file_content) counts lines in file_content, returning 0 for empty strings. Example: count_file_lines('a\nb\n') → 2.

Logic error

pythonEasy
Longest-word finder returns the shortest

longest_word(words) returns the longest word. Example: longest_word(["hi", "hello", "hey"]) → "hello".

Logic error

pythonEasy
Zero retry count override falls back to default limit

get_retry_limit(override) returns override count, falling back to 3 only if override is None. Example: get_retry_limit(0) → 0.

Logic error

pythonEasy
Popping from empty stack raises IndexError without check

pop_undo_action(history) pops and returns the last action from history, returning None if history is empty. Example: pop_undo_action([]) → None.

Logic error

pythonEasy
Counting words using space delimiter overcounts on multiple spaces

count_words(text) counts the total words in a string, ignoring irregular consecutive spaces. Example: count_words("hello world") → 2.

Logic error

javascriptEasy
Single equals assignment in condition grants admin access to all

evaluate_access_tier(user) returns "Privileged" if user.role is "admin", returning "Standard" otherwise. Example: evaluate_access_tier({ role: "guest" }) → "Standard".

Logic error

pythonEasy
Finding minimum on empty transaction list raises ValueError

find_lowest_fee(fees) returns the lowest fee from fees, returning 0 if the list is empty. Example: find_lowest_fee([]) → 0.

Logic error

pythonEasy
Negative banker rounding rounds midpoint toward even integer

round_penalty_score(score) rounds score using standard half-away-from-zero rounding. Example: round_penalty_score(-2.5) → -3.

Logic error

pythonEasy
Counter subtraction retains zero count keys in dictionary

subtract_inventory_counts(stock, sold) subtracts sold items from stock, removing items that reach zero. Example: subtract_inventory_counts({"apple": 2}, {"apple": 2}) → {}.

Logic error

pythonEasy
Purging inactive sessions raises dictionary changed size

purge_inactive_sessions(sessions) removes all keys where active is False and returns the cleaned dictionary. Example: purge_inactive_sessions({"s1": True, "s2": False}) → {"s1": True}.

Logic error

pythonEasy
Average of 4 and 6 comes out as 7

average_of_two(a, b) returns the average of two marks. Example: average_of_two(4, 6) → 5.

Logic error

pythonEasy
Floating point fee calculation leaves precision artifact

calculate_net_payout(gross_amount, processing_fee) subtracts processing_fee from gross_amount rounded to 2 decimal places. Example: calculate_net_payout(1.1, 0.9) → 0.2.

Logic error

pythonEasy
Top scorer is picked alphabetically

top_scorer(scores) takes a dict of names and scores and returns the name with the highest score. Example: top_scorer({"asha": 90, "ravi": 95, "zoe": 70}) → "ravi".

Logic error

pythonEasy
Set difference operator direction inverts unmatched items

find_missing_required_keys(provided_keys, required_keys) returns the missing required keys in sorted order. Example: find_missing_required_keys(["id"], ["id", "email"]) → ["email"].

Logic error

pythonEasy
Itertools groupby on unsorted list splits identical keys

extract_grouped_keys(items) returns the unique sorted group keys from items. Example: extract_grouped_keys(["a", "b", "a"]) → ["a", "b"].

Logic error

javascriptEasy
Sorting mixed case words orders capital letters before lowercase

sort_names_alphabetical(names) sorts strings in case-insensitive alphabetical order. Example: sort_names_alphabetical(["zebra", "apple", "Banana"]) → ["apple", "Banana", "zebra"].

Logic error

javascriptEasy
Deduplicating objects in array with Set returns duplicates

deduplicate_users_by_id(users) removes duplicate user objects sharing the same id. Example: deduplicate_users_by_id([{ id: 1 }, { id: 1 }]) → [{ id: 1 }].

Logic error

pythonEasy
Quiz marks "Paris " wrong because of a space

check_answer(answer) marks the answer to "What is the capital of France?", ignoring capitals and extra spaces. Example: check_answer("Paris ") → True.

Logic error

pythonEasy
AI Attempt: FizzBuzz never says FizzBuzz

An AI assistant wrote this FizzBuzz. fizzbuzz(n) returns "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for multiples of both, and otherwise the number as text. Example: fizzbuzz(15) → "FizzBuzz".

Logic error

javascriptEasy
Array constructor with map skips uninitialized empty slots

generate_index_range(length) generates an array of sequential integers from 0 to length - 1. Example: generate_index_range(3) → [0, 1, 2].

Logic error

pythonEasy
Summarizing stream twice causes generator to return zero sum

summarize_stream(numbers) returns a dictionary with the count and sum of numbers. Example: summarize_stream([10, 20]) → {"count": 2, "sum": 30}.

Logic error

javascriptEasy
Empty array evaluated in boolean condition returns true

format_tag_summary(tags) returns "No tags" if tags is null, undefined, or empty, returning "N tags" otherwise. Example: format_tag_summary([]) → "No tags".

Logic error

pythonEasy
Word count says 3 for "hello world"

count_words(text) counts the words, however many spaces are between them. Example: count_words("hello world") → 2.

Logic error

pythonEasy
Stripping file suffix strips filename characters as a set

strip_log_extension(filename) removes the trailing ".log" extension from a filename. Example: strip_log_extension("catalog.log") → "catalog".

Logic error

javascriptEasy
Clamping percentage bounds inverted returns upper limit

clamp_percentage(value) constrains value to the range 0 to 100 inclusive. Example: clamp_percentage(150) → 100.

Logic error

pythonEasy
Vowel counter skips capital letters

count_vowels(text) counts the vowels, capital or small. Example: count_vowels("Apple") → 2.

Logic error

pythonEasy
Ranking sorts students by name, not score

rank(students) takes [name, score] pairs and returns the names from highest score to lowest. Example: rank([["asha", 72], ["ravi", 95], ["zoe", 60]]) → ["ravi", "asha", "zoe"].

Logic error

javascriptEasy
Math floor on negative coordinate rounds down to lower integer

truncate_coordinate(val) removes the fractional digits of val, rounding toward zero. Example: truncate_coordinate(-1.7) → -1.

Logic error

javascriptEasy
String substring with negative argument treats index as zero

extract_trailing_characters(text, count) returns the last count characters of text. Example: extract_trailing_characters("hello_world", 5) → "world".

Logic error

pythonEasy
Swapping two values copies one over the other

swap(pair) returns the two values in the opposite order. Example: swap([1, 2]) → [2, 1].

Logic error

pythonEasy
Reversing words also reverses the letters

reverse_words(sentence) reverses the order of the words but keeps each word readable. Example: reverse_words("hello world") → "world hello".

Logic error

pythonEasy
Queue serves the last person first

serve_next(queue) removes and returns the person who has waited longest, at the front. Example: serve_next(["asha", "ravi", "zoe"]) → "asha".

Logic error

pythonEasy
Pass counter counts everyone

count_passing(scores) counts the scores of 40 or more. Example: count_passing([72, 35, 90]) → 2.

Logic error

pythonEasy
100 °C converts to 237.6 °F

to_fahrenheit(celsius) converts Celsius to Fahrenheit. Example: to_fahrenheit(100) → 212, to_fahrenheit(0) → 32.

Logic error

pythonEasy
Floating point subtraction in price calculator leaves precision artifact

calculate_discounted_price(price, discount) subtracts discount from price rounded to 2 decimal places. Example: calculate_discounted_price(0.3, 0.2) → 0.1.

Logic error

pythonEasy
Boolean evaluation on custom empty container treats object as false

is_valid_cart_container(items) returns True if cart was successfully initialized as an object, even if items is empty. Example: is_valid_cart_container([]) → True.

Logic error

pythonEasy
Weekend check says Monday is the weekend

is_weekend(day) returns True for "Saturday" and "Sunday", and False for other days. Example: is_weekend("Monday") → False.

Logic error

javascriptEasy
Zero percent promo code triggers fallback discount

calculate_discounted_total(subtotal, promoPercent) applies promoPercent to subtotal, falling back to 15% only if promoPercent is missing or undefined. Example: calculate_discounted_total(100, 0) → 100.

Logic error

javascriptEasy
Splitting empty string returns array with length one

count_csv_tags(tagString) returns the number of comma-separated tags in a string, returning 0 for an empty string. Example: count_csv_tags("") → 0.

Logic error

pythonEasy
Contact list puts capital names first

sort_contacts(names) sorts names A to Z, ignoring capitals. Example: sort_contacts(["bob", "Carl", "alice"]) → ["alice", "bob", "Carl"].

Logic error

pythonEasy
Floor division on negative number rounds away from zero

divide_truncate_toward_zero(a, b) divides a by b, truncating the fractional part toward zero. Example: divide_truncate_toward_zero(-7, 2) → -3.

Logic error

javascriptEasy
Checking property with in operator matches prototype methods

has_custom_field(payload, fieldName) returns true only if fieldName is an own property of payload, ignoring inherited prototype properties. Example: has_custom_field({}, "toString") → false.

Logic error

javascriptEasy
isEven says 4 is not even

isEven(n) returns true when n is even and false when it is odd. Example: isEven(4) → true, isEven(3) → false.

Logic error

javascriptEasy
Sort comparator returning boolean never returns negative one

sort_numbers_ascending(numbers) sorts numbers in ascending order using a custom comparator. Example: sort_numbers_ascending([10, 2, 5, 1]) → [1, 2, 5, 10].

Logic error

pythonEasy
Joining path with leading slash discards base directory

build_api_endpoint_path(base_path, sub_path) joins base_path and sub_path into a complete path string. Example: build_api_endpoint_path("/api/v1", "/users") → "/api/v1/users".

Logic error

javascriptEasy
Free shipping not given at exactly 50

qualifiesForFreeShipping(total) returns true when the order is 50 or more. Example: qualifiesForFreeShipping(50) → true, qualifiesForFreeShipping(49.99) → false.

Logic error

pythonEasy
Index method on list raises ValueError when item is missing

safe_find_index(items, target) returns the index of target in items, returning -1 if missing. Example: safe_find_index([1, 2], 99) → -1.

Logic error

pythonEasy
Dictionary fromkeys shares default mutable list across all keys

create_user_role_buckets(roles, initial_admin) initializes an empty list for each role and adds initial_admin to the first role. Example: create_user_role_buckets(["admin", "guest"], "alice") → {"admin": ["alice"], "guest": []}.

Logic error

pythonEasy
Removing even numbers while looping skips adjacent items

remove_even_numbers(numbers) removes all even integers and returns a list containing only odd numbers. Example: remove_even_numbers([2, 4, 6]) → [].

Logic error

pythonEasy
All function on empty user list evaluates to true

are_all_accounts_verified(accounts) returns True only if accounts is non-empty and every account is verified. Example: are_all_accounts_verified([]) → False.

Logic error

pythonEasy
Round function rounds 2.5 down to 2 instead of up to 3

round_order_rating(rating) rounds rating to the nearest integer using standard round-half-up math. Example: round_order_rating(2.5) → 3.

Logic error

javascriptEasy
Array indexOf looking up object returns negative one

find_user_position(users, id) returns the index of the user object with matching id, or -1 if missing. Example: find_user_position([{ id: 1 }, { id: 2 }], 2) → 1.

Logic error

pythonEasy
Leaderboard shows the three worst players

top_three(scores) returns the 3 highest scores, best first. Example: top_three([50, 90, 70, 80]) → [90, 80, 70].

Logic error

javascriptEasy
Palindrome check fails on capitalised words

isPalindrome(word) returns true if the word reads the same backwards, ignoring capitals. Example: isPalindrome("Racecar") → true.

Logic error

pythonEasy
Matching digits inside string returns None with re match

extract_first_digits(text) returns the first sequence of digits found anywhere in text. Example: extract_first_digits("order_123") → "123".

Logic error

pythonEasy
Search gives up after checking one item

contains(items, target) returns True if target is anywhere in the list. Example: contains([4, 8, 15], 8) → True.

Logic error

javascriptEasy
Validator never finds the negative number

hasNegative(nums) returns true if any number is negative. Example: hasNegative([5, -3, 8]) → true.

Logic error

pythonEasy
Even-number total adds up the odd ones

sum_evens(nums) adds up only the even numbers. Example: sum_evens([1, 2, 3, 4]) → 6.

Logic error

javascriptEasy
Number sort puts 10 before 2

sortNumbers(arr) sorts numbers from smallest to largest. Example: sortNumbers([10, 2, 30]) → [2, 10, 30].

Logic error

javascriptEasy
Encoding query redirect URL with encodeURI leaves delimiters unescaped

create_safe_redirect_url(targetUrl) encodes targetUrl as a query parameter in a redirect link. Example: create_safe_redirect_url("https://example.com/oauth?code=123") → "https://api.com?redirect=https%3A%2F%2Fexample.com%2Foauth%3Fcode%3D123".

Logic error

pythonEasy
Doubling the prices doubles the list instead

double_all(prices) doubles every price. Example: double_all([1, 2, 3]) → [2, 4, 6].

Logic error

pythonEasy
Integer division for pagination leaves remainder items out

calculate_total_pages(total_items, page_size) returns the total number of pages required to display all items. Example: calculate_total_pages(11, 5) → 3.

Logic error

pythonEasy
Removing duplicate items with set scrambles original order

deduplicate_preserve_order(items) removes duplicates while preserving the original appearance order. Example: deduplicate_preserve_order(["b", "a", "c", "a"]) → ["b", "a", "c"].

Logic error

pythonEasy
Total only counts the first item

order_total(prices) adds up every price. Example: order_total([5, 10, 15]) → 30.

Logic error

pythonEasy
Checkout works without a valid payment

can_checkout(cart_total, has_valid_payment) returns True only when the cart is not empty and the payment is valid. Example: can_checkout(50, True) → True, can_checkout(50, False) → False.

Logic error

pythonEasy
Finding max on empty score list raises ValueError

find_top_score(scores) returns the highest score from scores, returning 0 if scores is empty. Example: find_top_score([]) → 0.

Logic error

javascriptEasy
Accessing last element with negative index returns undefined

get_latest_breadcrumb(breadcrumbs) returns the final item from breadcrumbs using modern indexing. Example: get_latest_breadcrumb(["home", "docs", "api"]) → "api".

Logic error

pythonEasy
Stripping protocol prefix strips domain characters as set

strip_url_protocol(url) removes the leading "https://" protocol prefix from a URL string. Example: strip_url_protocol("https://threat.com") → "threat.com".

Logic error

javascriptEasy
Array pop on array with zero element returns fallback value

pop_with_fallback(items) removes and returns the last element from items, returning -1 only if items was empty. Example: pop_with_fallback([0]) → 0.

Logic error

pythonEasy
Comparing high user IDs with is keyword returns false

is_matching_account_id(account_id, target_id) returns True if account_id matches target_id by value. Example: is_matching_account_id(1000, 1000) → True.

Logic error

javascriptEasy
Math max on empty score list returns negative infinity

get_max_score(scores) returns the highest score from scores, returning 0 if the array is empty. Example: get_max_score([]) → 0.

Logic error

javascriptEasy
Checking all items in empty cart are in stock returns true

are_all_items_in_stock(items) returns true only if items contains at least one item and every item is in stock. Example: are_all_items_in_stock([]) → false.

Logic error

javascriptEasy
Find index returning zero evaluated as falsy in condition

has_user_by_id(users, targetId) returns true if a user with targetId exists in users. Example: has_user_by_id([{ id: 'u1' }], 'u1') → true.

Logic error

pythonEasy
Prime checker thinks 1 is prime

is_prime(n) returns True if n is a prime number. Example: is_prime(7) → True, is_prime(8) → False, is_prime(1) → False.

Logic error

javascriptEasy
Deleting array element leaves empty slot instead of removing

remove_item_at_index(items, index) removes the item at index and returns the shortened array. Example: remove_item_at_index(["apple", "banana", "cherry"], 1) → ["apple", "cherry"].

Logic error

javascriptEasy
Math min on empty price list returns positive infinity

get_lowest_price(prices) returns the minimum price from prices, returning 0 if the list is empty. Example: get_lowest_price([]) → 0.

Logic error

javascriptEasy
Array shift removes first element and returns removed item

discard_oldest_log(logs) returns a new array with the first log removed, without mutating logs. Example: discard_oldest_log(["a", "b", "c"]) → ["b", "c"].

Logic error

javascriptEasy
Floating point balance calculation leaves precision artifact

calculate_remaining_balance(balance, payment) subtracts payment from balance, rounded to 2 decimal places. Example: calculate_remaining_balance(1.0, 0.9) → 0.1.

Logic error

javascriptEasy
Flattening nested category list leaves inner arrays unflattened

flatten_nested_categories(categories) flattens a deeply nested array of category names into a single flat array. Example: flatten_nested_categories([1, [2, [3, 4]]]) → [1, 2, 3, 4].

Logic error

javascriptEasy
Joining URL path parts with null leaves double slash

join_endpoint_path(parts) joins non-empty path segments with a single slash. Example: join_endpoint_path(["api", null, "users"]) → "api/users".

Logic error

pythonEasy
Word search misses a match at the start

mentions(text, word) returns True if word appears anywhere in text. Example: mentions("hello world", "hello") → True.

Logic error

javascriptEasy
Filtering products by inventory drops items with zero count

filter_valid_inventory(items) keeps all items that have a defined count property, including zero. Example: filter_valid_inventory([{ id: 1, count: 0 }]) → [{ id: 1, count: 0 }].

Logic error

javascriptHard
Out-of-stock item shows as available

isAvailable(item) is true only when the item is in stock and not discontinued. Example: isAvailable({ inStock: false, discontinued: false }) → false.

Logic error

pythonHard
Divide-by-zero check comes too late

safe_ratio(a, b) returns True when a / b is more than 1. If b is 0 it returns False instead of crashing. Example: safe_ratio(4, 2) → True, safe_ratio(1, 0) → False.

Logic error

javascriptMedium
Grouping words keeps only one per group

groupByLength(words) groups words by their length. Example: groupByLength(["ab", "cd", "x"]) → { 1: ["x"], 2: ["ab", "cd"] }.

Logic error

pythonMedium
Highest temperature reads 0 on a cold day

highest_temp(readings) returns the highest temperature of the day. Example: highest_temp([12, 18, 15]) → 18, highest_temp([-5, -2, -9]) → -2.

Logic error

pythonMedium
Admin check rejects the admin

is_admin(role) returns True for "admin" in any mix of capitals. Example: is_admin("Admin") → True, is_admin("user") → False.

Logic error

pythonMedium
Age is a year too high before the birthday

age_on(birth_iso, today_iso) returns how old someone is on a given date. Example: age_on("2000-12-25", "2024-06-01") → 23.

Logic error

pythonMedium
Shallow dictionary copy mutates original nested port in place

override_tenant_port(default_config, new_port) overrides db port in a cloned config without mutating default_config. Example: override_tenant_port({'db': {'port': 5432}}, 5433) → [5433, 5432].

Logic error

javascriptMedium
AI Attempt: Remove all occurrences

An AI assistant wrote this for a classic interview question. removeAll(arr, item) removes every copy of item from the array. Example: removeAll([1, 2, 2, 3], 2) → [1, 3].

Logic error

pythonMedium
AI Attempt: The Two Sum Trap

An AI assistant wrote this for a classic interview question. has_pair_sum(numbers, target) returns True if two different numbers in the list add up to target. Example: has_pair_sum([1, 2, 3], 5) → True, has_pair_sum([5], 10) → False.

Logic error

pythonMedium
AI Attempt: The runner-up finder

An AI assistant wrote this to find the second-best score in a quiz. second_highest(scores) returns the second-highest different score. Example: second_highest([70, 90, 80]) → 80, second_highest([90, 90, 80]) → 80.

Logic error

pythonMedium
50% off 200 comes to 150

checkout(total, pct) takes pct percent off the total. This project has two files: cart.py and pricing.py. Example: checkout(200, 50) → 100.

Logic error

javascriptMedium
Switch says Saturday is a weekday

dayType(day) returns "weekend" for Saturday and Sunday, and "weekday" for any other day. Example: dayType("Saturday") → "weekend".

Logic error

pythonMedium
AI Attempt: The anagram checker

An AI assistant wrote this for a classic interview question. is_anagram(a, b) returns True when both words use the same letters, the same number of times. Example: is_anagram("listen", "silent") → True, is_anagram("aab", "abb") → False.

Logic error

pythonMedium
Spam filter removes only the first "spam"

remove_word(words, target) removes every copy of target. Example: remove_word(["spam", "eggs", "spam"], "spam") → ["eggs"].

Logic error

pythonMedium
AI Attempt: The bracket checker

An AI assistant wrote this for a classic interview question. is_balanced(text) returns True when every ( is closed by a ) that comes after it. Example: is_balanced("(())") → True, is_balanced(")(") → False.

Logic error

pythonMedium
Leap year check says 2000 was not a leap year

is_leap_year(year) returns True for leap years. The rule: divisible by 4, but not by 100, unless also divisible by 400. Example: 2024 → True, 1900 → False, 2000 → True.

Logic error

pythonMedium
Pair finder returns the last pair, not the first

first_pair(nums, target) returns the first pair, from the left, that adds up to target. Example: first_pair([1, 2, 3, 4], 5) → [1, 4].

Logic error

pythonMedium
Duplicate finder reports each duplicate twice

find_duplicates(nums) lists each repeated value once, in the order it first appears. Example: find_duplicates([1, 2, 2, 3]) → [2].

Logic error

pythonMedium
A score of 95 gets a D

grade(score) returns "A" for 90 and above, "B" for 80–89, "C" for 70–79, "D" for 60–69 and "F" below 60. Example: grade(95) → "A".

Logic error

pythonMedium
Biggest gap between numbers comes out as -1

largest_gap(nums) returns the biggest jump between neighbouring numbers in a list that goes up. Example: largest_gap([1, 5, 6]) → 4.

Logic error

pythonMedium
Login says a registered user doesn't exist

is_registered(users, name) checks if a username exists. users maps IDs to names, like {"u1": "asha", "u2": "ravi"}. Example: is_registered(users, "asha") → True.

Logic error

pythonMedium
"All positive" check accepts a negative number

all_positive(nums) returns True only when every number is above zero. Example: all_positive([1, -2]) → False.

Logic error

javascriptMedium
Going from 100 to 150 shows -50%

percentChange(oldValue, newValue) returns the change as a percentage of the old value. Example: percentChange(100, 150) → 50.

Logic error

javascriptMedium
Cart total ignores how many of each item

cartTotal(items) adds up price × quantity for every item. This project has two files: cart.js and lineItem.js. Each item looks like { price: 10, quantity: 2 }. Example: [{ price: 10, quantity: 2 }, { price: 5, quantity: 1 }] → 25.

Logic error

Stuck on your own code?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other bug patterns