SlideShare a Scribd company logo
1 of 138
Download to read offline
Python Jump Start
Haim Michael
June 19th
, 2019
All logos, trade marks and brand names used in this presentation belong
to the respective owners.
lifemichael
© 1996-2018 All Rights Reserved.
Haim Michael Introduction
● Snowboarding. Learning. Coding. Teaching. More
than 18 years of Practical Experience.
lifemichael
© 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
© 2008 Haim Michael 20150805
Introduction
© 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.
© 2008 Haim Michael 20150805
Monty Python
© 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.
© 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.
© 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.
© 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.
© 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.
© 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.
© 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.
© 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.
© 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.
© 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.
© 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.
© 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.
© 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.
© 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
© 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
© 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.
© 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
© 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)
© 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
© 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)
© 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.
© 2008 Haim Michael 20150805
The Python Package Index
© 2008 Haim Michael 20150805
The Python Package Index
© 2008 Haim Michael 20150805
Types
© 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.
© 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.
© 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'}
© 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))
© 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.
© 2008 Haim Michael 20150805
Types Categories
 The available types are grouped into categories. Each category
and its characteristics.
© 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.
© 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.
© 2008 Haim Michael 20150805
The Sequences Category
a = [3,5,21,23,5,"fafa"]
a.append(499)
print(a)
© 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.
© 2008 Haim Michael 20150805
The Set Category
a = {3,5,21,23,5,"fafa",5,3,23,23,"fafa"}
print(a)
© 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.
© 2008 Haim Michael 20150805
The Mappings Category
a = { 123123:"haim michael", 42534:"moshe solomon",
454234:"david magen"}
print(a.get(542534))
© 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.
© 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
© 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.
© 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)
© 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
© 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.
© 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.
© 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
© 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.
© 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.
© 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
© 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.
© 2008 Haim Michael 20150805
Shared References
© 2008 Haim Michael 20150804
Operatros
© 2008 Haim Michael 20150804
Introduction
 The Python programming language supports a huge range of
various operators.
© 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)
© 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
© 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...)
© 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
© 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
© 2008 Haim Michael 20170720
Statements
© 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.
© 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.
© 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.
© 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.
© 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.
© 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.
© 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.
© 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:
...
© 2008 Haim Michael 20170720
Try Statements
© 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.
© 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.
© 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
© 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.
© 2008 Haim Michael 20170720
The 'if' Statements
if <test_1>:
statement_1
elif <test_2>:
statement_2
elif <test_3>:
statement_3
else:
statement
© 2008 Haim Michael 20170720
The 'if' Statements
© 2008 Haim Michael 20170720
The 'if' Statements
© 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.
© 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.
© 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.
© 2008 Haim Michael 20170720
Truth Tests
© 2008 Haim Michael 20170720
Truth Tests
 Comparisons two objects using the the == operator works
recursively when applying them to data structures.
© 2008 Haim Michael 20170720
Truth Tests
© 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
© 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>
© 2008 Haim Michael 20170720
The while Loop
© 2008 Haim Michael 20170720
The while Loop
© 2008 Haim Michael 20170720
The while Loop
© 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>
© 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.
© 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.
© 2008 Haim Michael 20170720
The for Loop
 Working with dictionaries we can iterate the keys and use
them to get the values.
© 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.
© 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.
© 2008 Haim Michael 20170720
The for Loop
 We can nest one loop within another. There is no limit for
the number of levels.
© 2008 Haim Michael 20170720
The for Loop
 We can execute the for loop on every sequence type,
including lists, tuples and strings.
© 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.
© 2008 Haim Michael 20151020
Functions
© 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.
© 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
© 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.
© 2008 Haim Michael 20151020
The def Statement
def sum(a,b):
total = a + b
return total
print(sum(4,3))
© 2008 Haim Michael 20151025
Classes
© 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.
© 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.
© 2008 Haim Michael 20151025
Simple Class Definition
 Assignment to attributes of self in methods create per-
instance attributes.
© 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.
© 2008 Haim Michael 20151025
The Simplest Python Class Definition
 Assigning the attributes can be done outside of the class
definition.
© 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.
© 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()))
© 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.
© 2008 Haim Michael 20151025
Inheritance
 Defining a class that extends another we should specify the
super class within the parentheses of the class header.
© 2008 Haim Michael 20151025
Inheritance
© 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.
© 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())
© 2008 Haim Michael 20151025
The super() Function
© 2008 Haim Michael 20151026
Functional Programming
© 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.
© 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.
© 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]))
© 2008 Haim Michael 20151026
Recursive Function
© 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.
© 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.
© 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]))
© 2008 Haim Michael 20151026
Lambda Expression
© 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.
© 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))
© 2008 Haim Michael 20151026
Higher Order Functions
© 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.
© 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.
© 2008 Haim Michael 20151026
Lazy Evaluation
def numbers():
for num in range(10):
print("num=",num)
yield num
for number in numbers():
print(number)
© 2008 Haim Michael 20151026
Lazy Evaluation
© 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))
© 2008 Haim Michael 20151026
Recursion instead of Loop
© 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

