You are on page 1of 8

Python

Expressions
Types of expressions

An expression describes a computation and evaluates to a value

3
Call Expressions in Python

All expressions can use function call notation

4
Anatomy of a Call Expression

add ( 2 , 3 )

Operator Operand Operand

Operators and operands are also expressions

So they evaluate to values

Evaluation procedure for call expressions:

1. Evaluate the operator and then the operand subexpressions

2. Apply the function that is the value of the operator

to the arguments that are the values of the operands

5
Evaluating Nested Expressions

224
mul(add(4, mul(4, 6)), add(3, 5))

mul 28 8
add(4, mul(4, 6)) add(3, 5)

add 4 24 add 3 5

mul(4, 6)

mul 4 6

6
Evaluating Nested Expressions

Value of the whole expression


Operand subexpression
224
mul(add(4, mul(4, 6)), add(3, 5))

Value of subexpression 1st argument to mul


mul 28 8
add(4, mul(4, 6)) add(3, 5)

add 4 24 add 3 5

mul(4, 6)

mul 4 6

Expression tree

7
Conditional Statements

def my_abs(x):
"""Return the absolute value of x."""
if x < 0:
1 statement, return -x
3 clauses, elif x == 0:
3 headers, return 0
3 suites else:
return x

Execution Rule for Conditional Statements: Syntax Tips:

Each clause is considered in order. 1. Always starts with "if" clause.

1. Evaluate the header's expression. 2. Zero or more "elif" clauses.

2. If it is a true value, 3. Zero or one "else" clause,


execute the suite & skip the remaining clauses. always at the end.
8

You might also like