CS1010E Chap.2 Numerical Expressions and Functions
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.
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
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.
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.
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.
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.