More Related Content

What's hot

Overview of c++
Overview of c++Overview of c++
Overview of c++geeeeeet
 
C++ OOP Implementation
C++ OOP ImplementationC++ OOP Implementation
C++ OOP ImplementationFridz Felisco
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Featurestechfreak
 
Python Programming - III. Controlling the Flow
Python Programming - III. Controlling the FlowPython Programming - III. Controlling the Flow
Python Programming - III. Controlling the FlowRanel Padon
 
Lecture21 categoriesof userdefinedfunctions.ppt
Lecture21 categoriesof userdefinedfunctions.pptLecture21 categoriesof userdefinedfunctions.ppt
Lecture21 categoriesof userdefinedfunctions.ppteShikshak
 
KMS TechCon 2014 - Interesting in JavaScript
KMS TechCon 2014 - Interesting in JavaScriptKMS TechCon 2014 - Interesting in JavaScript
KMS TechCon 2014 - Interesting in JavaScriptDuy Lâm
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#Riccardo Terrell
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of VariableMOHIT DADU
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1YOGESH SINGH
 
The Erlang Programming Language
The Erlang Programming LanguageThe Erlang Programming Language
The Erlang Programming LanguageDennis Byrne
 
Lesson slides for C programming course
Lesson slides for C programming courseLesson slides for C programming course
Lesson slides for C programming courseJean-Louis Gosselin
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoringkim.mens
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An OverviewIndrajit Das
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogrammingLuis Atencio
 
JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014Noopur Gupta
 

What's hot (20)

Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++
 
C++ ch1
C++ ch1C++ ch1
C++ ch1
 
Overview of c++
Overview of c++Overview of c++
Overview of c++
 
C++ OOP Implementation
C++ OOP ImplementationC++ OOP Implementation
C++ OOP Implementation
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
 
Python Programming - III. Controlling the Flow
Python Programming - III. Controlling the FlowPython Programming - III. Controlling the Flow
Python Programming - III. Controlling the Flow
 
Lecture21 categoriesof userdefinedfunctions.ppt
Lecture21 categoriesof userdefinedfunctions.pptLecture21 categoriesof userdefinedfunctions.ppt
Lecture21 categoriesof userdefinedfunctions.ppt
 
KMS TechCon 2014 - Interesting in JavaScript
KMS TechCon 2014 - Interesting in JavaScriptKMS TechCon 2014 - Interesting in JavaScript
KMS TechCon 2014 - Interesting in JavaScript
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
 
A tutorial on C++ Programming
A tutorial on C++ ProgrammingA tutorial on C++ Programming
A tutorial on C++ Programming
 
Hanoi JUG: Java 8 & lambdas
Hanoi JUG: Java 8 & lambdasHanoi JUG: Java 8 & lambdas
Hanoi JUG: Java 8 & lambdas
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
The Erlang Programming Language
The Erlang Programming LanguageThe Erlang Programming Language
The Erlang Programming Language
 
Lesson slides for C programming course
Lesson slides for C programming courseLesson slides for C programming course
Lesson slides for C programming course
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Programming paradigms
Programming paradigmsProgramming paradigms
Programming paradigms
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
 
JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014
 

Similar to Python Jump Start

Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on SteroidHaim Michael
 
Python Crash Course
Python Crash CoursePython Crash Course
Python Crash CourseHaim Michael
 
python programming.pptx
python programming.pptxpython programming.pptx
python programming.pptxKaviya452563
 
Mastering the Interview: 50 Common Interview Questions Demystified
Mastering the Interview: 50 Common Interview Questions DemystifiedMastering the Interview: 50 Common Interview Questions Demystified
Mastering the Interview: 50 Common Interview Questions DemystifiedMalcolmDupri
 
Python and its applications
Python and its applicationsPython and its applications
Python and its applicationsmohakmishra97
 
Basic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptxBasic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptxAditya Patel
 
IRJET- Python: Simple though an Important Programming Language
IRJET- Python: Simple though an Important Programming LanguageIRJET- Python: Simple though an Important Programming Language
IRJET- Python: Simple though an Important Programming LanguageIRJET Journal
 
Introduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfIntroduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfVaibhavKumarSinghkal
 
Migration of Applications to Python is the most prudent Decision
Migration of Applications to Python is the most prudent DecisionMigration of Applications to Python is the most prudent Decision
Migration of Applications to Python is the most prudent DecisionMindfire LLC
 
introduction of python in data science
introduction of python in data scienceintroduction of python in data science
introduction of python in data sciencebhavesh lande
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unitmichaelaaron25322
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1Kirti Verma
 
Python and Its fascinating applications in the real world.pdf
Python and Its fascinating applications in the real world.pdfPython and Its fascinating applications in the real world.pdf
Python and Its fascinating applications in the real world.pdfSkilloVilla
 
Introduction to Python.pdf
Introduction to Python.pdfIntroduction to Python.pdf
Introduction to Python.pdfRahul Mogal
 

