SlideShare une entreprise Scribd logo
1  sur  216
Télécharger pour lire hors ligne
Python Crash Course
Haim Michael
June 11th
, 2018
All logos, trade marks and brand names used in this presentation belong
to the respective owners.
lifemichael
https://youtu.be/Vahb-lJ_0J4
Part 1
https://youtu.be/QejEywRHlDs
Part 2
© 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
Python Domains
 Python is commonly used in the following domains: System
Programming, GUIs and Internet Scripting.
© 2008 Haim Michael 20150805
Database Programming
 There are available interfaces that allow us to connect our
Python code with nearly all commonly used relational
databases, such as Oracle, Informix, MySQL SQLite and
others.
 The Python community has also defined a portable database
API that allows accessing SQL databases from within scripts
written in Python.
© 2008 Haim Michael 20150805
Database Programming
 The Python standard pickle module provides an easy to use
objects persistence system, that allows programs to easily
save and restore entire graphs of objects to the files system.
 Python includes the SQLite embedded SQL database engine
as a standard.
 Third party open source systems, such as SQLObject and
SQLAlchemy, map relational tables onto Python's class
model.
© 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
SL4A
 SL4A is an open source project that allows us to execute
code in various scripting programming languages, including
Python, Perl, Jruby, Lua and JavaScript, on the android
platform.
https://github.com/damonkohler/sl4a
© 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
# script_a
print("before...")
import script_b
print("after...")
# script_b
print("good luck!")
© 2008 Haim Michael 20150805
Modules Import
© 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
The Interactive Console
 PyCharm interactive console allows us to write code in
Python and get its immediate evaluation. It is a great tool for
learning Python!
© 2008 Haim Michael 20150805
The Interactive Console
© 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
Complex Numbers
 Python supports complex numbers. A complex number is a
distinct core object type in Python.
 Complex numbers in Python are represented as two floating
point numbers. The real and the imaginary part.
 We code a complex number by adding 'j' or 'J' suffix to the
imaginary part (e.g. 2 + -4j).
© 2008 Haim Michael 20150805
Complex Numbers
 In order to create a complex number we need to specify a
real number and an imaginary one.
temp = 3+2j
print(type(temp))
© 2008 Haim Michael 20150805
Hexadecimal, Octal and Binary
 Coding octal literals is done by adding '0o'.
0o1, 0o724,0o123
 Coding hexadecimal literals is done by adding '0x'.
0x1A3, 0x32BF, 0x24BA98
 Coding binary literals is done by adding '0b'.
0b1001, 0b1100, 0b1001
© 2008 Haim Michael 20150805
Hexadecimal, Octal and Binary
 Using the oct(), hex() and bin() functions we can
convert integers from decimal to other bases' digit strings.
© 2008 Haim Michael 20150805
Binary Operations
 Python supports most of the numeric expressions available
in C, including operators that refer the binary representation.
<<
>>
&
|
^
© 2008 Haim Michael 20150805
Built-in Numeric Tools
 In addition to the core object types, Python provides built-in
functions and standard library modules that assist with
numeric processing. One of them is the math module.
...
import math
math.sin(123) #gives sin of 123
math.pow(4,2) #gives 16
...
© 2008 Haim Michael 20150805
Decimal Type
 Decimals are like floating point values that have a fixed
number of digits to the right of the decimal point. Decimals
are fixed precision floating point values.
 We can create decimal objects by calling the Decimal
constructor in the decimal module passing in strings that
have the desired number of decimal digits.
from decimal import Decimal;
Decimal('0.3') + Decimal('2.2') #we should get 2.5
Decimal('-0.4') + Decimal('1.4') #we should get 1
© 2008 Haim Michael 20150805
Decimal Type
 Calling 'from decimal import Decimal' imports the
decimal module, and creates references in the current
namespace to the given Decimal object. We can now use
Decimal in our program.
 We can alternatively call 'import decimal' only and then
change our code to the following.
import decimal;
decimal.Decimal('0.3') + decimal.Decimal('2.2')
decimal.Decimal('-0.4') + decimal.Decimal('1.4')
© 2008 Haim Michael 20150805
Decimal Type
 We can set the precision of all decimal numbers, set up
errors handling etc.
...
decimal.getcontext().prec=4 #set a precision of 4 digits
...
© 2008 Haim Michael 20150805
Decimal Type
 Setting the precision effects the result we get from
calculation that use the various available operators. It
doesn't just influence the result we get on screen.
© 2008 Haim Michael 20150805
Fraction Type
 As with Decimal, Fraction resides in a separated module.
The fractions module. When creating a Fraction object we
should pass over a numerator and a denominator.
...
from fractions import Fraction
numA = Fraction(3,8)
numB = Fraction(2,4)
numA + numB
...
© 2008 Haim Michael 20150805
Fraction Type
© 2008 Haim Michael 20150805
Fraction Type
import fractions
a = fractions.Fraction(3,4)
b = fractions.Fraction(3,4)
c = a + b
print(c)
© 2008 Haim Michael 20150805
Booleans
 Python has the explicit Boolean data type called bool. Its
possible values are 'True' and 'False'. These two objects
are instances of bool, a subclass of the built-in integer type
int.
© 2008 Haim Michael 20150805
Numeric Extensions
 There is a large library of third party open source extensions
we can use to perform advance operations related to the
numeric values we work on.
www.scipy.orgwww.numpy.org
© 2008 Haim Michael 20150805
Dynamic Typing
 When developing code in Python we don't need to predefine
the type of a variable we want to use.
 In Python, the types are determined automatically at runtime
in accordance with the assigned value.
© 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
 Each time we assign a value to the same variable, the type
of the referenced object might change into a different type.
© 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 20150805
The sys.getrefcount() Function
 Calling this function we can get an object's reference count.
© 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
Assignments
 The following illustrates the various assignments forms
