Reading and Writing Basic Python: Values, Collections, Loops and Functions

Names, values and types

A Python assignment binds a name to a value. The name does not have a type; the value does, and the same name can be rebound to a value of a different type later.


Reading a short program therefore means tracking what each name currently refers to. The types met first are the integer, the floating-point number, the string and the boolean.


Two division operators are easy to confuse. With the built-in int and float operands used throughout this lesson, the single slash performs true division and produces a floating-point result, even when the division is exact; other numeric types, such as Decimal and Fraction, divide to their own type instead.


The double slash performs floor division, taking the floor of the exact quotient - the greatest integer that does not exceed it - and returning an integer when both operands are integers. The percent sign gives the remainder.


For example, 45 divided by 8 with a single slash gives 5.625; with a double slash it gives 5; and 45 with the percent operator against 8 gives 5 as the remainder.


The identity 8 times 5 plus 5 = 45 is a quick way to confirm that the last two agree.


Taking the floor is not the same as discarding the fractional part: -9 divided by 8 is -1.125, so -9 with the double slash against 8 gives -2, not -1.

Collections and indexing

A list is an ordered, changeable collection written with square brackets.


Indexing starts at zero, so the first element of a list is at index 0 and the last is at index -1. A slice written as start colon stop returns a new list containing the elements from the start index up to but not including the stop index.


That half-open convention is the single most common source of off-by-one errors. For a positive-step slice, when 0 ≤ start ≤ stop ≤ the list length, its length is stop minus start.


Python normalizes negative indices and clips endpoints outside the list bounds; if the effective start is at or beyond the effective stop, the result is empty.


For a five-element list nums, nums[1:9] is clipped at the end and has four elements, while nums[3:1] is empty.


prices = [12, 7, 25, 4]
prices[0]        gives 12
prices[-1]       gives 4
prices[1:3]      gives [7, 25]
len(prices)      gives 4
sum(prices)      gives 48


A tuple, written with round brackets, is like a list but cannot be changed after creation. A dictionary, written with braces, stores values under keys rather than positions and is retrieved by key rather than by index.

Conditionals and loops

Blocks in Python are marked by indentation rather than by braces, so the indentation is part of the program's meaning.


A conditional runs its block when the test is true; a for loop runs its block once for each item in a sequence.


The built-in range function generates integers from a start value up to but not including a stop value, using the same half-open convention as slicing, so range(1, 5) produces 1, 2, 3 and 4.


prices = [12, 7, 25, 4]
running = 0
for p in prices:
    if p % 2 == 0:
        running = running + p
print(running)


Reading this carefully: the loop visits each price in turn, the conditional admits only the even ones, which are 12 and 4, and the running total ends at 16. Note the difference between the single equals sign, which assigns, and the double equals sign, which tests for equality.

Defining and calling functions

A function is defined with def, a name, a parameter list and an indented body.


The return statement hands a value back to the caller; a function that reaches the end of its body without returning gives back the special value None. Parameters may be given default values, which are used when the caller omits that argument.


def span(values, scale=1.0):
    return (max(values) - min(values)) * scale

span([12, 7, 25, 4])        gives 21.0
span([12, 7, 25, 4], 2.0)   gives 42.0


The result of the first call is a float rather than an integer because the default scale is a float, and multiplying an integer by a float produces a float.

Assignment does not copy a list

This is the idea that catches most newcomers. Assigning one name to another does not duplicate the underlying list; it makes a second name for the same object, so a change made through one name is visible through the other.


To obtain an independent outer list, take a full slice or call the list's copy method.


Both make a shallow copy: the new list can be extended, shortened or have its elements replaced without touching the original, but any nested mutable elements are still shared with it and need a copy of their own.


The same distinction governs what a function can do to its arguments. Rebinding a parameter inside a function - assigning a new object to it - affects only the local name and leaves the caller's list untouched.


Calling a method that modifies the list in place changes the object that the caller also refers to.


Deciding which of the two a line performs is the reliable way to predict the outcome, and it matters well beyond toy examples, since a function that quietly alters the data it was handed is a frequent source of statistical bugs.

Common misconceptions

  • A slice or a range does not include its stop value. Both are half-open.
  • The double slash is not rounding. It takes the floor, which for negative operands is not the same as truncating towards zero.
  • A function without a return statement does not return the last value computed; it returns None.

What value does the expression 7 // 2 produce in Python?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A program defines nums = [10, 20, 30, 40, 50]. What does nums[1:4] evaluate to?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Determine what the following program prints. Report the printed value as a decimal number.

total = 0
for k in range(1, 6):
    if k % 2 == 1:
        total += k * k
print(total)

Give your answer as a number.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors