Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python in A Nutshell: Python's Whys & Hows

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Python’s Whys & Hows

What is Python

Python in a Python in a
Nutshell Nutshell

Walter Cazzola Walter Cazzola

Python Python Python is a general-purpose high-level programming language.


Whys Whys
– it pushes code readability and productivity;
Hows Python in a Nutshell Hows

Python’s Basics Python’s Basics – it best fits the role of scripting language.
functions
Overview of the Basic Concepts functions
Readable Code Readable Code Python supports multiple programming paradigms
Objects Objects
Indenting Code Indenting Code – imperative (functions, state, . . . );
Exceptions Exceptions
Running Scripts
Walter Cazzola Running Scripts – object-oriented/based (objects, methods, inheritance, . . . );
References References – functional (lambda abstractions, generators, dynamic typing, . . . ).
Dipartimento di Informatica e Comunicazione
Università degli Studi di Milano Python is
e-mail: cazzola@dico.unimi.it – interpreted, dynamic typed and object-based;
– open-source.

Slide 1 of 14 Slide 2 of 14

Python’s Whys & Hows Python’s Whys & Hows


How to Use Python How to Use Python (Cont’d)

Python in a
Nutshell
We are considering Python 3+ Python in a
Nutshell
The python shell can be used to get interactive help.
Walter Cazzola – versions >3 is incompatible with previous versions; Walter Cazzola [23:35]cazzola@ulik:~/esercizi-pa>python3
– version 2.6 is the current version. Python 3.1.1 (r311:74480, Aug 17 2009, 21:52:33)
[GCC 4.4.1] on linux2
Python Python
Type "help", "copyright", "credits" or "license" for more information.
Whys
A python program can be: Whys
>>> help()
Hows Hows

Python’s Basics
– edited and run through the interpreter Python’s Basics Welcome to Python 3.1! This is the online help utility.
functions functions
Readable Code
[23:31]cazzola@ulik:~/esercizi-pa>vim hello.py Readable Code If this is your first time using Python, you should definitely check out
Objects
[23:32]cazzola@ulik:~/esercizi-pa>cat hello.py Objects the tutorial on the Internet at http://docs.python.org/tutorial/.
Indenting Code
print("Hello World!!!") Indenting Code
Exceptions
[23:32]cazzola@ulik:~/esercizi-pa>python3 hello.py Exceptions Enter the name of any module, keyword, or topic to get help on writing
Running Scripts
Hello World!!! Running Scripts Python programs and using Python modules. To quit this help utility and
[23:32]cazzola@ulik:~/esercizi-pa> return to the interpreter, just type "quit".
References References
To get a list of available modules, keywords, or topics, type "modules",
– edited in the python shell and executed step-by-step by the shell. "keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
[23:34]cazzola@ulik:~/esercizi-pa>python3 such as "spam", type "modules spam".
Python 3.1.1 (r311:74480, Aug 17 2009, 21:52:33)
[GCC 4.4.1] on linux2 help> ^D
Type help, copyright, credits or license for more information. You are now leaving help and returning to the Python interpreter.
>>> print("Hello World!!!") If you want to ask for help on a particular object directly from the
Hello World!!! interpreter, you can type "help(object)". Executing "help(’string’)"
>>> has the same effect as typing a particular string at the help> prompt.
[23:35]cazzola@ulik:~/esercizi-pa> >>> ^D
[23:40]cazzola@ulik:~/esercizi-pa>

Slide 3 of 14 Slide 4 of 14
Overview of the Basic Concepts Overview of the Basic Concepts
Our First Python Program Declaring Functions

Python in a Python in a
Nutshell humanize.py Nutshell

Walter Cazzola Walter Cazzola