Python supports.
ob = 'abc' - basic form assignment
ob_a, ob_b = 'aaa', 'bbb' - tuple assignment
[ob_a, ob_b] = ['aaa','bbb'] - list assignment
ob_a, ob_b, ob_c = 'abc' - sequence assignment
ob_a, *ob_b = 'abc' - extended sequence unpacking
ob_a = ob_b = 'abc' - multiple target assignment
ob_a += 123 - augment assignment
© 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
Tuple & List Unpacking Assignment
 The code includes a tuple or a list on the left side of the '='
sign, the objects on the right side are paired with the targets
on the left by positioning and assigning them left to right.
© 2008 Haim Michael 20170720
Sequence Assignment
 Any sequence of names can be assigned with any
sequence of values. The values of the specified sequence
are assigned one at a time in accordance with their position.
© 2008 Haim Michael 20170720
Extended Sequence Assignment
 Any sequence of names can be assigned with any
sequence of values. The values of the specified sequence
are assigned one at a time in accordance with their position.
When a specific name is specified with * then the rest of the
values will be assigned to it.
© 2008 Haim Michael 20170720
Multiple Target Assignments
 Specifying multiple names on the left, the same reference
will be assigned to each one of them.
© 2008 Haim Michael 20170720
Augmented Assignments
 The var operator = expression is evaluated as if we
write var = var operator expression.
 The augmented assignment is supported by each one of the
available binary operators. The variable var must be
assigned with a value before we can use it.
© 2008 Haim Michael 20170720
Useful Patterns
 The extended sequence unpacking assignment is highly
useful and can be reflected in the following patters.
© 2008 Haim Michael 20170720
Variables Names Rules
 Each variable name must start either with an underscore or
a letter, which can be followed by any number of letters,
digits or underscores.
 The names are case sensitive and the reserved words
cannot be used as names for variables we define.
© 2008 Haim Michael 20170720
Variables Names Conventions
 The variables and functions that start with an underscore
are not imported when using the 'from module import
*' statement.
 Names with two leading and trailing underscores (__x__)
are system defined names with a special meaning to
development tools we use.
 Class names start with an upper case. Module names start
with a lower case.
© 2008 Haim Michael 20170720
Names Don't Have Types
 The variables' names are not associated with permanent
types. Only the objects have types that cannot be changed.
For that reason, it is possible to assign the same variable
with different types of objects.
ob = 12
ob = 43.2
ob = 'abc'
ob = [1,2,3,4]
© 2008 Haim Michael 20170720
Expression Statements
 An expression can be used as a statement... just that its
result won't be saved. Calling a function is an example for
an expression that is used as a statement.
© 2008 Haim Michael 20170720
The print Built-in Function
 The print built-int function doesn't return any value we care
about (it actually returns None). Calling this function is an
example for expression we use as a statement.
print ([object, ...][, sep=' '][, end='n'][, file=sys.stdout])
© 2008 Haim Michael 20170720
The print Built-in Function
 We can assign a new object to sys.stdout. Doing so we
can assign an object that represents a file so that every call
to print will result in printing out to that file.
© 2008 Haim Michael 20170720
The print Built-in Function
 Instead of changing the value of sys.stdout it is also
possible to change the value of the file parameter we can
use when calling the print function.
© 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
Multiway Branching
 Python allows us to code multiway branching either by using
a series of if/elif tests or by indexing dictionaries or
searching lists. Using a separated variable together with a
dictionary or an indexed list we can get kind of a functional
switch statement.
© 2008 Haim Michael 20170720
Multiway Branching
 We can get a multiway branching also by calling 'get' on a
dictionary object passing over the key as well as the default
value to be returned if the key (we pass over) doesn't exist.
© 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 while Loop
 Calling break will jump out of the closest enclosing loop.
 Calling continue will jump to the top of the closest
enclosing loop.
 Calling pass does nothing. We will call pass when there
is nothing we want to do. Since we cannot leave the body
empty calling pass is the only solution.
© 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 20170720
List Comprehensions
 Working with a list, instead of iterating its elements using a
loop we can create a comprehension list.
 We create a comprehension list by placing the logic code on
which the new list is based within square brackets.
© 2008 Haim Michael 20170720
List Comprehensions
 We can use the list comprehension syntax when working
with files as well.
© 2008 Haim Michael 20170720
Extended List Comprehensions
 We can extend the definition for our comprehended list
adding a filter condition.
list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = [num*num for num in list1 if num
%2==0]
list3 = [num if num%2==0 else "###" for
num in list1]
print(list1)
print(list2)
print(list3)
© 2008 Haim Michael 20170720
Extended List Comprehensions
 We can even extend the definition for our comprehended list
adding more for clauses representing other nested loops.
0
© 2008 Haim Michael 20170720
The 'range' Function
 This function returns a range of numbers. Passing over that
range to the list() function we get a list. Calling the iter()
function passing over that range we shall get an iterator.
Using the next() function we can iterate all elements.
© 2008 Haim Michael 20170720
The 'range' Function
 This range object we get is iterable so we can iterate it using
the for loop.
© 2008 Haim Michael 20170720
The 'map' Function
 The 'map' function, as well as the 'zip' and the 'filter'
functions returns iterable objects we can iterate either
directly or indirectly.
 Calling the map() function we get a reference for an iterable
object through which we can iterate the returned elements.
Either directly using the iterator we can get or indirectly
using a simple for loop.
© 2008 Haim Michael 20170720
The 'map' Function
© 2008 Haim Michael 20170720
The 'map' Function
© 2008 Haim Michael 20170720
The 'zip' Function
 Calling the zip() function we pass over two lists. The
zip() function puts together the values from the two lists
as if they are pairs.
 The zip() function returns an iterable object that holds
