Python 1 2021
Python 1 2021
S. Bertocco
Python introduction
Bibliography and learning materials
★ Bibliography:
https://www.python.org/doc/
http://docs.python.it/
and much more available in internet
★ Learning Materials:
https://github.com/gtaffoni/Learn-Python/tree/master/
Lectures
https://github.com/bertocco/abilita_info_units_1920
Python introduction 2/49
The python language
★ Python is an interpreted language.
– old-style interpreted languages (like bash): the code is
saved in the same format that you entered
– new-style interpreted languages (like python): the
code is pre-processed to produce a bytecode (similar
to machine language) and then executed by the
interpreter (virtual machine).
★ Code portability: means run on hardware/software
platforms different from which used to develop the
code.
– Python is portable if the interpreter is available on the
target platform
Python introduction 3/49
Work Environment Setup
★Pipenv & Virtual Environments
★The next step is to install Pipenv, so you can install
dependencies and manage virtual environments.
# you can make sure you are now working with Python3
python3 – version
# this command will show you what is going on: the python executable
you are using is now located inside your virtualenv repository
which python
deactivate https://naysan.ca/2019/08/05/install-python-3-virtualenv-on-ubuntu/
Rules for Python variable names: A variable can have a short name (like x and y) or
a more descriptive name (age, carname, total_volume):
●
a variable name must start with a letter or the underscore character;
●
a variable name cannot start with a number;
●
a variable name can only contain alpha-numeric characters and underscores (A-
z, 0-9, and _ );
●
white spaces and signs with special meanings, as "+" and "-" are not allowed;
●
variable names are case-sensitive (age, Age and AGE are three different
variables).
Python introduction 10/49
Examples on variable names
●
a variable name must start with a letter or the underscore character
>>> alfa = 1
>>> alfa >>> _pippo = 1
1 >>> _pippo
>>> beta =10 1
●
a variable name cannot start with a number
>>> 1cane=3
1cane=3
^
SyntaxError: invalid syntax
^
SyntaxError: invalid syntax
●
a variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
>>> urca! = 10
File "<stdin>", line 1
urca! = 10
^
SyntaxError: invalid syntax
●
white spaces and signs with special meanings, as "+" and "-" are not allowed
>>> a-b=0 >>> a$b='sara'
File "<stdin>", line 1
File "<stdin>", line 1
a$b='sara'
SyntaxError: can't assign to operator ^
SyntaxError: invalid syntax
Python introduction 11/49
Variable types
Each variable in python has a type.
You can get the data type of any object by using the type()
function:
Example
Print the data type of the variable x:
x=5
print(type(x))
You can also assign a single value to several variables simultaneously multiple
assignments.
Variable a,b and c are assigned to the same memory location, with the value of 1
a=b=c=1
------------------
>>> a = 3
>>> b = 3.4
>>> a + str
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Defining a Function:
Function blocks begin with the keyword def followed by the function name and
parentheses ( ) .
Any input parameter or argument should be placed within these parentheses.
The first statement of a function can be an optional statement (the
documentation string of the function or docstring)
The code block within every function starts with a colon (:) and is indented.
The statement return [value] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.
Syntax:
def function_name( parameters ):
"function_docstring"
instruction_set
…..
return [value]
Python introduction 26/49
Functions: calling a function
Defining a function you specify:
name, parameters and the structure of the block of code.
Given the basic structure of the function, it can executed by calling it from another
function, from a python script or directly from the python prompt.
Example:
#!/usr/bin/python3
# Function definition
def print_string( str ):
"This prints a passed string into this function"
print(str)
return
# Function call
print_string("I'm first call to user defined function!")
print_string("Again second call to the same function")
Required arguments:
the arguments passed to a function in correct positional order. Here, the number of
arguments in the function call should match exactly with the function definition.
Keyword arguments:
are related to the function calls. When you use keyword arguments in a function call,
the caller identifies the arguments by the parameter name. This allows you to skip
arguments or place them out of order because the Python interpreter is able to use
the keywords provided to match the values with parameters
Default arguments:
are arguments that assume a default value if a value is not provided in the function
call for these arguments
Variable-length arguments:
when a function has to be processed for more arguments than the specified in the
function, the variable-length arguments are used. They are not named in the
function definition, unlike required, and default arguments (next lesson).
#!/usr/bin/python3
Name: Silvia
Age 30
Name: Silvia
Age 35
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python:
Global variables
Local variables
Example: Output:
#!/usr/bin/python3
Values inside the function:
# Function definition is here [10, 20, 30, [1, 2, 3, 4]]
def changeme( mylist ):
"This changes a passed list into this function" Values outside the function:
mylist.append([1,2,3,4]) [10, 20, 30, [1, 2, 3, 4]]
print("Values inside the function:\n ", mylist)
# Function call
mylist = [10,20,30]
changelist( mylist )
print("Values outside the function: ", mylist)
The parameter mylist is local to the function changelist. Changing mylist within the
function does not affect mylist outside the function.
Output:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
!/usr/bin/python3
# Function definition is here
def changelist( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4] # This assigns new reference in mylist
print("Values inside the function: ", mylist)
return mylist
# Function call
mylist = [10,20,30]
mylist=changelist( mylist )
print("Values after the function: ", mylist)
The parameter mylist is local to the function changelist. Changing mylist within the
function does not affect mylist outside the function.
Output:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [1, 2, 3, 4]
Modules are useful to break down large programs into small manageable and organized
files.
Modules provide re-usability of code: useful functions can be put in a module and later
imported in another module/script and re-used.
●
Import a single function (my_modules_example_2.py)
from my_libs import multiply
print("Multiply 4 X 5. Result:", multiply(4, 5))
●
Import the entire module by name(my_modules_example_3.py)
import my_libs as example
print(“add 4 and 5.5. Result:”, example.add(4,5.5))
Python introduction 39/49
Example: module os (manage OS dialog operations)
import os
#namespace of module os
>>> os.curdir
’.’
>>> os.getenv('HOME')
'/home/bertocco'
>>> os.listdir('.')
['my_modules_example_1.py',
'read_by_line.py',
'.mozilla',
'.bash_logout',
…..
]
In [2]: import os
In [3]: os.defpath
Out[3]: ':/bin:/usr/bin'
●
The current directory
●
PYTHONPATH (an environment variable with a list of directory. It can be
modified by either applications or user)
●
The installation-dependent default directory
If the module is changed during the course of the program, we would have
to reload it. To reload the module you have two ways:
●
Restart the interpreter (not much clean).
●
Use the function reload() inside the importlib module. Example:
In [29]: import my_libs
In [31]: importlib.reload(my_libs)
Out[31]: <module 'my_libs' from 'my_libs.pyc'>
The interpreter can be used interactively to better know and understand the code.
For example, we have defined the functions add(a,b) and multiply(a,b) in the module
my_libs. We can find them:
In [32]: dir(my_libs)
Out[32]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'add',
'multiply']
names that begin with an underscore are default Python attributes associated with
the module (we did not define them ourself).
All the names defined in the current namespace can be found out using the dir()
function without any arguments. Example (try):
dir()
Example:
In [1]: a=5
In [2]: type a
File "<ipython-input-2-e92615c5fd0c>", line 1
type a
^
SyntaxError: invalid syntax
In [3]: type(a)
Out[3]: int
Pydoc uses the doc string __doc__ and other standard attributes of objects
(__name__, __file__, ...).
$ pydoc os
Help on module os:
NAME
os - OS routines for Mac, DOS, NT, or Posix depending on what system we're on.
FILE
/usr/lib64/python2.4/os.py
DESCRIPTION
This exports:
- all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
- os.path is one of the modules posixpath, ntpath, or macpath
- os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos'
- os.curdir is a string representing the current directory ('.' or ':')
……………………...