National University of Singapore · FACULTY OF COMPUTER SCIENCE

CS1010E Chap.2 Numerical Expressions and Functions

- one subject, every graph, every model, every mark
8 Chapters3-page Bible
Our own words - no uploaded lecturer files
Updated for this semester
Chapter 2 of 6 · CS1010E

Numerical Expressions and Functions

What an expression is in CS1010E

Every program in this course is built from expressions, and an expression is simply a piece of Python that produces a value of one definite type. The early types are int, float and bool. A literal such as 12 is an int, 12.0 is a float, and a comparison such as 3 < 5 is a bool holding True.

You can check any value with the built-in type function, which is the quickest way to settle an argument about whether a result will print with a decimal point.

Small expressions combine into larger ones through arithmetic operators (+, -, *, /, //, %, **), comparison operators (<, <=, >, >=, ==, !=), the logical operators and, or and not, parentheses, function calls and the one-line conditional expression of the form a if condition else b.

Precedence settles which operator acts first, much like the school rule for brackets and multiplication, and associativity settles ties: subtraction and division group from the left, while exponentiation groups from the right, so 3 ** 2 ** 2 equals 81.

Two operators deserve special attention because they behave unlike a calculator key.

Integer division // and remainder % work as a pair: dividing by 1000 splits 45678 into 45 and 678, a trick that pulls digits, hours or units out of a single number. Converting with int() is a different operation again, since it cuts off the fractional part towards zero instead of flooring, which matters as soon as a value is negative.

Parentheses cost nothing and remove doubt, so use them freely.

Functions as named computations

A function definition starts with a header (the def keyword, a name and parameters) and a body that ends in return. Calling it with arguments copies those values into the parameters, evaluates the body and hands one value back.

The caller only needs to know what the function does, not how it does it, which is the idea of abstraction; a well designed function does one job well.

Parameters and variables created inside a function are local, so another function, or the shell, cannot see them.

Series, recurrences and conditions

Before loops arrive, a finite sum is expressed as a recurrence: a fixed base value for the smallest case, and a rule that adds one new term to the answer for the previous case.

The conditional expression supplies the branch between those two cases in a single return line. Conditions also matter for floats, because binary floating point cannot store values like 0.1 exactly, so two floats should be compared with a small tolerance rather than ==. Finally, and and or stop evaluating as soon as the outcome is known, which lets a guard such as y != 0 protect a division placed after it.

In this chapter

What this chapter covers

  • 01

    The int, float and bool values and the type function

  • 02

    Arithmetic operators including /, //, % and **

  • 03

    Operator precedence and associativity with expression trees

  • 04

    Defining functions with def, parameters and return

  • 05

    Function abstraction and local scope

  • 06

    Finite series written as recurrence relations

  • 07

    Comparison, logical and conditional expressions

  • 08

    Float equality with a tolerance and short-circuit guards

Worked example · free

A savings balance defined by recurrence

Q [6 marks]. A deposit of 2000 earns 5 percent interest once a year. Define growth(p, r, n) that returns the balance after n years using a recurrence and a conditional expression, trace growth(2000, 5, 3), and explain why it differs in its last digits from 2000 * 1.05 ** 3. The step weighting shown here is an AskSia study allocation and is not a University marking scheme.
Figure 2.1.Figure 2.1. Tree for 8 - 2 * 3 ** 2 // 4 . Deeper nodes are evaluated first: ** gives 9, then * and // run left to right for 18 and 4, and the root subtraction yields 4. - // * ** 8 4 2 3 2 = 4 = 18 = 9
Figure 2.1. Tree for 8 - 2 * 3 ** 2 // 4. Deeper nodes are evaluated first: ** gives 9, then * and // run left to right for 18 and 4, and the root subtraction yields 4.
  • 2State the recurrence: the balance after 0 years is p; after n years it is the balance after n - 1 years multiplied by (1 + r / 100).
  • 2Translate it into one return line: return p if n == 0 else growth(p, r, n - 1) * (1 + r / 100).
  • 2Trace the calls from the base case upwards and compare against the closed form, explaining the floating point difference.
def growth(p, r, n): return p if n == 0 else growth(p, r, n - 1) * (1 + r / 100). The call growth(2000, 5, 3) waits on growth(2000, 5, 2), which waits on n = 1 and then n = 0. The base case returns the int 2000. Unwinding, n = 1 gives 2000 * 1.05 = 2100.0, a float because / produced 1.05; n = 2 gives 2205.0; n = 3 gives 2315.25. Evaluating 2000 * 1.05 ** 3 instead prints 2315.2500000000005, since ** binds first and 1.05 cubed carries a rounding error that the step by step products happen to avoid. Both are correct to within a tiny tolerance, so a test should use abs(a - b) < 1e-9 rather than ==.
Sia tip — Write the base case of the conditional expression first, as in return p if n == 0 else ..., then fill in the rule that extends the answer by one step.
Glossary

Key terms

Expression
A piece of Python syntax that evaluates to a single value of a fixed type, such as 4 * 2 or x > 0.
Operator Precedence
The ranking that decides which operator in an expression is applied first, for example ** before * and * before +.
Associativity
The rule that groups operators of equal precedence, left to right for most operators and right to left for **.
Floor Division
The // operator, which divides and rounds the result down towards negative infinity, so -9 // 4 gives -3.
Function Abstraction
Treating a function as a named task whose purpose is known to the caller while its internal steps stay hidden.
Local Scope
The rule that parameters and variables created inside a function exist only within that function.
Recurrence Relation
A definition that gives a value for a base case and computes every other case from the previous one.
Conditional Expression
The one-line form a if condition else b, which evaluates to a when the condition is True and to b otherwise.
Short Circuit Evaluation
Stopping an and or an or as soon as its result is certain, so later parts are never evaluated.
FAQ

Numerical Expressions and Functions FAQ

Why does 0.1 + 0.2 == 0.3 return False in Python?

Floats are stored in binary, and 0.1 and 0.2 have no exact binary form, so their sum is stored as 0.30000000000000004. Compare floats by checking that the absolute difference is below a small tolerance such as 1e-9 or 1e-15.

What is the difference between / and // in Python?

The single slash always returns a float, so 9 / 3 gives 3.0. The double slash floors the quotient, returning an int when both operands are ints and a float otherwise, and it rounds negative results downward, so -9 // 4 is -3.

Is ** evaluated left to right like other operators?

No. Exponentiation groups from the right, so 3 ** 2 ** 2 is 3 ** 4, which is 81, not 9 ** 2. It also binds tighter than a leading minus sign, so -3 ** 2 evaluates to -9 unless you write (-3) ** 2.

Can a variable defined inside a function be used outside it?

No. Its scope is local to that function, and asking for it in the shell raises a NameError. Pass values in through parameters and send results out with return, which keeps each function independent of every other function.

How do I write a recursive series function without loops?

Pick the smallest case and its fixed value, then express the general case as one new term combined with a call on the smaller case. Put both in a single conditional expression after return, and test the base case before trying larger inputs.

Study strategy

Exam move

Take a sheet of mixed expressions, draw the evaluation tree for each by hand, write the predicted value and its type, and only then check in IPython. For every recurrence you meet, write the base case and the one-step rule as two plain sentences before coding the single return line.

Working through Numerical Expressions and Functions in CS1010E? Sia is AskSia’s AI Computer Science tutor — ask any CS1010E Numerical Expressions and Functions question and get a clear, step-by-step explanation grounded in how CS1010E is taught and assessed. Read this chapter free, then take your hardest questions to Sia.

A+Everything unlocked
Unlocks this Bible + all 21 of your National University of Singapore subjects - and 1,000+ Bibles across every Australian university.
Sia - your CS1010E tutor, unlimited, worked the way the exam marks it
The full 3-page Bible + practice bank with worked solutions
Chrome extension - sync your LMS so Sia knows your deadlines
Bilingual EN / Chinese on every Bible and every Sia answer
$0.99 Trial
30-day money-back · cancel in one tap · how it works