Skip to content

Empty and one

Read · 1 of 3

Start small

Code is usually written with a "normal" input in mind: a handful of different numbers. The smallest inputs are where it falls over: no items at all, or exactly one.

Look for nums[0], dividing by a length, and loops that compare neighbours. Each assumes there's something there.

Read this lesson as text

The smallest inputs break the most code.

Start small

Code is usually written with a "normal" input in mind: a handful of different numbers. The smallest inputs are where it falls over: no items at all, or exactly one.

Look for nums[0], dividing by a length, and loops that compare neighbours. Each assumes there's something there.

Nothing at all

n = int(input())
nums = list(map(int, input().split()))
first = nums[0]
print(first, len(nums))

The input may have zero numbers (0, then an empty line). What happens then?

  • It prints 0 0
  • It crashes with an IndexError
  • It prints nothing
Show the answer

It crashes with an IndexError. With no numbers, nums is empty and nums[0] doesn't exist. Check the length first.

Break it: Break the max

This should print the biggest of n numbers. Find an input where it prints the wrong answer.

n = int(input())
nums = list(map(int, input().split()))
best = 0
for x in nums:
    if x > best:
        best = x
print(best)

Input rules: first line n (1 to 20), second line n whole numbers between -1000 and 1000.