SUFFIXES = {1000: [’KB’, ’MB’, ’GB’, ’TB’, ’PB’, ’EB’, ’ZB’, ’YB’], Python has function
1024: [’KiB’, ’MiB’, ’GiB’, ’TiB’, ’PiB’, ’EiB’, ’ZiB’, ’YiB’]}
Python Python – no header files à la C/C++
Whys def approximate_size(size, a_kilobyte_is_1024_bytes=True): Whys
Hows ’ ’ ’ Convert a f i l e s i z e t o human r e a d a b l e f o r m . ’’’ Hows – no interface/implementation à la Java.
Python’s Basics if size < 0: Python’s Basics
functions
raise ValueError(’number must be non-negative’) functions def approximate_size(size, a_kilobyte_is_1024_bytes=True):
Readable Code
multiple = 1024 if a_kilobyte_is_1024_bytes else 1000 Readable Code
Objects
for suffix in SUFFIXES[multiple]: Objects
Indenting Code
size /= multiple Indenting Code
Exceptions
if size < multiple: Exceptions
Running Scripts
return ’{0:.1f} {1}’.format(size, suffix) Running Scripts function function comma default
raise ValueError(’number too large’) definition name separate ar- value
References References keyword gument
if __name__ == ’__main__’: list
print(approximate_size(1000000000000, False))
print(approximate_size(1000000000000)) Note
– no return type, it always return a value (None as a default);
Running the program:
– no parameter types, the interpreter figures out the parameter
[16:00]cazzola@ulik:~/esercizi-pa>python3 humanize.py type;
1.0 TB
931.3 GiB
[16:01]cazzola@ulik:~/esercizi-pa>

Slide 5 of 14 Slide 6 of 14

Overview of the Basic Concepts Overview of the Basic Concepts


Calling Functions Writing Readable Code

Python in a Python in a
Nutshell Nutshell

Walter Cazzola Walter Cazzola

Look at the bottom of the humanize.py program:


Python Python Documentation Strings
Whys 1 if __name__ == ’__main__’: Whys
Hows 2 print(approximate_size(1000000000000, False)) Hows A Python function can be documented by a documentation string
3 print(approximate_size(1000000000000))
Python’s Basics Python’s Basics (docstring for short).
functions functions
Readable Code
2 in this call to approximate_size(), the a_kilobyte_is_1024_bytes
Readable Code
’’’ Convert a file size to human readable form. ’’’
Objects Objects
Indenting Code parameter will be False since you explicitly pass it to the function; Indenting Code
Triple quotes delimit a single multi-string.
Exceptions Exceptions
Running Scripts 3 in this row we call approximate_size() with only a value, the parame- Running Scripts – if it immediately follows the function’s declaration it is the doc-
References ter a_kilobyte_is_1024_bytes will be True as defined in the function References string associated to the function.
declaration.
– docstrings can be retrieved at run-time (they are attributes).
Value can be passed by name as in: Case-Sensitive
approximate_size(a_kilobyte_is_1024_bytes=False, size=1000000000000)
All names in Python are case-sensitive.
Parameters’ order is not relevant.

Slide 7 of 14 Slide 8 of 14
Overview of the Basic Concepts Overview of the Basic Concepts
Everything is an Object Everything is an Object (Cont’d)

Python in a Python in a
Nutshell Everything in Python is an Object, functions included. Nutshell

Walter Cazzola Walter Cazzola


In Python everything is an object, better, is a first-class object
[15:51]cazzola@ulik:~/esercizi-pa>python3 – everything can be assigned to a variable or passed as an argument.
Python 3.1.1 (r311:74480, Aug 17 2009, 21:52:33)
Python [GCC 4.4.1] on linux2 Python
Whys Type help, copyright, credits or license for more information. Whys
[16:30]cazzola@ulik:~/esercizi-pa>python3
Hows >>> import humanize Hows
Python 3.1.1 (r311:74480, Aug 17 2009, 21:52:33)
Python’s Basics >>> print(humanize.approximate_size(4096)) Python’s Basics [GCC 4.4.1] on linux2
functions 4.0 KiB functions Type help, copyright, credits or license for more information.
Readable Code >>> print(humanize.approximate_size.__doc__) Readable Code >>> import humanize
Objects Convert a file size to human-readable form. Objects >>> h1 = humanize.approximate_size(9128)
Indenting Code >>> Indenting Code >>> h2 = humanize.approximate_size
Exceptions [15:52]cazzola@ulik:~/esercizi-pa> Exceptions >>> print("’{0}’ is the stored value, ’{1}’ is the calculated value".format(h1, h2(9128)))
Running Scripts Running Scripts ’8.9 KiB’ is the stored value, ’8.9 KiB’ is the calculated value
>>>
References References
– import can be used to load python programs in the system as modu- [16:36]cazzola@ulik:~/esercizi-pa>
les;
– the dot-notation gives access to the public functionality of the Note
imported modules; – h1 contains the string calculated by approximate_size(9128);
– the dot-notation can be used to access the attributes (e.g., the – h2 contains the “function” object approximate_size, the result is
__doc__); not calculated yet;
– humanize.approximate_size.__doc__ gives access to the docstring – to simplify the concept: h2 can be considered as a new name of (alias
of the approximate_size() function; the docstring is stored as an to) approximate_size.
attribute.
Slide 9 of 14 Slide 10 of 14

