More Related Content Similar to Python Jump Start (20) More from Haim Michael (20) Python Jump Start1. Python Crash Course
Haim Michael
February 10th
, 2020
All logos, trade marks and brand names used in this presentation belong
to the respective owners.
lifemichael
2. © 1996-2018 All Rights Reserved.
Haim Michael Introduction
● Snowboarding. Learning. Coding. Teaching. More
than 18 years of Practical Experience.
lifemichael
3. © 1996-2018 All Rights Reserved.
Haim Michael Introduction
● Professional Certifications
Zend Certified Engineer in PHP
Certified Java Professional
Certified Java EE Web Component Developer
OMG Certified UML Professional
● MBA (cum laude) from Tel-Aviv University
Information Systems Management
lifemichael
5. © 2008 Haim Michael 20150805
What is Python?
Python is an open source free portable powerful and a
remarkable easy to learn scripting based programming
language.
Python is used for the development of server side applications
as well as for the development of stand alone ones.
Python is named after Monty Python.
7. © 2008 Haim Michael 20150805
Why Python?
The Python programming language focuses on readability.
Being readable, the source code written in Python is reusable,
maintainable and of an higher quality.
A variety of integration mechanisms allow us to develop code
that can easily communicate with other parts of the
application, even if written in another software programming
language, such as C, C++, Java and C#. The other way
around is available as well.
8. © 2008 Haim Michael 20150805
Why Python?
Python is known for its productivity. Code written in Python is
shorted than the equivalent written in Java or C++. In addition,
Python development cycle is simpler. There is no need in any
lengthy compile and linking phases.
Python has a large collection of ready to use functionality,
known as the standard library. That library can be extended
by adding more libraries, as well as libraries developed by
third party developers.
9. © 2008 Haim Michael 20150805
Why Python?
Variety of third party development tools for the Python
programming language allow us using that language for
various tasks, such as web sites development, games
development, Matlab equivalent programming and others.
Code written in Python usually doesn't require any change in
order to execute it on another computer platform. Porting from
one platform to another is straight forward.
10. © 2008 Haim Michael 20150805
Why Python?
Python has excellent support for most of the common object
oriented programming mechanisms.
Python is a popular and enjoyable programming language,
already been used by more than 1 million of developers from
all over the world. Python is been used by a huge growing
number of big companies, such as Google and others.
11. © 2008 Haim Michael 20150805
Why Python?
Python is free. It is an open source programming language
you are free to use and distribute.
Python memory management is automatic. Garbage collector
tracks all memories allocations.
12. © 2008 Haim Michael 20150805
Why Python?
Python is a dynamic type programming language. It keeps
tracking after all objects the program uses when it executes.
There is no need to declare the variables with a specific type
and a specific size. There is no such thing a type or a variable
declaration.
13. © 2008 Haim Michael 20150805
Real World Samples
The google web search systems was largely developed in
Python.
The youtube video sharing service was largely developed in
Python.
The famous BitTorrent peer-to-peer files sharing system
was developed in Python.
The Google Apps web development framework uses Python
extensively.
14. © 2008 Haim Michael 20150805
Real World Samples
Maya, a 3D modeling and animation system provides a
scripting API in Python.
Big financial companies usually use Python in the
development of financial applications.
15. © 2008 Haim Michael 20150805
Python History
Python first implementation was introduced in 1989 by Guido
van Rossum at CWI as a successor to the ABC programming
language.
Python 2.0 was released in October 2000. This release
introduced a garbage collection and built in support for
Unicode.
16. © 2008 Haim Michael 20150805
Python History
Python 3.0 was released in December 2008. The changes in
this version are so big that it includes a unique tool the
converts Python code written in prior version into a Python 3.0
compatible one.
17. © 2008 Haim Michael 20150805
The Python Software Foundation
The Python Software Foundation (PSF) is a formal nonprofit
organization. PSF is responsible for organizing conferences
and it also handles various legal issues related to Python.
18. © 2008 Haim Michael 20150805
The First Program
Writing a program in Python is relatively simple. The following
code prints out “hello students” to the screen.
print(“hello students”);
The source file is saved with the “.py” extension.
In order to execute the above code the simplest would be
installing the Python environment on your machine and use
an IDE, such as PyCharm.
We can turn a Python script into an executable program.
19. © 2008 Haim Michael 20150805
The Python Virtual Machine
Our code is compiled into some sort of a Python byte code
that is executed on a Python virtual machine.
20. © 2008 Haim Michael 20150805
Jython
Jython is a Java implementation of Python. Code written in
Python is translated into Java byte code, that is executed on
the Java virtual machine.
www.jython.org
21. © 2008 Haim Michael 20150805
IronPython
IronPython is a .NET implementation of Python. Code written
in IronPython is translated into CLR code, that is executed on
the same virtual machine that executes other .NET
programming languages.
www.ironpython.net
22. © 2008 Haim Michael 20150805
Modules Import
Each Python source code file that ends with the “.py”
extension is a module.
We can import one module into another by using the
'import' command.
23. © 2008 Haim Michael 20150805
Modules Import
def sum(numA,numB):
return numA+numB
import abelskiutils
temp = abelskiutils.sum(4,3)
print(temp)
abelskiutils.py
hello.py
24. © 2008 Haim Michael 20150805
Python Version
You can easily check the version of the Python version you
are using by importing sys and referring sys.version.
import sys
print (sys.version)
25. © 2008 Haim Michael 20150805
Comments
We write comments using the '#' mark. Placing the '#' mark,
all code that follows it to the end of the line is considered to
be a comment and is ignored.
numA = 4 #assigning numA with the value 4
numB = 3 #assigning numB with the value 3
numC = numA + numB #assigning numC with the sum of
#numA and numB
26. © 2008 Haim Michael 20150805
Comments
We can write comments that span over multiple lines by
using the “”” string.
a = 3
b = 4
c = a+b
"""
c = c * 10
c = c +1000000000
"""
print(c)
27. © 2008 Haim Michael 20150805
The Python Package Index
The python package index is a website that lists all python's
available packages. You can easily install new packages by
using the pip3 utility.
28. © 2008 Haim Michael 20150805
The Python Package Index
29. © 2008 Haim Michael 20150805
The Python Package Index
31. © 2008 Haim Michael 20150805
Introduction
The data in Python is in the form of objects, either objects of
new types we define or objects of built-in types that Python
provides.
An object in Python, as in other OOP languages, is just a
piece of memory with values and associated operations.
As we shall see, there are no type declarations in Python. The
syntax of the executed expression determines the types of the
objects we create and use.
32. © 2008 Haim Michael 20150805
The Program Structure
Programs developed in Python share a similar structure.
Each program is composed of modules. Modules contain
statements. Statements contain expressions. Expressions
create and process objects.
Everything we process in Python is actually a kind of an
object.
33. © 2008 Haim Michael 20150805
Samples for Built-in Types
Type Examples
float 12.4
str 'abc', “abc”, “ab'c”, “0xA12”
list [12, [2,3,4], 'a']
dict {'one':'The One', 'two': 'Two Files'}
tuple (1, 'abc', 23, “A”)
set {'a', 'b', 'c'}
34. © 2008 Haim Michael 20150805
The type Function
Using the type function we can get the type of values we
have in our code.
a = [3,5,21,23,5]
print(type(a))
35. © 2008 Haim Michael 20150805
Dynamically Typed
Python is dynamic type programming language. It keeps
tracking the types automatically. Python doesn't require us
to specify the types.
At the same time, Python is also a strongly typed language.
We can perform on a given object those operations that are
valid for its type only.
36. © 2008 Haim Michael 20150805
Types Categories
The available types are grouped into categories. Each category
and its characteristics.
37. © 2008 Haim Michael 20150805
The Numbers Category
This category includes the following types:
int, float, long, decimal and complex.
Each type of this category is expected to support addition,
multiplication etc.
38. © 2008 Haim Michael 20150805
The Sequences Category
This category includes string, list, bytearray,
buffer and tuple.
Each type of this category are expected to support indexing,
slicing and concatenation.
39. © 2008 Haim Michael 20150805
The Sequences Category
a = [3,5,21,23,5,"fafa"]
a.append(499)
print(a)
40. © 2008 Haim Michael 20150805
The Set Category
This category includes set and frozenset.
Each type of this category is expected to support operators
that were defined for this category.
41. © 2008 Haim Michael 20150805
The Set Category
a = {3,5,21,23,5,"fafa",5,3,23,23,"fafa"}
print(a)
42. © 2008 Haim Michael 20150805
The Mappings Category
This category includes dict. Having an object of the dict type
we can use it to hold key-value pairs.
43. © 2008 Haim Michael 20150805
The Mappings Category
a = { 123123:"haim michael", 42534:"moshe solomon",
454234:"david magen"}
print(a.get(542534))
44. © 2008 Haim Michael 20150805
Numeric Types
Python's numeric types include the following main types:
Integer, Floating Point Numbers, Complex Numbers, Fixed Precision Decimal
Numbers, Rational Fraction Numbers, Sets, Booleans, and Unlimited Integer
Precision.
45. © 2008 Haim Michael 20150805
Numeric Literals
Python supports the following basic numeric literals.
Literal Interpretation
129, -4.5, 9000000000000000000000 Integers (unlimited size)
2.5, 55.3, 1.22e21 Floating Point Numbers
0o345, 0x98a, 0b1001100 Octal, Hexadecimal and Binary
3+2j, 2.0+4.2j, 2J Complex Numbers
46. © 2008 Haim Michael 20150805
Mixed Types Conversion
When having a mixed type expression, Python first converts
the operands up to to the type of the most complex operand,
and then completes the calculation.
5 + 2.2 #evaluated to 7.2
This mixed types expressions' conversion takes place when
dealing with numeric types only.
47. © 2008 Haim Michael 20150805
Types Conversion
We can force a type conversion by calling one of the
available built-in functions.
int(4.2+1.2)
float(40)
48. © 2008 Haim Michael 20150805
Variables
Variables are created when they are first assigned with a
value.
num = 12 #There is no need to define a variable in advance
When been used within an expression they are replaced
with their values.
numA = 2
numB = 3
total = numA + numB
49. © 2008 Haim Michael 20150805
Variables
Variables we use in expressions must be assigned with a
value before we use them.
Each variable refers an object. There is no need to create
that object in advance. These objects are created
automatically behind the scene.
50. © 2008 Haim Michael 20150805
Variables, Objects & References
A variable is created when the code first assigns it a value.
Other assignments that take place after the variable was
already created will change the value the variable holds.
A variable doesn't have any type information or constraints
regarding the value it can hold. The type information as well
as the constraints are associated with the objects their
references are held by variables.
51. © 2008 Haim Michael 20150805
Variables, Objects & References
The value we can assign a variable is a reference for a
specific object.
When a variable is been used within an expression it is
immediately replaced with the object the variable holds its
reference.
num FA24B
an object that
represents the numeric
value 242
num = 242
52. © 2008 Haim Michael 20150805
Variables, Objects & References
Variables don't have a type. Assigning a new referent to our
variable simply makes the variable reference a different type
of object.
53. © 2008 Haim Michael 20150805
Objects are Garbage Collected
Whenever a variable is assigned with a referent for a new
object the space held by the prior object is reclaimed
(unless that object is still referenced by another name or
object).
This automatic reclamation of objects' space is known as
garbage collection.
54. © 2008 Haim Michael 20150805
Objects are Garbage Collected
Each object has a counter through which it keeps tracking
after the number of references currently pointing at it. When
that counter reaches zero the object's memory is
automatically reclaimed
55. © 2008 Haim Michael 20150805
Shared References
Each variable holds a reference for a specific object.
Assigning one variable to another will cause the two to hold
the same reference for the very same specific object.
58. © 2008 Haim Michael 20150804
Introduction
The Python programming language supports a huge range of
various operators.
59. © 2008 Haim Michael 20150804
Operators
Python supports the following standard expression
operators.
Operator Description
X if Y else z if y is true x is evaluated, if not z is evaluated
X or Y if x is false y is evaluated
X and Y if x is true y is evaluated
not X logical negation
X in Y, X not in Y Memberships (Iterables, Sets)
60. © 2008 Haim Michael 20150804
Operators
Operator Description
X is Y, X is not Y Objects Identity
X < Y, X<=Y, X>Y, X>=Y Magnitude Comparison
X == Y, X!= Y Equality Comparison
X + Y Addition, Concatenation
X – Y Subtraction, Set Difference
61. © 2008 Haim Michael 20150804
Operators
Operator Description
X * Y Multiplication, Repetition
X % Y Reminder, Format
X / Y, X // Y Division
-X, -Y Negation
X ** Y Power
X[i] Indexing (sequence, mapping)
X[i:j] Slicing
X(...) Call (function, method, class...)
62. © 2008 Haim Michael 20150804
Operators Precedence
The operators shown in the previous slides are listed in
accordance to their precedence, starting with those that
have the lowest precedence.
Using parentheses we can group sub expressions and by
doing so override the precedence rules.
(4+5) * 2 #should evaluate to 18
4 + 5 * 2 #should evaluate to 14
63. © 2008 Haim Michael 20150804
Floor & Classic Divisions
Using the '/' classic division operator we shall get a result
that includes the fraction part (if exists).
a = 42 / 8 #a will be assigned with 5.25
Using the '//' floor division operator we shall get a result that
doesn't include any fraction part. The result is truncated
down to its floor.
a = 42 // 8 #a will be assigned with 5
b = -42 // 8 #b will be assigned with -6
65. © 2008 Haim Michael 20170720
Introduction
Statements are those code fragments that tell the execution
environment what the program should do.
Python is a procedural statement based language.
When combining statements we get a procedure that
instructs the execution environment to do what we want our
program to do.
Statements are composed of expressions. Expressions
process objects.
66. © 2008 Haim Michael 20170720
Introduction
Statements are those code fragments that tell the execution
environment what the program should do.
Python is a procedural statement based language.
When combining statements we get a procedure that
instructs the execution environment to do what we want our
program to do.
Statements are composed of expressions. Expressions
process objects.
67. © 2008 Haim Michael 20170720
Introduction
Modules are composed of statements. The modules
themselves are managed with statements.
Some statements create entirely new objects, such as
functions, classes etc.
68. © 2008 Haim Michael 20170720
The Syntax
Python compound statements (e.g. statements with nested
statements inside them) follow the same general pattern of
a header line terminated in a colon, followed by a nested
block of code usually indented underneath the header line.
if x>y:
x = 12
y = 14
Python adds the colon character (:) to be used when coding
compound statements.
69. © 2008 Haim Michael 20170720
The Syntax
There is no need in parentheses. The indentation kept in all
lines is the indication for having a compound statement.
if a>b:
print('bla bla')
print('qua qua')
The end of the line is the end of the statement. We don't
place semicolon in order to mark the end of a statement.
The end of the indentation is the end of the block.
70. © 2008 Haim Michael 20170720
The Syntax
It is possible to have several statements in the same line by
placing semicolons as separator signs between the
statements.
71. © 2008 Haim Michael 20170720
The Syntax
We can span simple single statements over more than one
line by placing it within a brackets, parentheses or square
brackets.
72. © 2008 Haim Michael 20170720
Try Statements
We can use the 'try' keyword to mark a block that if an error
is raised while executed then the block of code following
'except' shall be executed and if all goes well then the block
of code following 'else' would be the one that is executed.
try:
...
except:
...
else:
...
74. © 2008 Haim Michael 20170720
Assignments
We write the target of our assignment on the left of the '='
equals sign and the object its reference we want to assign
on the right.
ob = 122
The assignment always create a reference for the assigned
object. The reference is the one that is assigned to the
variable. The variable holds a reference.
75. © 2008 Haim Michael 20170720
Assignments
The variable is created the first time we assign it a value.
There is no need to define a variable in advance. If we use a
variable before it was assigned we shall get an exception.
The assignment might take place implicitly in different
cases, such as when we import a module, invoke a function
or instantiate a class.
76. © 2008 Haim Michael 20170720
Basic Form Assignment
The basic form assignment is the most common one. We
bind a name (or a data structure element) with the reference
of a single specific object.
ob_a = 'abc'
ob_b = 122
ob_c = 4.5
77. © 2008 Haim Michael 20170720
The 'if' Statements
The 'if' statement selects the action to be performed. The
'if' statement takes the form of an 'if' test, followed by one
or more optional 'elif' ('else if') tests and a final
optional 'else' block.
Each 'elif' as well as the optional 'else' in the end have
an associated block of nested statements, indented under a
header line.
78. © 2008 Haim Michael 20170720
The 'if' Statements
if <test_1>:
statement_1
elif <test_2>:
statement_2
elif <test_3>:
statement_3
else:
statement
81. © 2008 Haim Michael 20170720
Truth Tests
Nonzero number and nonempty collections are considered as
true.
Zero as well as empty collections are considered as false.
The special object 'None' is considered as false as well.
Comparisons and equality tests return either True or False.
82. © 2008 Haim Michael 20170720
Truth Tests
Both True and False are objects of the type bool.
Python supports the following Boolean operators:
and
or
not
Calling or on two objects we will get back the first object
that is evaluated as True or the second one if both of the
two objects are False.
83. © 2008 Haim Michael 20170720
Truth Tests
Calling and on two objects will get back the second object if
the first object is equivalent to True and the first object if
equivalent to False.
85. © 2008 Haim Michael 20170720
Truth Tests
Comparisons two objects using the the == operator works
recursively when applying them to data structures.
87. © 2008 Haim Michael 20170720
The if/else Ternary Expression
We can get a ternary expression by using a simple if
statement in the following way.
a = Y if X else Z
88. © 2008 Haim Michael 20170720
The while Loop
The while loop is composed of a header line that
includes a test expression, a body that includes one (or
more) indented statements and an optional else part that
is executed if control exits the loop without a break
statement.
while <test>:
<statements>
else:
<statements>
92. © 2008 Haim Michael 20170720
The for Loop
The for loop in Python is a generic sequence iterator.
It can step through the items of any ordered sequence
object, as strings, lists, tuples and new classes we can
define.
for <target> in <object>:
<statements>
else:
<statements>
93. © 2008 Haim Michael 20170720
The for Loop
The for loop starts with a header line that specifies an
assignment along with the object we want to step through.
The header is followed by a block of statements we want
to repeat. That block must be indented.
94. © 2008 Haim Michael 20170720
The for Loop
We can use the for loop to iterate any kind of a sequence
object. In addition, we can include within our for loop a
tuple assignment.
95. © 2008 Haim Michael 20170720
The for Loop
Working with dictionaries we can iterate the keys and use
them to get the values.
96. © 2008 Haim Michael 20170720
The for Loop
Calling the items() method on our dictionary we can get a
list of items, each one of them composed of a key together
with a value. We can then iterate those items using a simple
for loop.
97. © 2008 Haim Michael 20170720
The for Loop
Using starred names we can collect multiple items. Doing so
we can extract parts of nested sequences in the for loop.
98. © 2008 Haim Michael 20170720
The for Loop
We can nest one loop within another. There is no limit for
the number of levels.
99. © 2008 Haim Michael 20170720
The for Loop
We can execute the for loop on every sequence type,
including lists, tuples and strings.
100. © 2008 Haim Michael 20170720
The for Loop
The for loop is even more generic. It can work on every
iterable object. One example is having the for loop running
over a file we open printing out to the screen each one of its
lines in a separated line.
102. © 2008 Haim Michael 20151020
Introduction
Each function is a collection of statements that can be
executed more than once in a program.
Functions can receive arguments and they can calculate
and return a value back to the caller.
103. © 2008 Haim Michael 20151020
The def Statement
We create a function by calling the def statement. Each
function we create is assigned with a name. We can later
use that name in order to call it.
def function_name (param1, param2, param3,... paramN):
statements
104. © 2008 Haim Michael 20151020
The def Statement
The execution of 'def' takes place in run-time. Only then the
object function is created.
The definition of our function is a statement. We can place a
function definition wherever we can place a statement.
105. © 2008 Haim Michael 20151020
The def Statement
def sum(a,b):
total = a + b
return total
print(sum(4,3))
107. © 2008 Haim Michael 20151025
Introduction
Using the class statement we create a class object and
assign it with a name.
The class object is kind of a factory we can use to create
objects in accordance with the template our class object
represents.
108. © 2008 Haim Michael 20151025
Introduction
Whenever we instantiate the class we get a new object on
which we can invoke each one of the functions that were
defined in the class with the self parameter.
When calling a function, that was defined in the class with
the self parameter, the self parameter is assigned with the
reference for the object on which the function is invoked.
It is possible to dynamically add new attributes to every
object.
109. © 2008 Haim Michael 20151025
Simple Class Definition
Assignment to attributes of self in methods create per-
instance attributes.
110. © 2008 Haim Michael 20151025
The Simplest Python Class Definition
We can define a new class without any attribute attached
using the following syntax.
class MyClass: pass
We use the pass statement as we don't have any method to
code.
Once the class is instantiated we can dynamically attach
attributes to the new created object.
111. © 2008 Haim Michael 20151025
The Simplest Python Class Definition
Assigning the attributes can be done outside of the class
definition.
112. © 2008 Haim Michael 20151025
The __init__ Function
The __init__ method is Python's replacement for the
constructor. When we create a new object this function will
be invoked.
It is possible to define this function with more parameters (in
addition to self mandatory parameter) and get the support
for instantiating the class passing over multiple arguments.
It is common to add the attributes to the new created object
within the scope of the __init__ function.
113. © 2008 Haim Michael 20151025
The __init__ Function
class Rectangle:
def __init__(self,w,h):
self.width = w
self.height = h
def area(self):
return self.width*self.height
a = Rectangle(3,4)
b = Rectangle(5,6)
print("area of a is %d and area of b is %d " % (a.area(),b.area()))
114. © 2008 Haim Michael 20151025
Inheritance
Python allows us to define a class that inherits from another
class.
Defining the sub class we can redefine the functions by
overriding the more general definitions.
115. © 2008 Haim Michael 20151025
Inheritance
Defining a class that extends another we should specify the
super class within the parentheses of the class header.
117. © 2008 Haim Michael 20151025
The super() Function
We can use the super() function for calling a function's
overridden version.
When we define a class that extends another class we can
include within the first class' definition for __init__ a call
for invoking __init__ in the base class.
Doing so, each __init__ function in each one of the
classes will be responsible for building the relevant parts of
the object.
118. © 2008 Haim Michael 20151025
The super() Function
class Person:
def __init__(self,id,name):
self.id = id
self.name = name
def details(self):
return "id=%d name=%s" % (self.id,self.name)
class Student(Person):
def __init__(self,id,name,average):
self.average = average
super().__init__(id,name)
def details(self):
return super().details() + " average=%d" % self.average
ob = Student(123123,"danidin",98)
print(ob.details())
120. © 2008 Haim Michael 20151026
Functional Programming
121. © 2008 Haim Michael 20151026
Introduction
Functional programming is a programming paradigm that
emphasizes the use of expressions and their evaluation and
especially through the definition of functions that are treated
as expressions. In addition, it avoids the complexity involved
with state changes.
122. © 2008 Haim Michael 20151026
Introduction
The use of functions as expressions enable us getting more
expressive code. In many cases we will exploit the power of
recursion in order to get expressive succinct (expressed in
few words) code.
Python is not a pure functional programming language.
Nevertheless, it has more than a few functional programming
capabilities.
123. © 2008 Haim Michael 20151026
Recursive Function
def total(numbers):
if len(numbers) == 0:
return 0
else:
return numbers[0] + total(numbers[1:])
print(total([2,5,7]))
125. © 2008 Haim Michael 20151026
Pure Functions
When we define a function that always returns the same
value for the very same arguments, and it doesn't depend
on any hidden information or state and its evaluation of the
result does not cause any observable side effects nor output
then it is a pure function.
Pure functions are usually simpler and much easier to test
and are very popular in Python programming.
126. © 2008 Haim Michael 20151026
Pure Functions
In order to write a pure function we should make sure that
we write local only code. We should make sure we don't use
neither the global statement nor the nonlocal one.
Writing a lambda expression as a pure function is the
common approach.
127. © 2008 Haim Michael 20151026
Lambda Expression
Using lambda expressions we can define a recursive function
that feels much more as an expression than a function we
define using the def keyword.
total = lambda numbers: 0 if len(numbers)==0 else numbers[0] + total(numbers[1:])
print(total([5,2,3,6]))
129. © 2008 Haim Michael 20151026
Higher Order Functions
When the function we define receives another function (or
functions) as an argument(s) or when its returned value is
another function it will called an higher order function.
We can use higher order functions for creating new
functions in our code.
130. © 2008 Haim Michael 20151026
Higher Order Functions
data = [(13225324,"daniel",54), (3452344,"ronen",92),
(98234234,"moshe",80), (65354435,"yael",70)]
beststudent = lambda dat: max(dat, key=lambda ob:ob[2])
print(beststudent(data))
131. © 2008 Haim Michael 20151026
Higher Order Functions
132. © 2008 Haim Michael 20151026
Immutable Data
One of the key characteristics of functional programming is
using immutable objects and constants instead of variables.
One of the possible advantages for this approach is the
performance advantage. Functional programming hardly
uses stateful objects.
133. © 2008 Haim Michael 20151026
Lazy Evaluation
One of the functional programming characteristics that
improves its performance is the deferred computation till it is
required, also known as lazy evaluation.
The yield statement is one example for the lazy evaluation
we can find in Python.
134. © 2008 Haim Michael 20151026
Lazy Evaluation
def numbers():
for num in range(10):
print("num=",num)
yield num
for number in numbers():
print(number)
136. © 2008 Haim Michael 20151026
Recursion instead of Loop
When writing pure functional code we will avoid using loops.
We will use recursive functions instead.
total = lambda num: 0 if num==0 else num + total(num-1)
print(total(4))
137. © 2008 Haim Michael 20151026
Recursion instead of Loop
138. © 2009 Haim Michael All Rights Reserved 138
Questions & Answers
Thanks for Your Time!
Haim Michael
haim.michael@lifemichael.com
+972+3+3726013 ext:700
lifemichael