programming in python 3 -  · programming in python 3.x catalin boja [email protected] bogdan...

113
PROGRAMMING IN PYTHON 3.X CATALIN BOJA [email protected] BOGDAN IANCU [email protected]

Upload: others

Post on 21-May-2020

41 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

PROGRAMMING IN PYTHON 3.XCATALIN BOJA

[email protected]

BOGDAN IANCU

[email protected]

Page 2: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 3: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 4: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 5: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 6: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 7: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 8: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 9: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 10: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 11: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 12: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 13: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 14: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 15: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 16: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 17: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 18: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 19: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

DEVELOPMENT CYCLE

Python interactive interpreter

Python IDLE editor

2018 © CATALIN BOJA

Page 20: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 21: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 22: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 23: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 24: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 25: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 26: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 27: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 28: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 29: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 30: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 31: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 32: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 33: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 34: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 35: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 36: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 37: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 38: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

PYTHON - VARIABLES

value1 #generates NameError: name

#'value1' is not defined

value2 = value1 + 100

2018 © CATALIN BOJA

Page 39: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 40: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 41: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 42: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 43: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 44: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 45: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 46: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 47: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 48: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 49: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 50: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 51: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 52: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 53: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 54: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 55: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 56: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 57: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 58: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 59: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 60: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 61: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 62: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

PYTHON FUNDAMENTALS

In Python INDENTATION is very, very,

very important. It makes the difference.

It’s a “white space” language

2018 © CATALIN BOJA

Page 63: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 64: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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/

Page 65: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 66: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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 indenthttps://www.python.org/dev/peps/pep-0008/#naming-conventions

2018 © CATALIN BOJA

Page 67: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 68: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 69: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 70: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 71: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

PYTHON – CONTROL STRUCTURES

Flow control structures:

• if-then

• if-then-else

• while-do

• for

2018 © CATALIN BOJA

Page 72: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 73: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 74: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 75: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 76: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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;

Page 77: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 78: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

PYTHON - FUNCTIONS

def function_name(arguments list):

["function description"]

<statement1>

<statement2>

return [value]

• are code sequences that can be reused

• allow functional programming

2018 © CATALIN BOJA

Page 79: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 80: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 81: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 82: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 83: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 84: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 85: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 86: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 87: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 88: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 89: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 90: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 91: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 92: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 93: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 94: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 95: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 96: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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 instructions

except [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

Page 97: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 98: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 99: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 100: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 101: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 102: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 103: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 104: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 105: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

PYTHON – ADVANCED TOPICS

• Iterators

• Generators

• Yield vs Return

2018 © CATALIN BOJA

Page 106: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 107: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

PYTHON - ITERATORS

for item in collection:

<statement 1>

<statement 2>

• 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

Page 108: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 109: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 110: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

PYTHON – YIELD VS RETURNYIELD RETURN

2018 © CATALIN BOJA

Page 111: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

PYTHON – YIELD KEYWORD

2018 © CATALIN BOJA

Page 112: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

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

Page 113: PROGRAMMING IN PYTHON 3 -  · programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

QUESTIONS ?

2018 © CATALIN BOJA