tuples.
© 2008 Haim Michael 20170720
The 'zip' Function
© 2008 Haim Michael 20170720
The 'zip' Function
© 2008 Haim Michael 20170720
The 'filter' Function
 Calling the filter() function we pass over a function and
an iterable object. The filter() function returns an
iterable object that holds all elements the passed function
returned true.
© 2008 Haim Michael 20170720
The 'filter' Function
© 2008 Haim Michael 20170720
The 'filter' Function
© 2008 Haim Michael 20170720
The 'dir' Function
 Calling the built-in 'dir' function passing over an object we
shall get a list of all attributes available at that object.
© 2008 Haim Michael 20170720
The del Keyword
 We can use the del keyword for deleting a reference to an
object. Every value in Python is an object.
© 2008 Haim Michael 20170720
The None Constant
 We can use the None constant in order to represent the
absent of a value or in order to represent null.
 The type of None is NoneType. It isn't possible to create
new objects of the NoneType class. We can assign None to
multiple variable. All of them will hold the same reference.
 When converting None into boolean we will get False.
© 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 20151020
The def Statement
 We can place different definitions for the same function and
using a simple if statement choosing which of those
versions will be defined.
...
if test:
def func():
...
else:
def func():
...
...
© 2008 Haim Michael 20151020
The def Statement
 Each function is just an object. The name assigned to each
function is just a name. We use that name in order to call
the function.
© 2008 Haim Michael 20151020
Function Attributes
 Because a function is an object we can add new attributes
we choose.
def sum(a,b):
c = a + b
return c
sum.version = 101
sum.author = "haim michael"
sum.priority = 3
print(sum.author)
© 2008 Haim Michael 20151020
Returned Functions
 We can define a function that its returned value is another
function.
 When one function returns a function it includes its
definition.
 The returned function is capable of referring variables that
belong to the scope of the outer one.
© 2008 Haim Michael 20151020
Returned Functions
def doSomethingA():
number = 7
def doSomethingB():
print(number)
return doSomethingB
ob = doSomethingA()
ob()
© 2008 Haim Michael 20151020
Returned Functions
© 2008 Haim Michael 20151020
Arguments
 When calling a function passing over names, we actually
pass the references held by these names.
 Assigning new references to the parameter names within
the function scope doesn't effect the names the caller
passed.
 Changing a mutable object from within the function the
caller code should feel that as well.
© 2008 Haim Michael 20151020
Sequence Returned Value
 We can define a function that returns a tuple, or any other
sequence type.
#dmo
def f(a,b):
numA = 2 * a
numB = 2 * b
return [numA,numB]
x = f(3,5)
print(x)
© 2008 Haim Michael 20151020
The func(name) Syntax
 By default, the arguments we pass must match by position,
left to right, and we must pass exactly as many arguments
as required.
def f(a,b):
sum = a+b
print(sum)
f(2,3)
© 2008 Haim Michael 20151020
The func(name=value) Syntax
 Calling a function we can specify which parameters should
receive a value by using the argument's name in the
name=value syntax.
#dmo
def f(a,b):
numA = 2 * a
numB = 2 * b
return [numA,numB]
x = f(a=3,b=5)
print(x)
© 2008 Haim Michael 20151020
The func(*name) Syntax
 Adding * to the sequence we pass over to the function, the
function will be capable of unpacking the passed argument
into discrete separated parameters.
def f(x1,y1,x2,y2):
return (y2-y1)*(y2-y1)+(x2-x1)*(x2-x1)
ob = [0,0,4,3]
num = f(*ob)
print(num)
© 2008 Haim Michael 20151020
The func(**name) Function
 Adding ** to the argument name, when calling the function a
collection of key/value pairs in the form of a dictionary will
be expected to be passed over to the function as individual
keyword arguments.
def f(a,b):
print(a)
print(b)
ob = {'a':1,'b':2}
f(**ob)
© 2008 Haim Michael 20151020
The func(**name) Function
 When defining a function we must specify the parameters
in the following order. The first should be the normal
parameters. After these parameters we should specify the
default parameters followed by the *name parameters and
followed by the **name ones.
© 2008 Haim Michael 20151020
The def func(name) Syntax
 Defining a simple function, the passed values should match
by position or name.
def f(a,b):
sum = a+b
print(sum)
f(2,3)
© 2008 Haim Michael 20151020
The def func(name=value) Syntax
 Defining a function we can use the argument's name in the
name=value syntax in order to specify default values for
specific arguments.
def f(a=4,b=6):
numA = 2 * a
numB = 2 * b
return [numA,numB]
x = f()
print(x)
© 2008 Haim Michael 20151020
The def func(name=value) Syntax
 This code sample includes a function with two parameters.
The first is a normal positioned one. The second has a
default value.
def f(a,b=6):
numA = 2 * a
numB = 2 * b
return [numA,numB]
x = f(5)
print(x)
© 2008 Haim Michael 20151020
The def func(*name) Syntax
 Adding * to the parameter name in the function definition
collects unmatched positional arguments into a tuple.
#dmo
def sum(*tpl):
sum = 0
for num in tpl:
sum = sum + num
return sum
print(sum(3,4,6,2,3,6))
© 2008 Haim Michael 20151020
The def func(**name) Syntax
 Adding ** to the parameter name in the function definition
collects unmatched positional arguments into a dictionary.
def f(**args):
print(args)
f(a=10,b=20)
© 2008 Haim Michael 20151020
Indirect Function Call
 When assigning a function to one of our variables we can
append () to that variable and use it in order to call that
function.
def factorial(a):
if a==0:
return 1
else:
return a * factorial(a-1)
f = factorial
print(f(5))
© 2008 Haim Michael 20151020
Functions Are Objects
 Because the functions are objects we can process a
