Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

0.2 Python Basics

This section introduces the small part of Python needed to express calculations clearly. Focus on reading code, predicting its result, and checking whether the result is reasonable.

Values, variables, and expressions

Python distinguishes several basic types:

float

A variable name refers to a value. Assignment evaluates the right side first and then stores the result under the name on the left.

5

Here x = x + 2 means “replace x by its old value plus 2.” It is assignment, not a mathematical equation.

Common arithmetic operators are:

OperationPythonExample result
Addition+7 + 2 gives 9
Subtraction-7 - 2 gives 5
Multiplication*7 * 2 gives 14
Division/7 / 2 gives 3.5
Integer quotient//7 // 2 gives 3
Remainder%7 % 2 gives 1
Power**7 ** 2 gives 49

Use parentheses when they make the intended order clear.

48.0

Comparisons and Booleans

Comparisons produce True or False.

(True, True, True)

Use == to compare values and = to assign a value. Combine conditions with and, or, and not.

Collections and indexing

A list stores an ordered collection of Python objects.

(2.1, 2.8, 4)

Python uses half-open slices: start is included and stop is excluded.

[2.4, 2.2]

Lists are useful for general Python data. Numerical linear algebra uses NumPy arrays, introduced in the next section.

Functions

A function packages a calculation under a name. Parameters are inputs, and return sends a result back to the caller.

10.0

Indentation defines the function body. Use four spaces for each indentation level.

Functions make assumptions easier to state and test:

1.999999999999993

Conditionals

A conditional selects code based on a Boolean condition.

'negative determinant'

Later, we will avoid exact equality tests for most floating-point calculations because rounding can produce tiny nonzero values.

Loops

A for loop repeats an action for each item in a collection.

[1, 4, 9, 16]

Loops are important for learning Python and for tasks that genuinely proceed one item at a time. For array arithmetic, NumPy operations are usually shorter and faster.

Writing readable code

Practice

Exercise 1: temperature conversion

Write a function celsius_to_fahrenheit(celsius) that implements

F=95C+32.F = \frac{9}{5}C + 32.

Test it with C=0C=0 and C=100C=100.

Solution
(32.0, 212.0)

The results should be 32.0 and 212.0.

Exercise 2: classify a number

Write a function that returns "negative", "zero", or "positive" for a given number.

Solution
('negative', 'zero', 'positive')

Exercise 3: accumulate a sum

Use a loop to find the sum of the numbers from 1 through 10. Then compare your result with sum(range(1, 11)).

Solution
(55, 55)

Both results should be 55.