Overview of the Basic Concepts Overview of the Basic Concepts


Indenting Code Exceptions

Python in a Python in a
Nutshell Nutshell Exceptions are Anomaly Situations
Walter Cazzola Walter Cazzola – C encourages the use of return codes which you check;
No explicit block delimiters
– the only delimiter is a column (’:’) and the code indentation. – Python encourages the use of exceptions which you handles.
Python Python
Whys Whys
Hows
def approximate_size(size, a_kilobyte_is_1024_bytes=True): Hows Raising Exceptions
Python’s Basics if size < 0: Python’s Basics – the raise statement is used to raise an exception as in
functions raise ValueError(’number must be non-negative’) functions
Readable Code multiple = 1024 if a_kilobyte_is_1024_bytes else 1000 Readable Code raise ValueError(’number must be non-negative’)
Objects for suffix in SUFFIXES[multiple]: Objects
Indenting Code size /= multiple Indenting Code – syntax recalls function calls: raise statement followed by an excep-
Exceptions if size < multiple: Exceptions
Running Scripts return ’{0:.1f} {1}’.format(size, suffix) Running Scripts
tion name with an optional argument;
raise ValueError(’number too large’)
References References – exceptions are realized by classes.
Note No need to list the exceptions in the function declaration.
– code blocks (i.e., functions, if statements, loops, . . . ) are defined by Handling Exceptions
their indentation;
– an exception is handled by a try . . . except block.
– white spaces and tabs are relevant: use them consistently;
try:
– indentation is checked by the compiler. from lxml import etree
except ImportError:
import xml.etree.ElementTree as etree

Slide 11 of 14 Slide 12 of 14
Overview of the Basic Concepts References
Running Scripts

Python in a Python in a
Nutshell Nutshell
Look, again, at the bottom of the humanize.py program:
Walter Cazzola Walter Cazzola
1 if __name__ == ’__main__’:
2 print(approximate_size(1000000000000, False))
Python
Whys
3 print(approximate_size(1000000000000))
Python
Whys
I Jennifer Campbell, Paul Gries, Jason Montojo, and Greg Wilson.
Hows Hows
Practical Programming: An Introduction to Computer Science Using
Modules are Objects
Python’s Basics Python’s Basics Python.
functions – they have a built-in attribute __name__ functions
Readable Code Readable Code The Pragmatic Bookshelf, second edition, 2009.
I
Objects Objects
[18:29]cazzola@ulik:~/esercizi-pa>python3
Indenting Code Indenting Code
Mark Lutz.
Exceptions >>> import humanize Exceptions
Running Scripts >>> humanize.__name__ Running Scripts Learning Python.
’humanize’
References
>>> ^D
References O’Reilly, third edition, November 2007.
I
[18:30]cazzola@ulik:~/esercizi-pa>python3 humanize.py
1.0 TB Mark Pilgrim.
931.3 GiB
[18:30]cazzola@ulik:~/esercizi-pa> Dive into Python 3.
Apress*, 2009.
The value of __name__ depends on how you call it
– if imported it contains the name of the file without path and
extension;
– if run as a stand-alone program it contains the "main" string.

Slide 13 of 14 Slide 14 of 14

You might also like