Similar to Python Jump Start (20)

Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on Steroid
 
Python Crash Course
Python Crash CoursePython Crash Course
Python Crash Course
 
python programming.pptx
python programming.pptxpython programming.pptx
python programming.pptx
 
Mastering the Interview: 50 Common Interview Questions Demystified
Mastering the Interview: 50 Common Interview Questions DemystifiedMastering the Interview: 50 Common Interview Questions Demystified
Mastering the Interview: 50 Common Interview Questions Demystified
 
Python and its applications
Python and its applicationsPython and its applications
Python and its applications
 
Python
Python Python
Python
 
Basic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptxBasic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptx
 
IRJET- Python: Simple though an Important Programming Language
IRJET- Python: Simple though an Important Programming LanguageIRJET- Python: Simple though an Important Programming Language
IRJET- Python: Simple though an Important Programming Language
 
Introduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfIntroduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdf
 
Migration of Applications to Python is the most prudent Decision
Migration of Applications to Python is the most prudent DecisionMigration of Applications to Python is the most prudent Decision
Migration of Applications to Python is the most prudent Decision
 
introduction of python in data science
introduction of python in data scienceintroduction of python in data science
introduction of python in data science
 
Research paper on python by Rj
Research paper on python by RjResearch paper on python by Rj
Research paper on python by Rj
 
Python Online From EasyLearning Guru
Python Online From EasyLearning GuruPython Online From EasyLearning Guru
Python Online From EasyLearning Guru
 
Python Programming Draft PPT.pptx
Python Programming Draft PPT.pptxPython Programming Draft PPT.pptx
Python Programming Draft PPT.pptx
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unit
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
 
Python and Its fascinating applications in the real world.pdf
Python and Its fascinating applications in the real world.pdfPython and Its fascinating applications in the real world.pdf
Python and Its fascinating applications in the real world.pdf
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Introduction to Python.pdf
Introduction to Python.pdfIntroduction to Python.pdf
Introduction to Python.pdf
 

More from Haim Michael

Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in JavaHaim Michael
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design PatternsHaim Michael
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL InjectionsHaim Michael
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in JavaHaim Michael
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design PatternsHaim Michael
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in PythonHaim Michael
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in PythonHaim Michael
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScriptHaim Michael
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214Haim Michael
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump StartHaim Michael
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHPHaim Michael
 
What is new in Python 3.9
What is new in Python 3.9What is new in Python 3.9
What is new in Python 3.9Haim Michael
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib LibraryHaim Michael
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908Haim Michael
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818Haim Michael
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728Haim Michael
 
Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Haim Michael
 
The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]Haim Michael
 

More from Haim Michael (20)

Anti Patterns
Anti PatternsAnti Patterns
Anti Patterns
 
Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in Java
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design Patterns
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL Injections
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in Java
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in Python
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScript
 
Java Jump Start
Java Jump StartJava Jump Start
Java Jump Start
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump Start
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHP
 
What is new in Python 3.9
What is new in Python 3.9What is new in Python 3.9
What is new in Python 3.9
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib Library
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728
 
Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start)
 
The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]
 

Recently uploaded

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 

Python Jump Start

  • 1. Python Jump Start Haim Michael June 19th , 2019 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
  • 4. © 2008 Haim Michael 20150805 Introduction
  • 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.
  • 6. © 2008 Haim Michael 20150805 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
  • 30. © 2008 Haim Michael 20150805 Types
  • 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.
  • 56. © 2008 Haim Michael 20150805 Shared References
  • 57. © 2008 Haim Michael 20150804 Operatros
  • 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
  • 64. © 2008 Haim Michael 20170720 Statements
  • 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: ...
  • 73. © 2008 Haim Michael 20170720 Try Statements
  • 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
  • 79. © 2008 Haim Michael 20170720 The 'if' Statements
  • 80. © 2008 Haim Michael 20170720 The 'if' Statements
  • 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.
  • 84. © 2008 Haim Michael 20170720 Truth Tests
  • 85. © 2008 Haim Michael 20170720 Truth Tests  Comparisons two objects using the the == operator works recursively when applying them to data structures.
  • 86. © 2008 Haim Michael 20170720 Truth Tests
  • 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>
  • 89. © 2008 Haim Michael 20170720 The while Loop
  • 90. © 2008 Haim Michael 20170720 The while Loop
  • 91. © 2008 Haim Michael 20170720 The while Loop
  • 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.
  • 101. © 2008 Haim Michael 20151020 Functions
  • 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))
  • 106. © 2008 Haim Michael 20151025 Classes
  • 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.
  • 116. © 2008 Haim Michael 20151025 Inheritance
  • 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())
  • 119. © 2008 Haim Michael 20151025 The super() Function
  • 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]))
  • 124. © 2008 Haim Michael 20151026 Recursive Function
  • 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]))
  • 128. © 2008 Haim Michael 20151026 Lambda Expression
  • 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)
  • 135. © 2008 Haim Michael 20151026 Lazy Evaluation
  • 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