You are on page 1of 63

Python Training Course IV

Code Structure
 Comment with #
 Continue Lines with \
 Compare with if, elif, and else
 Repeat with while
 Iterate with for
 Comprehensions (Pythonic way)
 Functions, Generators, Decorators
 Namespaces and Scope
 Handle Errors with try and except
2
COMMENT WITH #

3
CONTINUE LINES WITH \

4
Compare with if, elif, and else

5
if, else
as many levels deep as needed

4 個空白,不可使用 tabs
或與空白混用

6
elif

7
Python’s comparison operators

8
What Is True?
以下為 False 除此之外是 True

9
Repeat with while

10
11
Cancel with break

12
Skip Ahead with continue

13
Check break Use with else

14
If , while 練習題

 Book P.106
 Things to Do 4.1~4.2

15
Iterate with for

16
Iterate with for

Better way

17
Iterate with for

18
Iterate with for

19
Cancel with break as it does for a while loop.

Skip with continue as it does for a while loop.

20
Check break Use with else

21
Iterate Multiple Sequences with zip()

22
Generate Number Sequences with range()

23
Comprehensions (Pythonic)

24
List Comprehensions

Pythonic way

25
List Comprehensions

Pythonic way

26
List Comprehensions (nested for)

Tuple unpacking

27
Dictionary Comprehensions

Better way

28
Set Comprehensions

29
Generator Comprehensions

A generator can be run only once. Lists, sets,


strings, and dictionaries exist in memory, but a
generator creates its values on the fly and
hands them out one at a time through an iterator.
It doesn’t remember them, so you can’t restart or
back up a generator.

30
For, Comprehesions 練習題

 Book P.106
 Things to Do 4.3~4.7

31
Functions, Generators, Decorators

32
Functions

 命名規則與變數 (variables) 相同
 定義它
 執行它

33
Functions parameters

arguments

No return 34
None is useful

35
Positional Arguments

36
Keyword Arguments

Positional 和 Keyword 混用時 , Positional 要先於 Keyword

37
Specify Default Parameter Values

38
A Common Error in Specify Default Parameter Values

Default argument values are


calculated when the function is
defined, not when it is run.
39
Gather Positional Arguments with *

40
Gather Keyword Arguments with **
You can use two asterisks ( ** ) to group keyword
arguments into a dictionary, where the argument
names are the keys, and their values are the
corresponding dictionary values.

41
Function’s Docstrings

Readability counts, says the Zen of Python.

42
Functions Are First-Class Citizens

Everything is an object includes numbers, strings,


tuples, lists, dictionaries—and functions, as well.
Functions are first-class citizens in Python.
You can assign them to variables, use them as
arguments to other functions, and return them
from functions.

43
Can combine with *args and **kwargs techniques

You can use functions as elements of lists,


tuples, sets, and dictionaries. Functions are
immutable, so you can also use them as
dictionary keys.

44
Inner Functions

An inner function can be useful when


performing some complex task more
than once within another function, to
avoid loops or code duplication.

45
Closures Closure : a dynamically created function that
remembers where it came from.

The inner2() function knows the value of saying


that was passed in and remembers it. The line
return inner2 returns this specialized copy of the
inner2 function (but doesn’t call it). That’s a
closure: a dynamically created function that
remembers where it came from.

46
Anonymous Functions: the lambda() Function

Lambdas are mostly useful for cases


in which you would otherwise need
to define many tiny functions and
remember what you called them all
47
A generator is a Python sequence
Generators creation object. With it, you can iterate
through potentially huge sequences
without creating and storing the entire
sequence in memory at once.
Generators are often the source of data
for iterators.
If you want to create a potentially
large sequence, and the code is too
large for a generator comprehension,
write a generator function.

48
Functions 練習題

 Book P.106
 Things to Do 4.8~4.9

49
Decorators A decorator is a function that takes one function as
input and returns another function.
Sometimes, you want to modify an existing function
without changing its source code. A common example
is adding a debugging statement to see what
arguments were passed in.

50
add @decorator_name before the function

51
Another example of decorator

52
Namespaces and Scope

53
Global vs. Local (I) If you define a variable called x in a
main program and another variable
called x in a function, they refer to
different things. But the walls can be
breached: if you need to, you can
access names in other namespaces in
various ways.

54
Global vs. Local (II)

55
Global vs. Local (III)

56
Global vs. Local (III)

57
Global vs. Local (IV)
• locals() returns a dictionary of the
contents of the local namespace.
• globals() returns a dictionary of the
contents of the global namespace.

58
Uses of _ and __ in Names
Names that begin and end with two
underscores ( __ ) are reserved for use
within Python, so you should not use
them with your own variables.

59
Handle Errors with try and except

60
Exception Handlers
Python uses exceptions: code that is
executed when an associated error
occurs.

61
Exception Pattern

62
練習題

 Book P.107
 Things to Do 4.10~4.12

63

You might also like