Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
PROGRAMMING IN PYTHON 3.XCATALIN BOJA
BOGDAN IANCU
SCOPE
• Understand the language fundamental concepts
• Understand how to use and what’s the development cycle
• Being able to read and understand Python source code
• Prerequisite for starting to modify and write Python source code
2018 © CATALIN BOJA
OTHER RESOURCES
https://docs.python.org/3/library/
https://docs.python.org/3/tutorial/
https://www.learnpython.org/en
https://www.tutorialspoint.com/python/
https://automatetheboringstuff.com/
• Paul Barry David Griffiths, Head First Programming Python, O’Reilly
2018 © CATALIN BOJA
https://docs.python.org/3/tutorial/https://docs.python.org/3/tutorial/https://www.learnpython.org/enhttps://www.tutorialspoint.com/python/https://automatetheboringstuff.com/
UNDERSTANDING PYTHON
Section I – Python fundamentals
• basic concepts: interpreter, scripts
• Prerequisites, using an IDE – IDLE
• Basic Python Concepts: syntax and coding styles, data types, variables, operators, control structures, strings, some collections, functions, lambda
expressions, exceptions, files
2018 © CATALIN BOJA
UNDERSTANDING PYTHON
Section II – Python advanced topics
• Modules
• Classes and objects
• Regular expressions
• Iterators and Generators
• Database
• Networking
• UI
• Standard Library
• Multithreading
2018 © CATALIN BOJA
PREREQUISITES
• Almost none
• Some knowledge about some programming languages (any)
• To know what is a variable or a function
• Ability to abstract problems
• Ability to follow logic flows
2018 © CATALIN BOJA
WHAT IS PYTHON?
• an interpreted programming language
• easy to learn, powerful high-level programming language
• object-oriented
• ranked 5th in TIOBE index (August 2017) - http://www.tiobe.com/tiobe-index/
• used for rapid application development
• created by Guido van Rossum during 1985-1990 at the National Research Institute for Mathematics and Computer Science in the Netherlands
2018 © CATALIN BOJA
http://www.tiobe.com/tiobe-index/
WHY USING PYTHON ?
• easy to learn, to read and maintain
• is portable and extendable
• supports functional, structured programming methods and OOP
• provides very high-level dynamic data types
• supports dynamic type checking
• supports automatic garbage collection
• it can be integrated with C, C++ and Java
2018 © CATALIN BOJA
THE TOOLS
• Windows and Linux/Unix distributions on https://www.python.org/downloads
• The Python interpreter, python, is in the installed folder
• /usr/local/bin/python for Linux
• C:\Python - the path of the Python directory (or any other path)
• A free IDE for Linux and Unix is IDLE - https://www.python.org/downloads/
• A editor: Notepad++, Sublime, JEdit
2018 © CATALIN BOJA
https://www.python.org/downloads/
PYTHON BASICS
• Python Application Structure
• Python Development Steps
• Hello World application
• Command line development with Python 3
• Using an IDE - IDLE
• \Python\Section1\Hello.py
2018 © CATALIN BOJA
PYTHON FUNDAMENTALS
Python source code - module
.py file
=> Interpret and execute – python.exe source.py
Executed by CPython interpreter
2018 © CATALIN BOJA
CPython compiles your python code into bytecode (transparently) and
interprets that bytecode in a evaluation loop. It is implemented in C.
http://stackoverflow.com/questions/17130975/python-vs-cpython
http://stackoverflow.com/questions/17130975/python-vs-cpython
PYTHON FUNDAMENTALS
• Start the python interpreter with optional arguments
• -d – provides debug output
• -O – generates optimized bytecode (resulting in .pyo files)
• -v - verbose output
• C cmd - run Python script sent in as cmd string
• file - run Python script from given file
More available with python.exe -h
2018 © CATALIN BOJA
PYTHON FUNDAMENTALS
1. Needed software and tools
• a simple ASCII editor (Notepad++, Sublime, JEdit, or other) for writing source files;
• Python interpreter, python.exe for Windows to compile and run source code scripts, .py;
• Python libraries
2018 © CATALIN BOJA
INSTALLING PYTHON ON WINDOWS
• python.exe (for Windows) is obtained by installing the Python SDK (Software Development Kit), obtained from the https://www.python.org/downloads/
site;
• the executable is available in your installation folder (eg. D:\PythonInstall);
• If you use Sublime (https://www.sublimetext.com/) you can set it up with the following add-ons: https://realpython.com/blog/python/setting-up-sublime-
text-3-for-full-stack-python-development/
2018 © CATALIN BOJA
https://www.python.org/downloads/https://www.sublimetext.com/https://realpython.com/blog/python/setting-up-sublime-text-3-for-full-stack-python-development/
INSTALLING PYTHON ON LINUX/UBUNTU
• Python can be build by downloading the source code form https://www.python.org/downloads/release/python-352/ site;
• For Ubuntu: $sudo apt-get install python3-minimal
• If you use Sublime (https://www.sublimetext.com/) you can set it up with the following add-ons: https://realpython.com/blog/python/setting-up-sublime-
text-3-for-full-stack-python-development/
2018 © CATALIN BOJA
https://www.python.org/downloads/release/python-352/https://www.sublimetext.com/https://realpython.com/blog/python/setting-up-sublime-text-3-for-full-stack-python-development/
PYTHON FUNDAMENTALS
1. Edit the source code with your chosen editor;
2. Open the command prompt; select Windows Start, type cmd.exe and press Enter;
3. Check if the system knows where to find the two executables, python.exe
4. Set environment variables (if needed)
set PYTHONPATH=D:\PythonInstall
set PATH=%PYTHONPATH%\bin
set PYTHONHOME=%PYTHONPATH%\Lib;
2018 © CATALIN BOJA
PYTHON FUNDAMENTALS
5. Compile, interpret and run the source code
d:\PythonExamples> python.exe HelloWorld.py
6. Run the Python application
An alternative is to use an IDE:
• IDLE (https://www.python.org/downloads/)
• https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
• PyCharm from JertBrains
2018 © CATALIN BOJA
https://www.python.org/downloads/https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
DEVELOPMENT CYCLE
•Use the interpreter in an interactive mode
•Write Python scripts (files with .py extension) and run them with the interpreter
2018 © CATALIN BOJA
DEVELOPMENT CYCLE
Python interactive interpreter
Python IDLE editor
2018 © CATALIN BOJA
PYTHON 3.X VS 2.X
• 3.x introduces some significant changes
• New features can be imported via the in-built __future__ module in Python 2
from __future__ import division
• https://wiki.python.org/moin/Python2orPython3
• https://www.tutorialspoint.com/python3/python3_whatisnew.htm
2018 © CATALIN BOJA
https://www.tutorialspoint.com/python3/python3_whatisnew.htmhttps://www.tutorialspoint.com/python3/python3_whatisnew.htm
PYTHON FUNDAMENTALS
• The language is developed continuously and the official documents are called Python Enhancement Proposals (PEPs) available on
https://www.python.org/dev/peps/
• The official documentation is available on https://www.python.org/doc/ and there are 2 major versions 2.x (2.7 being the latest) and 3.x (3.6 at this
moment)
2018 © CATALIN BOJA
https://www.python.org/dev/peps/https://www.python.org/doc/
PYTHON FUNDAMENTALS
• one line comments defined by #
• multiple lines comments – each line must be commented individually
• the end delimiter for a instruction is Enter (CRLF);
• commented instructions are ignored;
• instructions can be associated in blocks of code that are defined by the same level of indentation; there is no { } like in Java or C/C++
• Python language is case sensitive, vb as variable is different than Vb or VB
• Imports should usually be on separate lines
2018 © CATALIN BOJA
PYTHON CODING STYLE
• “code is read much more often than it is written” (Guido van Rossum)
• Readability is the source code quality that measures the easiness/difficulty of reading it
• If a source is easy to read then it is easy to understand, test and change
• Coding styles rules are part of the Clean Code principles
• For Python the coding rules are defined in PEP 8 (https://www.python.org/dev/peps/pep-0008/)
2018 © CATALIN BOJA
https://en.wikipedia.org/wiki/Guido_van_Rossumhttps://www.python.org/dev/peps/pep-0008/
PYTHON CODING STYLE
• Indentation: use 4 spaces per indentation level and avoid TAB (despite it is tempting)
• Maximum Line Length: maximum of 79 characters (and docstrings/comments to 72).
• Imports are always put at the top of the file on separate lines
• Single-quoted strings and double-quoted strings are the same but a single rule should be used
2018 © CATALIN BOJA
PYTHON CODING STYLE
• Avoid extraneous whitespace
• Avoid trailing whitespace anywhere
• always surround binary operators (+, -, +=, ++, etc.) with a single space on either side
• Avoid comments at all cost – the code should explain itself
2018 © CATALIN BOJA
PYTHON CODING STYLE
• Package and Module Names: short, all-lowercase names
• Class Names: should normally use the CapWords convention
• Exception Names: CapWords convention with the suffix "Error"
• Function Names: lowercase, with words separated by underscores
• Constants: all capital letters with underscores separating words
2018 © CATALIN BOJA
PYTHON CODING STYLE
The Zen of Python (by Tim Peters) rules
PEP 20 - https://www.python.org/dev/peps/pep-0020/
And some examples
http://artifex.org/~hblanks/talks/2011/pep20_by_example.pdf
2018 © CATALIN BOJA
https://www.python.org/dev/peps/pep-0020/http://artifex.org/~hblanks/talks/2011/pep20_by_example.pdf
PYTHON - VARIABLES
Other languages have "variables“,
Python has "names"
http://python.net/~goodger/projects/pycon/2007/idiom
atic/handout.html#other-languages-have-variables
2018 © CATALIN BOJA
http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables
PYTHON - VARIABLES
Built in types:
1. Numeric: integer, bool, float, complex
2. Sequences, mappings, classes, instances and exceptions
3. Mutable Objects: integer, float, complex, str (string), bytes, tuple, frozen set
4. Immutable Objects: byte array, list, set, dictionary
2018 © CATALIN BOJA
PYTHON - VARIABLES
Value data
type
Size Range for signed values Category
int >= 8 bytes equivalent to C longs in Python 2.x, non-limited
length in Python 3.x
integer
float 8 bytes 7 significant digits real double precision
complex a complex number with the
value real + imag*1j
complex value
boolean True, 1 or any value different from 0
False, 0, 0.0, '', (), [], {}
Logic/truth value
2018 © CATALIN BOJA
PYTHON - VARIABLES
• variable name must begin with a letter or underscore symbol (_);
• variable names can not begin with a digit;
• after first character, you can use digits in the variable name;
• variable name can not be a word reserved for Python language, a keyword;
• several variables can be defined simultaneously using , ;
• can’t use @, $, and % within variables names
2018 © CATALIN BOJA
PYTHON - VARIABLES
• variable names are chosen by the programmer, but for efficiency, there are some naming conventions about variable names: Hungarian notation ,
CamelCase;
iBooksNumber #Hungarian Notation
BooksNumber #CamelCase or CapsWords
booksNumber #Java mixed case
2018 © CATALIN BOJA
PYTHON - VARIABLES
• class names should normally use the CapWords convention
• you should use the suffix "Error" on your exception names
• function names should be lowercase, with words separated by underscores or mixedCase
• use one leading underscore only for non-public methods and instance variables
• constants are usually defined in all capital letters with underscores separating words
https://www.python.org/dev/peps/pep-0008/#naming-conventions
2018 © CATALIN BOJA
https://www.python.org/dev/peps/pep-0008/#naming-conventions
PYTHON - VARIABLES
• Python is a dynamically typed language – the variable name is bound to the object, at execution
vb2 = 23.5 #variable vb2 is assign to a float
vb2 = 34 #variable is reassign to an integer
vb2 = True #variable is reassign to a bool value
• Java is statically typed language;
2018 © CATALIN BOJA
PYTHON - VARIABLES
• Python is a strongly typed language - variables can NOT be implicitly converted to unrelated types without an explicit conversion
vb3 = "test"
vb4 = vb3 + 56 #generates TypeError: Can't convert
#'int' object to str implicitly
vb4 = vb3 + str(56) # works
2018 © CATALIN BOJA
PYTHON - VARIABLES
• several variables can be initialized at the same time
vb4 , vb5, vb6 = 1, 23, "test"
• string symbols are defined between ‘ ‘ (apostrophe) or between " " (quotation marks);
• integer values in base 16 (hexadecimal representation) are prefixed with 0x, for example 0×11 is 17 in base 10;
2018 © CATALIN BOJA
PYTHON - VARIABLES
In Python local variables are not initialized
by default, because they are just
names/symbols
You can’t use them without giving them a value
2018 © CATALIN BOJA
PYTHON - VARIABLES
value1 #generates NameError: name
#'value1' is not defined
value2 = value1 + 100
2018 © CATALIN BOJA
PYTHON – SEQUENCE TYPES
• str – strings or arrays of Unicode characters
• bytes – array of bytes
• bytearray – array of bytes
• list – list of values
• tuple – read-only list of values
• range – generator for a list
2018 © CATALIN BOJA
PYTHON – STRINGS
• String• string values (equivalent of string in Java or String in C#)
• used as primitives
• a sequence of Unicode characters (UTF-16 or UTF-32, depending on how Python was compiled)
• Immutable• entities that DO NOT change their value
• almost all values in Python
2018 © CATALIN BOJA
PYTHON – STRINGS
• every char is Unicode value;
• are written in single or double quotes: 'abc', "abc";
• the syntax allows you to use Strings as primitive data types (you can use = operator to initialize them);
• Strings variables are immutable, meaning that once are created, they can’t change their value
2018 © CATALIN BOJA
PYTHON – STRINGS
• you can use == to compare 2 strings value
• you can use + (plus) to concatenate 2 strings
• you can use * (asterisk) to repeat strings
• in and not in operators can be used to check for substrings
• strings are different than byte literals (defined using the b prefix) as latter are arrays of small integers (0 to 255)
2018 © CATALIN BOJA
PYTHON – STRINGS
• + (plus) does NOT convert numbers or other types to string; you need to use str() method
name = ’Alice’
value = 23
name + value #error
name + str(value)
2018 © CATALIN BOJA
PYTHON – STRINGS
• using [] (slice) operator you can access a single or more chars
string[index]
• the index starts at 0 and should not exceed the string length
• you can use negative numbers for an index
• string[start : end] - using a start index and an end index in [] – slice
• in a slice you can omit the start index, the end index or both
2018 © CATALIN BOJA
https://developers.google.com/edu/python/strings
https://developers.google.com/edu/python/strings
PYTHON – STRINGS
name = ”Hello”
name[0] #'H'
name[-3] #'l'
name[:] #'Hello'
name[-2:] #'lo‘
name[:3] #'Hel‘
name[5] #IndexError: string index out of range
2018 © CATALIN BOJA
PYTHON – STRINGS
2018 © CATALIN BOJA
Method Description
replace() replace occurrences of a substring with a given one
split() returns a list of the words in the string, using a given delimiter string
lower() converts all chars to lowercase
upper() converts all chars to uppercase
strip() removes leading and trailing whitespace
find() returns the lowest index in the string where a given substring is found
These methods will create a copy of the String
More on https://docs.python.org/3.1/library/stdtypes.html#string-methods
https://docs.python.org/3.1/library/stdtypes.html#string-methods
PYTHON – STRINGS
• several variables can be initialized at the same time using split()
names = 'John Alice Bob Bianca‘
father, mother, son, daughter = names.split()
2018 © CATALIN BOJA
PYTHON – STRINGS
Escape sequences Value
\b backspace
\t tab
\n line feed
\f form feed
\r carriage return
\” double quotes
\’ apostrophe
\\ backslash
char variables can have as values a series of special characters, escape sequences:
2018 © CATALIN BOJA
PYTHON – STRINGS
• Strings can be formatted using % specifier; similar to sprint() and printf() in C
vb1 = ‘John’
vb2 = 3
text = ('Hello %s, you have %i messages' % (vb1,vb2))
• you can use the r specifier to use a raw string
2018 © CATALIN BOJA
PYTHON – STRINGS
Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%f floating point real number
2018 © CATALIN BOJA
https://www.tutorialspoint.com/python3/python_strings.htm
https://www.tutorialspoint.com/python3/python_strings.htm
PYTHON – STRINGS
• triple quotes """ can be used to define a string that spans over multiple lines
name = """Testing a very long
message that requires more
than 2 lines"""
2018 © CATALIN BOJA
PYTHON – LISTS/ARRAYS
array_name = [] #empty list/array
array_name = [value1,value2, …]
• defined using [] (square brackets)
• different than C/C++ arrays – is in fact a list
• has methods: count(), extend(), index(), insert(), pop(), remove(), reverse(), sort()
2018 © CATALIN BOJA
PYTHON – LISTS/ARRAYS
• array values are mutable; using = you can define multiple variables that will reference the same array
• an array is initialized in 2 steps:
• define the array;
• append values
• access to array elements is done using operator [] and in index that starts at 0
2018 © CATALIN BOJA
PYTHON – LISTS/ARRAYS
• A list can contain values with different types
list = [23,'test',123.4]
• you can use == to compare 2 list values
• you can use + (plus) to concatenate 2 lists
• you can use * (asterisk) to repeat a list
2018 © CATALIN BOJA
PYTHON – LISTS/ARRAYS
2018 © CATALIN BOJA
vector1 = []
vector2 = [1,2,3,4]
vector3 = [5,6,7,8]
empty array
vector2
vector3
1,2,3,4
5,6,7,8
vector3 = vector2 vector3
vector3[0] = 10 10,2,3,4vector2
vector3
PYTHON – TUPLES
tuple_name = () #empty tuple
tuple_name = (value1,value2,… )
• is similar to the list but is read-only
• tuples are enclosed within () parentheses
• it has less methods: index(), count()
2018 © CATALIN BOJA
PYTHON – TUPLES
• when defining a tuple with 1 element, the , (comma) is mandatory
tuple = (34,)
• Because they are read-only you can’t change their values
tuple2 = (34,35,36)
tuple2[1] = 78 #TypeError: 'tuple' object does not support
item assignment
2018 © CATALIN BOJA
PYTHON – RANGE
• range() is a built-in function used to generate a list of numbers
range([start], stop[, step])
• start is by default 0
• step is by default 1
• all parameters are integer values
• can be positive or negative values
2018 © CATALIN BOJA
PYTHON – DICTIONARY
dictionary_name = {} #empty dictionary
• defined using {} (curly braces)
• similar to maps collections in Java
• is a list of key-value pairs
2018 © CATALIN BOJA
PYTHON – DICTIONARY
• a key-value pair is added/used using square braces []
dictionary_name[key_value] = value
• the key or the value can have any type
2018 © CATALIN BOJA
PYTHON FUNDAMENTALS - GARBAGE COLLECTOR
• solve some problems regarding memory management – memory leaks in C++;
• it is an efficient CPython routine that will not interfere with your Python app performance;
• it will not save any out of memory situation
• you can request garbage collector to make a memory clean explicitly by invoking the gc.collect() methodof the gc module
2018 © CATALIN BOJA
PYTHON FUNDAMENTALS
In Python INDENTATION is very, very,
very important. It makes the difference.
It’s a “white space” language
2018 © CATALIN BOJA
PYTHON FUNDAMENTALS
• Python doesn't use braces({}) to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation,
which is rigidly enforced.
• The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount.
2018 © CATALIN BOJA
https://www.tutorialspoint.com/python3/python_basic_syntax.htm
https://www.tutorialspoint.com/python3/python_basic_syntax.htm
PYTHON FUNDAMENTALS - BLOCKS
• Blocks begin when current line indentation increases.
• The statements inside a block must have the same indentation level
• Blocks can contain other blocks.
• Blocks end when the indentation decreases to zero or to a containing block’s indentation.
2018 © CATALIN BOJA
https://automatetheboringstuff.com/chapter2/
https://automatetheboringstuff.com/chapter2/
PYTHON FUNDAMENTALS - BLOCKS
name = "Alice"
password = "12345678"
if (name == "Alice"):
print("Hello "+name)
if (password == "12345678"):
print("Access granted.")
print("You can access your files")
else:
print("Wrong password.")
else:
print("Wrong user.")
2018 © CATALIN BOJA
name = "Alice"
password = "12345678"
if (name == "Alice"):
print("Hello "+name)
if (password == "12345678"):
print("Access granted.")
print("You can access your files")
else:
print("Wrong password.")
else:
print("Wrong user.")
Syntax error
Good vs Evil
PYTHON FUNDAMENTALS
• Use 4 spaces per indentation level
• Spaces are the preferred indentation method
• Tabs should be used solely to remain consistent with code that is already indented with tabs
• Python 3 disallows mixing the use of tabs and spaces for indentation
• Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent
https://www.python.org/dev/peps/pep-0008/#naming-conventions
2018 © CATALIN BOJA
https://www.python.org/dev/peps/pep-0008/#naming-conventions
PYTHON FUNDAMENTALS – OPERATORS
• Assignment operator: =
• Compound assignment operators: +=, -=, *=, /=
• Relational operators: =, ==, !=• The result is a Bool value (True or False)
• The equality (==) operator is doing value check (in C/C++ or Java you must avoid reference check)
• For if control structure you can use only relational operators
2018 © CATALIN BOJA
PYTHON FUNDAMENTALS – OPERATORS
• Boolean/Logical operators: and, or, not
• Arithmetic operators: +, -, *, /, ** (exponent)
• Reminder operator: %
• String concatenation operator: +
• Bit-string operations: |, ^, &, , ~
• Increment and Decrement operators: ++, --• Have 2 forms: prefix and postfix
2018 © CATALIN BOJA
PYTHON FUNDAMENTALS – OPERATORS
• Comma operator: ,• Does not work like the one in C/C++
• Defines a tuple
>>> a = 3
>>> b = 4
>>> a, b = b, a+b #(x , y) – a pair of values like (a, b) = (b, a+b)
>>> a #prints 4
>>> b #prints 7
2018 © CATALIN BOJA
PYTHON FUNDAMENTALS – OPERATORS
The or statement (x or y):
• Evaluate x. If x is True return x. Else return y
The and statement (a and y):
• Evaluate x. If x is False return x. Else return y
Empty string (‘’) and 0 are considered False
2018 © CATALIN BOJA
PYTHON – CONTROL STRUCTURES
Flow control structures:
• if-then
• if-then-else
• while-do
• for
2018 © CATALIN BOJA
PYTHON – CONTROL STRUCTURES
2018 © CATALIN BOJA
IF-THEN
if (condition):
-- < statement 1 >
-- < statement 2 >
- condition is a Boolean expression or
variable that has the value True or
False. For example 30> 10 or 10
== 30
- are expressions or variables that
have numeric values
- the condition parentheses are
optional
- the statements must have the same
indentation level
same indentation level
PYTHON – CONTROL STRUCTURES
2018 © CATALIN BOJA
IF-THEN-ELSE
if (condition):
-- < statement 1 >
-- < statement 2 >
else:
-- < statement 3 >
-- < statement 4 >
- the colon (:) is mandatory
- condition parenthesis () are optional
and is recommended not to use them
same indentation level
PYTHON – CONTROL STRUCTURES
2018 © CATALIN BOJA
IF-THEN-ELSE-IF
if (condition1):
-- < statement 1 >
-- < statement 2 >
elif (condition2):
-- < statement 3 >
-- < statement 4 >
- the colon (:) is mandatory
- the else-if block will execute if
condition1 is evaluated to False and
the condition2 is evaluated to True
same indentation level
PYTHON – CONTROL STRUCTURES
2018 © CATALIN BOJA
WHILE-DO
while condition:
< statement 1>
< statement 2>
- the condition for exiting
from/staying in the loop is
checked before the first
statement in the loop block is
executed
PYTHON – CONTROL STRUCTURES
2018 © CATALIN BOJA
FOR
for item in collection:
< statement 1>
< statement 2>
- like do-while
- item iterates through each value
- the collection must be a sequence
(list, tuples and strings)
- is efficient, simply because the
iteration and the initialization
statements are included in the
structure and not in the block;
PYTHON – CONTROL STRUCTURES
BREAK and CONTINUE statements:
• break statement stops the current loop block implemented by for, while-do;
• continue instruction will suspend the current iteration of a loop block, for, while-do and will execute the next iteration
2018 © CATALIN BOJA
PYTHON - FUNCTIONS
def function_name(arguments list):
["function description"]
return [value]
• are code sequences that can be reused
• allow functional programming
2018 © CATALIN BOJA
PYTHON - FUNCTIONS
• a function is called by its name, passing the required arguments
function_name(arguments_value)
value = function_name(arguments_value)
• the first statement in the function body can be a description string used for help (similar to JavaDoc)
• a function can return a value
2018 © CATALIN BOJA
PYTHON – FUNCTIONS ARGUMENTS
You can call a function by using following types of arguments:
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
2018 © CATALIN BOJA
PYTHON – FUNCTIONS ARGUMENTS
• methods receive input parameters by references
• ATTENTION most data types are immutable so changing their value inside the method will redefine the variable;
• collections values are mutable
2018 © CATALIN BOJA
PYTHON – FUNCTIONS ARGUMENTS
• transfer parameters by their value• changing the value inside the function will modify only the local copy
def changeValues (value1, value2):
value1 = "New value"
value2 = 100
return
vb1,vb2 = 10,20
changeValues(vb1,vb2) #calling method
Check Functions.py
2018 © CATALIN BOJA
PYTHON – FUNCTIONS ARGUMENTS
• transfer parameters by reference• works for collections because their values are mutable
def doSomething2( list ):
"Changing list values inside a list - #2"
for i in range(0,3):
list[i] = 10
return
2018 © CATALIN BOJA
Check Functions.py
PYTHON – FUNCTIONS ARGUMENTS
• changing the list reference will create a local copy; changes are not visible outside
def doSomething3( list ):
"Changing list values inside a list - #3"
list = [30,40,50]
return
2018 © CATALIN BOJA
Check Functions.py
PYTHON – FUNCTIONS ARGUMENTS
• changing the list values using an iterator; changes are not visible outside
def doSomething1( list ):
"Changing list values inside a list - #1"
for value in list:
value = 10
return
2018 © CATALIN BOJA
Check Functions.py
PYTHON – FUNCTIONS ARGUMENTS
• transfer parameters by their reference
How to do that for a primitive variable ?
1. NO way to get the address of a primitive
2. Use an array
3. Define your own wrapper class/structure
2018 © CATALIN BOJA
PYTHON – FUNCTIONS ARGUMENTS
• keyword arguments are related only to the function calls; a keyword is in fact the argument name
• using keyword arguments in a function call, the caller identifies the arguments by the parameter name.
• using keyword arguments you can skip arguments or place them out of order
2018 © CATALIN BOJA
PYTHON – FUNCTIONS ARGUMENTS
def doSomething (value1, value2):
print("value1 = ",value1)
print("value2 = ",value2)
return
#using keywords
doSomething(value1 = 10,value2 = 20)
doSomething(value2 = 20, value1 = 10)
2018 © CATALIN BOJA
PYTHON – FUNCTIONS ARGUMENTS
• methods can have variable length inputs
def functionname([formal_args,] *var_args_tuple ):
"function description"
function_suite
return [expression] Check Functions.py
2018 © CATALIN BOJA
PYTHON – VARIABLES SCOPE
• local variables – these variables are defined on the function body and they exists as long as the method is executed; local variables are not visible
outside the function body
• global variables – these variables are defined in the module global scope; global variables can be used inside functions;
• Shadowing – defining a local variable with the same name as a global one; it will shadow/hide the global one
2018 © CATALIN BOJA
PYTHON – VARIABLES SCOPE
value = 'global‘
def test1():
print (value)
return
def test2():
value = 'local for test2' #shadowing global variable
print(value) # prints 'local for test2'
return
2018 © CATALIN BOJA
VariablesScope.py
PYTHON – USING MODULES
• A module is a .py script file. It can be reused using import keyword
import module_name
• Module variables and methods are accessed using module name specifier
module_name.variable_name
module_name.method_name
• Contextual help can be obtained using
dir(module_name) or help(module_name)
2018 © CATALIN BOJA
PYTHON – EXCEPTIONS
• exception - the situation where processing certain input data is not managed or is not possible (eg dividing by 0, reading outside the bounders of an array)
• allows management of exceptional situations that lead to immediate termination of the program
• necessary to achieve robust and reliable programs
• implemented through try, except, finally and raise
• allows the management of system exceptions
2018 © CATALIN BOJA
PYTHON – EXCEPTIONS
1. Compilation error = fail at COMPILE time. You need to correct it.
2. Errors = pass the compilation but fail at RUN-TIME because ......(ex. Bad
blocks on the HDD and you get an error trying to open the file).
3. Runtime exception = pass the compilation but fail at RUN-TIME. You can
implement try-catch, but is better to check and avoid.
2018 © CATALIN BOJA
PYTHON – EXCEPTIONS
try:
#statements
except exception_type_1 as e: #the name e is optional
#particular statements
except exception_type_2:
#particular statements
except: # catch *all* exceptions
#general statements
finally:
#must do always statements 2018 © CATALIN BOJA
PYTHON – EXCEPTIONS
try:
• contains the sequence of code that may generate exceptions;• has at least one catch block;• between the try block and catch blocks there are no other instructionsexcept [exception_type [as error]]:
• catch and manage an exception of exception_type type• exception_type is an instance of a class derived from BaseException (more on
https://docs.python.org/3/library/exceptions.html)
• you can process the exception if you associate a symbol using [as symbol_name]
2018 © CATALIN BOJA
https://docs.python.org/3/library/exceptions.html
PYTHON – EXCEPTIONS
except:
• catch and manage all exceptions
finally:
• contains code sequence that it is executed whether or not the try block has generated exceptions and whether they were or were not managed in other
catch blocks;
2018 © CATALIN BOJA
Exceptions.py
PYTHON – EXCEPTIONS
catch blocks are defined in the ascending order of the caught exceptions generality level
try:
except exception_type_1:
except exception_type_2:
…
except :
2018 © CATALIN BOJA
PYTHON – EXCEPTIONS
• try-except-finally blocks can be included in other try blocks;
• The programmer can define its own exceptions with classes derived from BaseException;
• raise function generates a new exception; without arguments will rise the previous error
• Attention to local variables defined in try or in except blocks and used outside. If the variable is not initialized you will get a name is not defined error
2018 © CATALIN BOJA
Exceptions.py
PYTHON – EXCEPTIONS
• in an except block you can use a raise-else combination; you can change to a finally based logic
try:
do_some_stuff()
except:
rollback()
raise #raise the error again if any
else:
commit()
2018 © CATALIN BOJA
https://wiki.python.org/moin/HandlingExceptions
https://wiki.python.org/moin/HandlingExceptions
PYTHON – INPUT
• two built-in functions to read a line of text from standard input
• raw_input([prompt]) – reads one line from standard input and returns it as a string
• input([prompt]) – like raw_input but assumes the input is a valid Python expression and returns the evaluated result
2018 © CATALIN BOJA
PYTHON – FILES
• Files/Folders are opened for read/write using the open(file_name [, access_mode][, buffering]) function
• filename – file name for local files of full path
• mode – a string representing one or a combination of different flags:r, rb, r+, rb+, w, wb, w+, wb+, a, ab, a+, ab+
• buffering: If the buffering value is set to 0, no buffering takes place
• more on https://www.tutorialspoint.com/python/python_files_io.htm
2018 © CATALIN BOJA
https://www.tutorialspoint.com/python/python_files_io.htm
PYTHON – FILES
2018 © CATALIN BOJA
• Files have attributes:• file.closed - returns true if file is closed, false otherwise.• file.mode - returns access mode with which file was opened.• file.name - returns name of the file
• File methods:• close();• write();• read([count]) – reads a number of bytes; if count is missing, then it tries to read as much as
possible, until the end of file
PYTHON – FILES
• File methods:• tell() – number of bytes from the beginning of the file• seek(offset[, from]) – for from argument, 0 – beginning, 1 – current location and 2 - end
• System methods for files (os module)• os.rename(current_file_name, new_file_name)• os.remove(file_name)• os.mkdir("newdir")• os.chdir("newdir")
2018 © CATALIN BOJA
PYTHON – ADVANCED TOPICS
• Iterators
• Generators
• Yield vs Return
2018 © CATALIN BOJA
PYTHON - ITERATORS
• Simply put, an iterator in python is any python type that can be used with a for loop.E.g:
• Lists
• Dictionaries
• Tuples
• etc.
• These types are iterators because they implement the iterator pattern.
• What that actually means is that they have some “magic methods” in their structure that the for loop can use to, well, iterate through the sequence.
2018 © CATALIN BOJA
PYTHON - ITERATORS
for item in collection:
• the iteration and the initialization are done in the structure and not in the block;
• the two “magic methods” implemented by each iterable object are:
• __iter__: method that is called on initialization of an iterator. This method should
return an object that has the __next__
method.
• __next__: returns the next value for the iterable.
2018 © CATALIN BOJA
PYTHON - GENERATORS
• Python generators are essentially a more efficient type of iterators.
• They can be used by either calling the next() method or by using the generator in a for loop.
• Unlike iterators, the generator objects use the yield keyword internally to provide the same functionality iterators provide using the __iter__ and __next__ methods.
2018 © CATALIN BOJA
PYTHON – YIELD VS RETURN
• Yield:• if a yield statement is encountered, the state of the function is frozen, and the value
proceeding the yield statement is returned to the caller.
• enough information is saved so that the next time .next() is invoked, the function can proceed exactly as if the yield statement were just another external call.
• Return:• when a function encounters a return statement, it returns to the caller along with any value
proceeding the return statement and the execution of such function is complete for all intent
and purposes.
2018 © CATALIN BOJA
PYTHON – YIELD VS RETURNYIELD RETURN
2018 © CATALIN BOJA
PYTHON – YIELD KEYWORD
2018 © CATALIN BOJA
PYTHON – YIELD KEYWORD
• Unlike iterators, generators can accept input from the user when the yield keyword is used as a right hand operator.
2018 © CATALIN BOJA
QUESTIONS ?
2018 © CATALIN BOJA