0% found this document useful (0 votes)
11 views

03 Control 1pp

The None value in Python represents nothing or no value. A function that does not explicitly return a value will return None. None is not displayed by the interpreter when it is the value of an expression. Printing None has no visible output. Functions that have side effects like printing are called non-pure functions, while functions that just return values without side effects are called pure functions. Code blocks are executed in separate environments, with nested function calls creating new local environments.

Uploaded by

方欧文
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

03 Control 1pp

The None value in Python represents nothing or no value. A function that does not explicitly return a value will return None. None is not displayed by the interpreter when it is the value of an expression. Printing None has no visible output. Functions that have side effects like printing are called non-pure functions, while functions that just return values without side effects are called pure functions. Code blocks are executed in separate environments, with nested function calls creating new local environments.

Uploaded by

方欧文
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Control

Announcements
Print and None

(Demo)
None Indicates that Nothing is Returned

The special value None represents nothing in Python

A function that does not explicitly return a value will return None

Careful: None is not displayed by the interpreter as the value of an expression

>>> def does_not_return_square(x):


... x * x
No return
...
None value is not displayed
>>> does_not_return_square(4)
The name sixteen >>> sixteen = does_not_return_square(4)
is now bound to
the value None >>> sixteen + 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

4
Pure Functions & Non-Pure Functions

Return value
Pure Functions
just return values -2 abs
2
Argument

2, 100 pow
1267650600228229401496703205376
2 Arguments

Returns None!
Non-Pure Functions
have side effects -2 print
None
A side effect isn't a
value; it's anything
Python displays the output “-2” that happens as a
consequence of
calling a function

5
Nested Expressions with Print

None, None print(...):


None Does not get
displayed

display “None None”


None
print(print(1), print(2))

func print(...) None None


print(1) print(2)

func print(...) 1 func print(...) 2

1 print(...): 2 print(...):
None None

display “1” display “2”

6
Multiple Environments
Life Cycle of a User-Defined Function
What happens?
Formal parameter
Return
Name expression
Def statement: >>> def square( x ): A new function is created!

return mul(x, x) Name bound to that function


Def
statement in the current frame
Body (return statement)

operand: 2+2 Operator & operands evaluated


Call expression: square(2+2) argument: 4
Function (value of operator)
called on arguments
operator: square (values of operands)
function: func square(x)

A new frame is created!


Calling/Applying: 4 square( x ):
Parameters bound to arguments
Argument 16
Signature
Body is executed in that new
Return value environment
8
(Demo)
Multiple Environments in One Diagram!

square(square(3))

func square(x)
square(3)

func square(x) 3

http://pythontutor.com/composingprograms.html#code=from%20operator%20import%20mul%0Adef%20square%28x%29%3A%0A%20%20%20%20return%20mul%28x,%20x%29%0Asquare%28square%283%29%29&cumulative=true&curInstr=0&mode=display&origin=composingprograms.js&py=3&rawInputLstJSON=%5B%5D
9
Multiple Environments in One Diagram!

square(square(3))

func square(x) 9
square(3)

func square(x) 3

http://pythontutor.com/composingprograms.html#code=from%20operator%20import%20mul%0Adef%20square%28x%29%3A%0A%20%20%20%20return%20mul%28x,%20x%29%0Asquare%28square%283%29%29&cumulative=true&curInstr=0&mode=display&origin=composingprograms.js&py=3&rawInputLstJSON=%5B%5D
10
Multiple Environments in One Diagram!

1
81
square(square(3))

func square(x) 9
square(3) An environment is a sequence of frames.

• The global frame alone


func square(x) 3
• A local, then the global frame
http://pythontutor.com/composingprograms.html#code=from%20operator%20import%20mul%0Adef%20square%28x%29%3A%0A%20%20%20%20return%20mul%28x,%20x%29%0Asquare%28square%283%29%29&cumulative=true&curInstr=0&mode=display&origin=composingprograms.js&py=3&rawInputLstJSON=%5B%5D
11
Names Have No Meaning Without Environments

1
Every expression is
evaluated in the context
of an environment.

A name evaluates to the


value bound to that name An environment is a sequence of frames.
in the earliest frame of
the current environment in • The global frame alone
which that name is found.
• A local, then the global frame
http://pythontutor.com/composingprograms.html#code=from%20operator%20import%20mul%0Adef%20square%28x%29%3A%0A%20%20%20%20return%20mul%28x,%20x%29%0Asquare%28square%283%29%29&cumulative=true&curInstr=0&mode=display&origin=composingprograms.js&py=3&rawInputLstJSON=%5B%5D
12
Names Have Different Meanings in Different Environments

A call expression and the body of the function being called


are evaluated in different environments

Every expression is
evaluated in the context
of an environment.

A name evaluates to the


value bound to that name
in the earliest frame of
the current environment in
which that name is found.

13
http://pythontutor.com/composingprograms.html#code=from%20operator%20import%20mul%0Adef%20square%28square%29%3A%0A%20%20%20%20return%20mul%28square,%20square%29%0Asquare%284%29&cumulative=true&curInstr=0&mode=display&origin=composingprograms.js&py=3&rawInputLstJSON=%5B%5D
Miscellaneous Python Features

Division
Multiple Return Values
Source Files
Doctests
Default Arguments

(Demo)
Conditional Statements
Statements

A statement is executed by the interpreter to perform an action

Compound statements:

Statement The first header determines a


Clause statement’s type

<header>:
<statement> The header of a clause
<statement> Suite “controls” the suite that
... follows
<separating header>:
<statement>
<statement> def statements are compound
... statements
...

16
Compound Statements

Compound statements:
A suite is a sequence of
<header>: statements
<statement>
Suite
<statement>
...
<separating header>: To “execute” a suite means to
<statement> execute its sequence of
<statement> statements, in order
...
...

Execution Rule for a sequence of statements:

• Execute the first statement

• Unless directed otherwise, execute the rest

17
Conditional Statements

def absolute_value(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.
18
Boolean Contexts

def absolute_value(x):
"""Return the absolute value of x."""
if x < 0:
return -x
elif x == 0:
return 0
else:
return x

George Boole

19
Boolean Contexts

def absolute_value(x):
"""Return the absolute value of x."""
if x < 0:
return -x
elif x == 0: Two boolean contexts
return 0
else:
return x

George Boole

False values in Python: False, 0, '', None (more to come)

True values in Python: Anything else (True)

Read Section 1.5.4!

(Demo)
20
Reading: http://composingprograms.com/pages/15-control.html#conditional-statements
Iteration
While Statements

(Demo)

1 2 3
1 3 6

Execution Rule for While Statements:


George Boole
1. Evaluate the header’s expression.

2. If it is a true value,
execute the (whole) suite,
then return to step 1.

(Demo)
22
Example: Prime Factorization
Prime Factorization

Each positive integer n has a set of prime factors: primes whose product is n

...
8 = 2 * 2 * 2
9 = 3 * 3
10 = 2 * 5
11 = 11
12 = 2 * 2 * 3
...

One approach: Find the smallest prime factor of n, then divide by it

858 = 2 * 429 = 2 * 3 * 143 = 2 * 3 * 11 * 13

(Demo)

24

You might also like