function as any other object.
>>> dir(factorial)
['__annotations__', '__call__', '__class__', '__closure__',
'__code__', '__defaults__', '__delattr__', '__dict__',
'__doc__', '__eq__', '__format__', '__ge__', '__get__',
'__getattribute__', '__globals__', '__gt__', '__hash__',
'__init__', '__kwdefaults__', '__le__', '__lt__',
'__module__', '__name__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__']
>>>
© 2008 Haim Michael 20151020
Anonymous Functions (Lambda)
 Using the lambda keyword we can define an anonymous
function.
lambda param1, param2, param3...paramN : expression
 Unlike using def, when using lambda we get an
expression. Not a statement.
© 2008 Haim Michael 20151020
Anonymous Functions (Lambda)
ob = lambda a,b,c:a+b+c
print(ob(1,2,3))
© 2008 Haim Michael 20151020
Anonymous Functions (Lambda)
 Unlike using def, when using lambda we can have one
single expression. We cannot have a block of statements.
© 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 216
Questions & Answers
Thanks for Your Time!
Haim Michael
haim.michael@lifemichael.com
+972+3+3726013 ext:700
lifemichael

Contenu connexe

Tendances

Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1Kirti Verma
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialQA TrainingHub
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming LanguageR.h. Himel
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Chariza Pladin
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming pptismailmrribi
 
Introduction To Python | Edureka
Introduction To Python | EdurekaIntroduction To Python | Edureka
Introduction To Python | EdurekaEdureka!
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaEdureka!
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Python ppt.pdf
Python ppt.pdfPython ppt.pdf
Python ppt.pdfkalai75
 
An Introduction to Python Programming
An Introduction to Python ProgrammingAn Introduction to Python Programming
An Introduction to Python ProgrammingMorteza Zakeri
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAMaulik Borsaniya
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaEdureka!
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-pythonAakashdata
 

Tendances (20)

Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python Tutorial
 
Python
PythonPython
Python
 
Python Presentation
Python PresentationPython Presentation
Python Presentation
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming ppt
 
Python ppt
Python pptPython ppt
Python ppt
 
Introduction To Python | Edureka
Introduction To Python | EdurekaIntroduction To Python | Edureka
Introduction To Python | Edureka
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
 
Python final ppt
Python final pptPython final ppt
Python final ppt
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Python ppt.pdf
Python ppt.pdfPython ppt.pdf
Python ppt.pdf
 
An Introduction to Python Programming
An Introduction to Python ProgrammingAn Introduction to Python Programming
An Introduction to Python Programming
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-python
 

Similaire à Python Crash Course

Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on SteroidHaim 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
 
Basic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptxBasic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptxAditya Patel
 
Python and its applications
Python and its applicationsPython and its applications
Python and its applicationsmohakmishra97
 
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 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
 
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
 
A complete guide to Python app development.pdf
A complete guide to Python app development.pdfA complete guide to Python app development.pdf
A complete guide to Python app development.pdfMoonTechnolabsPvtLtd
 
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 Programming - I
Introduction to Python Programming  - IIntroduction to Python Programming  - I
Introduction to Python Programming - IArnab Chakraborty
 
Python programming for beginners
Python programming for beginnersPython programming for beginners
Python programming for beginnersBenishchoco
 
Python App Development_ 7 Things to Keep in Mind.pdf
Python App Development_ 7 Things to Keep in Mind.pdfPython App Development_ 7 Things to Keep in Mind.pdf
Python App Development_ 7 Things to Keep in Mind.pdfBoTree Technologies
 

Similaire à Python Crash Course (20)

Python Jump Start
Python Jump StartPython Jump Start
Python Jump Start
 
Python Jump Start
Python Jump StartPython Jump Start
Python Jump Start
 
Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on Steroid
 
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
 
Basic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptxBasic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptx
 
Python
Python Python
Python
 
Python and its applications
Python and its applicationsPython and its applications
Python and its applications
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
 
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 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
 
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
 
A complete guide to Python app development.pdf
A complete guide to Python app development.pdfA complete guide to Python app development.pdf
A complete guide to Python app development.pdf
 
Summer Training Project.pdf
Summer Training Project.pdfSummer Training Project.pdf
Summer Training Project.pdf
 
Research paper on python by Rj
Research paper on python by RjResearch paper on python by Rj
Research paper on python by Rj
 
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 Programming - I
Introduction to Python Programming  - IIntroduction to Python Programming  - I
Introduction to Python Programming - I
 
Python Programming Draft PPT.pptx
Python Programming Draft PPT.pptxPython Programming Draft PPT.pptx
Python Programming Draft PPT.pptx
 
Python programming for beginners
Python programming for beginnersPython programming for beginners
Python programming for beginners
 
Python App Development_ 7 Things to Keep in Mind.pdf
Python App Development_ 7 Things to Keep in Mind.pdfPython App Development_ 7 Things to Keep in Mind.pdf
Python App Development_ 7 Things to Keep in Mind.pdf
 

Plus de 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
 

Plus de 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]
 

Dernier

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Dernier (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Python Crash Course

  • 1. Python Crash Course Haim Michael June 11th , 2018 All logos, trade marks and brand names used in this presentation belong to the respective owners. lifemichael https://youtu.be/Vahb-lJ_0J4 Part 1 https://youtu.be/QejEywRHlDs Part 2
  • 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 Python Domains  Python is commonly used in the following domains: System Programming, GUIs and Internet Scripting.
  • 18. © 2008 Haim Michael 20150805 Database Programming  There are available interfaces that allow us to connect our Python code with nearly all commonly used relational databases, such as Oracle, Informix, MySQL SQLite and others.  The Python community has also defined a portable database API that allows accessing SQL databases from within scripts written in Python.
  • 19. © 2008 Haim Michael 20150805 Database Programming  The Python standard pickle module provides an easy to use objects persistence system, that allows programs to easily save and restore entire graphs of objects to the files system.  Python includes the SQLite embedded SQL database engine as a standard.  Third party open source systems, such as SQLObject and SQLAlchemy, map relational tables onto Python's class model.
  • 20. © 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.
  • 21. © 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.
  • 22. © 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.
  • 23. © 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
  • 24. © 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
  • 25. © 2008 Haim Michael 20150805 SL4A  SL4A is an open source project that allows us to execute code in various scripting programming languages, including Python, Perl, Jruby, Lua and JavaScript, on the android platform. https://github.com/damonkohler/sl4a
  • 26. © 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.
  • 27. © 2008 Haim Michael 20150805 Modules Import # script_a print("before...") import script_b print("after...") # script_b print("good luck!")
  • 28. © 2008 Haim Michael 20150805 Modules Import
  • 29. © 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
  • 30. © 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)
  • 31. © 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
  • 32. © 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)
  • 33. © 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.
  • 34. © 2008 Haim Michael 20150805 The Python Package Index
  • 35. © 2008 Haim Michael 20150805 The Python Package Index
  • 36. © 2008 Haim Michael 20150805 The Interactive Console  PyCharm interactive console allows us to write code in Python and get its immediate evaluation. It is a great tool for learning Python!
  • 37. © 2008 Haim Michael 20150805 The Interactive Console
  • 38. © 2008 Haim Michael 20150805 Types
  • 39. © 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.
  • 40. © 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.
  • 41. © 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'}
  • 42. © 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))
  • 43. © 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.
  • 44. © 2008 Haim Michael 20150805 Types Categories  The available types are grouped into categories. Each category and its characteristics.
  • 45. © 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.
  • 46. © 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.
  • 47. © 2008 Haim Michael 20150805 The Sequences Category a = [3,5,21,23,5,"fafa"] a.append(499) print(a)
  • 48. © 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.
  • 49. © 2008 Haim Michael 20150805 The Set Category a = {3,5,21,23,5,"fafa",5,3,23,23,"fafa"} print(a)
  • 50. © 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.
  • 51. © 2008 Haim Michael 20150805 The Mappings Category a = { 123123:"haim michael", 42534:"moshe solomon", 454234:"david magen"} print(a.get(542534))
  • 52. © 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.
  • 53. © 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
  • 54. © 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.
  • 55. © 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)
  • 56. © 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
  • 57. © 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.
  • 58. © 2008 Haim Michael 20150805 Complex Numbers  Python supports complex numbers. A complex number is a distinct core object type in Python.  Complex numbers in Python are represented as two floating point numbers. The real and the imaginary part.  We code a complex number by adding 'j' or 'J' suffix to the imaginary part (e.g. 2 + -4j).
  • 59. © 2008 Haim Michael 20150805 Complex Numbers  In order to create a complex number we need to specify a real number and an imaginary one. temp = 3+2j print(type(temp))
  • 60. © 2008 Haim Michael 20150805 Hexadecimal, Octal and Binary  Coding octal literals is done by adding '0o'. 0o1, 0o724,0o123  Coding hexadecimal literals is done by adding '0x'. 0x1A3, 0x32BF, 0x24BA98  Coding binary literals is done by adding '0b'. 0b1001, 0b1100, 0b1001
  • 61. © 2008 Haim Michael 20150805 Hexadecimal, Octal and Binary  Using the oct(), hex() and bin() functions we can convert integers from decimal to other bases' digit strings.
  • 62. © 2008 Haim Michael 20150805 Binary Operations  Python supports most of the numeric expressions available in C, including operators that refer the binary representation. << >> & | ^
  • 63. © 2008 Haim Michael 20150805 Built-in Numeric Tools  In addition to the core object types, Python provides built-in functions and standard library modules that assist with numeric processing. One of them is the math module. ... import math math.sin(123) #gives sin of 123 math.pow(4,2) #gives 16 ...
  • 64. © 2008 Haim Michael 20150805 Decimal Type  Decimals are like floating point values that have a fixed number of digits to the right of the decimal point. Decimals are fixed precision floating point values.  We can create decimal objects by calling the Decimal constructor in the decimal module passing in strings that have the desired number of decimal digits. from decimal import Decimal; Decimal('0.3') + Decimal('2.2') #we should get 2.5 Decimal('-0.4') + Decimal('1.4') #we should get 1
  • 65. © 2008 Haim Michael 20150805 Decimal Type  Calling 'from decimal import Decimal' imports the decimal module, and creates references in the current namespace to the given Decimal object. We can now use Decimal in our program.  We can alternatively call 'import decimal' only and then change our code to the following. import decimal; decimal.Decimal('0.3') + decimal.Decimal('2.2') decimal.Decimal('-0.4') + decimal.Decimal('1.4')
  • 66. © 2008 Haim Michael 20150805 Decimal Type  We can set the precision of all decimal numbers, set up errors handling etc. ... decimal.getcontext().prec=4 #set a precision of 4 digits ...
  • 67. © 2008 Haim Michael 20150805 Decimal Type  Setting the precision effects the result we get from calculation that use the various available operators. It doesn't just influence the result we get on screen.
  • 68. © 2008 Haim Michael 20150805 Fraction Type  As with Decimal, Fraction resides in a separated module. The fractions module. When creating a Fraction object we should pass over a numerator and a denominator. ... from fractions import Fraction numA = Fraction(3,8) numB = Fraction(2,4) numA + numB ...
  • 69. © 2008 Haim Michael 20150805 Fraction Type
  • 70. © 2008 Haim Michael 20150805 Fraction Type import fractions a = fractions.Fraction(3,4) b = fractions.Fraction(3,4) c = a + b print(c)
  • 71. © 2008 Haim Michael 20150805 Booleans  Python has the explicit Boolean data type called bool. Its possible values are 'True' and 'False'. These two objects are instances of bool, a subclass of the built-in integer type int.
  • 72. © 2008 Haim Michael 20150805 Numeric Extensions  There is a large library of third party open source extensions we can use to perform advance operations related to the numeric values we work on. www.scipy.orgwww.numpy.org
  • 73. © 2008 Haim Michael 20150805 Dynamic Typing  When developing code in Python we don't need to predefine the type of a variable we want to use.  In Python, the types are determined automatically at runtime in accordance with the assigned value.
  • 74. © 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.
  • 75. © 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
  • 76. © 2008 Haim Michael 20150805 Variables, Objects & References  Each time we assign a value to the same variable, the type of the referenced object might change into a different type.
  • 77. © 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.
  • 78. © 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.
  • 79. © 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
  • 80. © 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.
  • 81. © 2008 Haim Michael 20150805 Shared References
  • 82. © 2008 Haim Michael 20150805 The sys.getrefcount() Function  Calling this function we can get an object's reference count.
  • 83. © 2008 Haim Michael 20170720 Statements
  • 84. © 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.
  • 85. © 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.
  • 86. © 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.
  • 87. © 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.
  • 88. © 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.
  • 89. © 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.
  • 90. © 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.
  • 91. © 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: ...
  • 92. © 2008 Haim Michael 20170720 Try Statements
  • 93. © 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.
  • 94. © 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.
  • 95. © 2008 Haim Michael 20170720 Assignments  The following illustrates the various assignments forms Python supports. ob = 'abc' - basic form assignment ob_a, ob_b = 'aaa', 'bbb' - tuple assignment [ob_a, ob_b] = ['aaa','bbb'] - list assignment ob_a, ob_b, ob_c = 'abc' - sequence assignment ob_a, *ob_b = 'abc' - extended sequence unpacking ob_a = ob_b = 'abc' - multiple target assignment ob_a += 123 - augment assignment
  • 96. © 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
  • 97. © 2008 Haim Michael 20170720 Tuple & List Unpacking Assignment  The code includes a tuple or a list on the left side of the '=' sign, the objects on the right side are paired with the targets on the left by positioning and assigning them left to right.
  • 98. © 2008 Haim Michael 20170720 Sequence Assignment  Any sequence of names can be assigned with any sequence of values. The values of the specified sequence are assigned one at a time in accordance with their position.
  • 99. © 2008 Haim Michael 20170720 Extended Sequence Assignment  Any sequence of names can be assigned with any sequence of values. The values of the specified sequence are assigned one at a time in accordance with their position. When a specific name is specified with * then the rest of the values will be assigned to it.
  • 100. © 2008 Haim Michael 20170720 Multiple Target Assignments  Specifying multiple names on the left, the same reference will be assigned to each one of them.
  • 101. © 2008 Haim Michael 20170720 Augmented Assignments  The var operator = expression is evaluated as if we write var = var operator expression.  The augmented assignment is supported by each one of the available binary operators. The variable var must be assigned with a value before we can use it.
  • 102. © 2008 Haim Michael 20170720 Useful Patterns  The extended sequence unpacking assignment is highly useful and can be reflected in the following patters.
  • 103. © 2008 Haim Michael 20170720 Variables Names Rules  Each variable name must start either with an underscore or a letter, which can be followed by any number of letters, digits or underscores.  The names are case sensitive and the reserved words cannot be used as names for variables we define.
  • 104. © 2008 Haim Michael 20170720 Variables Names Conventions  The variables and functions that start with an underscore are not imported when using the 'from module import *' statement.  Names with two leading and trailing underscores (__x__) are system defined names with a special meaning to development tools we use.  Class names start with an upper case. Module names start with a lower case.
  • 105. © 2008 Haim Michael 20170720 Names Don't Have Types  The variables' names are not associated with permanent types. Only the objects have types that cannot be changed. For that reason, it is possible to assign the same variable with different types of objects. ob = 12 ob = 43.2 ob = 'abc' ob = [1,2,3,4]
  • 106. © 2008 Haim Michael 20170720 Expression Statements  An expression can be used as a statement... just that its result won't be saved. Calling a function is an example for an expression that is used as a statement.
  • 107. © 2008 Haim Michael 20170720 The print Built-in Function  The print built-int function doesn't return any value we care about (it actually returns None). Calling this function is an example for expression we use as a statement. print ([object, ...][, sep=' '][, end='n'][, file=sys.stdout])
  • 108. © 2008 Haim Michael 20170720 The print Built-in Function  We can assign a new object to sys.stdout. Doing so we can assign an object that represents a file so that every call to print will result in printing out to that file.
  • 109. © 2008 Haim Michael 20170720 The print Built-in Function  Instead of changing the value of sys.stdout it is also possible to change the value of the file parameter we can use when calling the print function.
  • 110. © 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.
  • 111. © 2008 Haim Michael 20170720 The 'if' Statements if <test_1>: statement_1 elif <test_2>: statement_2 elif <test_3>: statement_3 else: statement
  • 112. © 2008 Haim Michael 20170720 The 'if' Statements
  • 113. © 2008 Haim Michael 20170720 The 'if' Statements
  • 114. © 2008 Haim Michael 20170720 Multiway Branching  Python allows us to code multiway branching either by using a series of if/elif tests or by indexing dictionaries or searching lists. Using a separated variable together with a dictionary or an indexed list we can get kind of a functional switch statement.
  • 115. © 2008 Haim Michael 20170720 Multiway Branching  We can get a multiway branching also by calling 'get' on a dictionary object passing over the key as well as the default value to be returned if the key (we pass over) doesn't exist.
  • 116. © 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.
  • 117. © 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.
  • 118. © 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.
  • 119. © 2008 Haim Michael 20170720 Truth Tests
  • 120. © 2008 Haim Michael 20170720 Truth Tests  Comparisons two objects using the the == operator works recursively when applying them to data structures.
  • 121. © 2008 Haim Michael 20170720 Truth Tests
  • 122. © 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
  • 123. © 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>
  • 124. © 2008 Haim Michael 20170720 The while Loop
  • 125. © 2008 Haim Michael 20170720 The while Loop
  • 126. © 2008 Haim Michael 20170720 The while Loop
  • 127. © 2008 Haim Michael 20170720 The while Loop  Calling break will jump out of the closest enclosing loop.  Calling continue will jump to the top of the closest enclosing loop.  Calling pass does nothing. We will call pass when there is nothing we want to do. Since we cannot leave the body empty calling pass is the only solution.
  • 128. © 2008 Haim Michael 20170720 The while Loop
  • 129. © 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>
  • 130. © 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.
  • 131. © 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.
  • 132. © 2008 Haim Michael 20170720 The for Loop  Working with dictionaries we can iterate the keys and use them to get the values.
  • 133. © 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.
  • 134. © 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.
  • 135. © 2008 Haim Michael 20170720 The for Loop  We can nest one loop within another. There is no limit for the number of levels.
  • 136. © 2008 Haim Michael 20170720 The for Loop  We can execute the for loop on every sequence type, including lists, tuples and strings.
  • 137. © 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.
  • 138. © 2008 Haim Michael 20170720 List Comprehensions  Working with a list, instead of iterating its elements using a loop we can create a comprehension list.  We create a comprehension list by placing the logic code on which the new list is based within square brackets.
  • 139. © 2008 Haim Michael 20170720 List Comprehensions  We can use the list comprehension syntax when working with files as well.
  • 140. © 2008 Haim Michael 20170720 Extended List Comprehensions  We can extend the definition for our comprehended list adding a filter condition. list1 = [1,2,3,4,5,6,7,8,9,10] list2 = [num*num for num in list1 if num %2==0] list3 = [num if num%2==0 else "###" for num in list1] print(list1) print(list2) print(list3)
  • 141. © 2008 Haim Michael 20170720 Extended List Comprehensions  We can even extend the definition for our comprehended list adding more for clauses representing other nested loops. 0
  • 142. © 2008 Haim Michael 20170720 The 'range' Function  This function returns a range of numbers. Passing over that range to the list() function we get a list. Calling the iter() function passing over that range we shall get an iterator. Using the next() function we can iterate all elements.
  • 143. © 2008 Haim Michael 20170720 The 'range' Function  This range object we get is iterable so we can iterate it using the for loop.
  • 144. © 2008 Haim Michael 20170720 The 'map' Function  The 'map' function, as well as the 'zip' and the 'filter' functions returns iterable objects we can iterate either directly or indirectly.  Calling the map() function we get a reference for an iterable object through which we can iterate the returned elements. Either directly using the iterator we can get or indirectly using a simple for loop.
  • 145. © 2008 Haim Michael 20170720 The 'map' Function
  • 146. © 2008 Haim Michael 20170720 The 'map' Function
  • 147. © 2008 Haim Michael 20170720 The 'zip' Function  Calling the zip() function we pass over two lists. The zip() function puts together the values from the two lists as if they are pairs.  The zip() function returns an iterable object that holds tuples.
  • 148. © 2008 Haim Michael 20170720 The 'zip' Function
  • 149. © 2008 Haim Michael 20170720 The 'zip' Function
  • 150. © 2008 Haim Michael 20170720 The 'filter' Function  Calling the filter() function we pass over a function and an iterable object. The filter() function returns an iterable object that holds all elements the passed function returned true.
  • 151. © 2008 Haim Michael 20170720 The 'filter' Function
  • 152. © 2008 Haim Michael 20170720 The 'filter' Function
  • 153. © 2008 Haim Michael 20170720 The 'dir' Function  Calling the built-in 'dir' function passing over an object we shall get a list of all attributes available at that object.
  • 154. © 2008 Haim Michael 20170720 The del Keyword  We can use the del keyword for deleting a reference to an object. Every value in Python is an object.
  • 155. © 2008 Haim Michael 20170720 The None Constant  We can use the None constant in order to represent the absent of a value or in order to represent null.  The type of None is NoneType. It isn't possible to create new objects of the NoneType class. We can assign None to multiple variable. All of them will hold the same reference.  When converting None into boolean we will get False.
  • 156. © 2008 Haim Michael 20151020 Functions
  • 157. © 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.
  • 158. © 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
  • 159. © 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.
  • 160. © 2008 Haim Michael 20151020 The def Statement def sum(a,b): total = a + b return total print(sum(4,3))
  • 161. © 2008 Haim Michael 20151020 The def Statement  We can place different definitions for the same function and using a simple if statement choosing which of those versions will be defined. ... if test: def func(): ... else: def func(): ... ...
  • 162. © 2008 Haim Michael 20151020 The def Statement  Each function is just an object. The name assigned to each function is just a name. We use that name in order to call the function.
  • 163. © 2008 Haim Michael 20151020 Function Attributes  Because a function is an object we can add new attributes we choose. def sum(a,b): c = a + b return c sum.version = 101 sum.author = "haim michael" sum.priority = 3 print(sum.author)
  • 164. © 2008 Haim Michael 20151020 Returned Functions  We can define a function that its returned value is another function.  When one function returns a function it includes its definition.  The returned function is capable of referring variables that belong to the scope of the outer one.
  • 165. © 2008 Haim Michael 20151020 Returned Functions def doSomethingA(): number = 7 def doSomethingB(): print(number) return doSomethingB ob = doSomethingA() ob()
  • 166. © 2008 Haim Michael 20151020 Returned Functions
  • 167. © 2008 Haim Michael 20151020 Arguments  When calling a function passing over names, we actually pass the references held by these names.  Assigning new references to the parameter names within the function scope doesn't effect the names the caller passed.  Changing a mutable object from within the function the caller code should feel that as well.
  • 168. © 2008 Haim Michael 20151020 Sequence Returned Value  We can define a function that returns a tuple, or any other sequence type. #dmo def f(a,b): numA = 2 * a numB = 2 * b return [numA,numB] x = f(3,5) print(x)
  • 169. © 2008 Haim Michael 20151020 The func(name) Syntax  By default, the arguments we pass must match by position, left to right, and we must pass exactly as many arguments as required. def f(a,b): sum = a+b print(sum) f(2,3)
  • 170. © 2008 Haim Michael 20151020 The func(name=value) Syntax  Calling a function we can specify which parameters should receive a value by using the argument's name in the name=value syntax. #dmo def f(a,b): numA = 2 * a numB = 2 * b return [numA,numB] x = f(a=3,b=5) print(x)
  • 171. © 2008 Haim Michael 20151020 The func(*name) Syntax  Adding * to the sequence we pass over to the function, the function will be capable of unpacking the passed argument into discrete separated parameters. def f(x1,y1,x2,y2): return (y2-y1)*(y2-y1)+(x2-x1)*(x2-x1) ob = [0,0,4,3] num = f(*ob) print(num)
  • 172. © 2008 Haim Michael 20151020 The func(**name) Function  Adding ** to the argument name, when calling the function a collection of key/value pairs in the form of a dictionary will be expected to be passed over to the function as individual keyword arguments. def f(a,b): print(a) print(b) ob = {'a':1,'b':2} f(**ob)
  • 173. © 2008 Haim Michael 20151020 The func(**name) Function  When defining a function we must specify the parameters in the following order. The first should be the normal parameters. After these parameters we should specify the default parameters followed by the *name parameters and followed by the **name ones.
  • 174. © 2008 Haim Michael 20151020 The def func(name) Syntax  Defining a simple function, the passed values should match by position or name. def f(a,b): sum = a+b print(sum) f(2,3)
  • 175. © 2008 Haim Michael 20151020 The def func(name=value) Syntax  Defining a function we can use the argument's name in the name=value syntax in order to specify default values for specific arguments. def f(a=4,b=6): numA = 2 * a numB = 2 * b return [numA,numB] x = f() print(x)
  • 176. © 2008 Haim Michael 20151020 The def func(name=value) Syntax  This code sample includes a function with two parameters. The first is a normal positioned one. The second has a default value. def f(a,b=6): numA = 2 * a numB = 2 * b return [numA,numB] x = f(5) print(x)
  • 177. © 2008 Haim Michael 20151020 The def func(*name) Syntax  Adding * to the parameter name in the function definition collects unmatched positional arguments into a tuple. #dmo def sum(*tpl): sum = 0 for num in tpl: sum = sum + num return sum print(sum(3,4,6,2,3,6))
  • 178. © 2008 Haim Michael 20151020 The def func(**name) Syntax  Adding ** to the parameter name in the function definition collects unmatched positional arguments into a dictionary. def f(**args): print(args) f(a=10,b=20)
  • 179. © 2008 Haim Michael 20151020 Indirect Function Call  When assigning a function to one of our variables we can append () to that variable and use it in order to call that function. def factorial(a): if a==0: return 1 else: return a * factorial(a-1) f = factorial print(f(5))
  • 180. © 2008 Haim Michael 20151020 Functions Are Objects  Because the functions are objects we can process a function as any other object. >>> dir(factorial) ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] >>>
  • 181. © 2008 Haim Michael 20151020 Anonymous Functions (Lambda)  Using the lambda keyword we can define an anonymous function. lambda param1, param2, param3...paramN : expression  Unlike using def, when using lambda we get an expression. Not a statement.
  • 182. © 2008 Haim Michael 20151020 Anonymous Functions (Lambda) ob = lambda a,b,c:a+b+c print(ob(1,2,3))
  • 183. © 2008 Haim Michael 20151020 Anonymous Functions (Lambda)  Unlike using def, when using lambda we can have one single expression. We cannot have a block of statements.
  • 184. © 2008 Haim Michael 20151025 Classes
  • 185. © 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.
  • 186. © 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.
  • 187. © 2008 Haim Michael 20151025 Simple Class Definition  Assignment to attributes of self in methods create per- instance attributes.
  • 188. © 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.
  • 189. © 2008 Haim Michael 20151025 The Simplest Python Class Definition  Assigning the attributes can be done outside of the class definition.
  • 190. © 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.
  • 191. © 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()))
  • 192. © 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.
  • 193. © 2008 Haim Michael 20151025 Inheritance  Defining a class that extends another we should specify the super class within the parentheses of the class header.
  • 194. © 2008 Haim Michael 20151025 Inheritance
  • 195. © 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.
  • 196. © 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())
  • 197. © 2008 Haim Michael 20151025 The super() Function
  • 198. © 2008 Haim Michael 20151026 Functional Programming
  • 199. © 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.
  • 200. © 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.
  • 201. © 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]))
  • 202. © 2008 Haim Michael 20151026 Recursive Function
  • 203. © 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.
  • 204. © 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.
  • 205. © 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]))
  • 206. © 2008 Haim Michael 20151026 Lambda Expression
  • 207. © 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.
  • 208. © 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))
  • 209. © 2008 Haim Michael 20151026 Higher Order Functions
  • 210. © 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.
  • 211. © 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.
  • 212. © 2008 Haim Michael 20151026 Lazy Evaluation def numbers(): for num in range(10): print("num=",num) yield num for number in numbers(): print(number)
  • 213. © 2008 Haim Michael 20151026 Lazy Evaluation
  • 214. © 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))
  • 215. © 2008 Haim Michael 20151026 Recursion instead of Loop
  • 216. © 2009 Haim Michael All Rights Reserved 216 Questions & Answers Thanks for Your Time! Haim Michael haim.michael@lifemichael.com +972+3+3726013 ext:700 lifemichael