0% found this document useful (0 votes)
12 views

Lab SSE1

Uploaded by

BYRON TONY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Lab SSE1

Uploaded by

BYRON TONY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

PYTHON AND PYCHARM Antonio Luca Alfeo

1
INTRODUCTION TO PYTHON

Based on previous lecture by F. Galatolo


2
WHY PYTHON?
Created by Guido van Rossum in the 1980s, to be a general-purpose
language with a simple and readable syntax. Today is more and more required
since it is:
• High level
• Open source
• Portable: write once run
everywhere
• Extendible in C/C++
• Easy to learn
• With a mature and supportive
community
• With hundreds of thousands of
libraries, packages and
frameworks, supported by big
players (Google, Facebook,
Amazon) and non-profit
organizations
3
VIRTUAL ENVIRONMENT
•In each project, a number of Python packages are imported and used. Each of
them may requires a given version of other packages and Python as well.
•A virtual environment is a self-contained directory tree that contains a Python
installation for a particular version of Python, plus a number of additional
packages
•In this way, the project-wide dependencies are stored, easily snapshotted and
retrieved
•Create a Virtual Environment with Python X.Y in folder env
virtualenv --python=pythonX.Y env
•Activate the Virtual Environment
source ./env/bin/activate
. ./env/bin/activate
•Deactivate the Virtual Environment
deactivate

4
BASIC PACKAGES MANAGING
•Install package
pip install package
•Uninstall package
pip uninstall package
•Snapshot installed packages in requirements.txt
pip freeze > requirements.txt
•Install all packages snapshotted in requirements.txt
pip install -r requirements.txt
•Now you can import and use this packages in your project

5
ANACONDA
Anaconda is a distribution of Python that aims to simplify package management
and deployment, suitable for Windows, Linux, and macOS.
Package versions in Anaconda are managed by conda, an open source, cross-
platform, language-agnostic package manager and environment management
system
Conda analyses the current environment including everything currently installed,
works out how to install/run/update a compatible set of dependencies

6
PYTHON IDE + MINICONDA = PYCHARM
Pycharm offers configurable python interpreter
and virtual environment support.

Based on previous lecture by A. L. Alfeo


7
INSTALLATION 1/2
1. Install PyCharm using this links:
 Linux
 Windows
 MacOs

2. During PyCharm installation


enable “open folder as project”

8
INSTALLATION 2/2
•Accept the JetBrains Privacy Policy

•Choose the UI theme you prefer

•Do not install any featured plugin

•Install Miniconda: includes the


conda environment manager,
Python, the packages they
depend on, and a small number of
other useful packages (e.g. pip).

•Remember, Miniconda can be


installed at any time from
Tools -> Install Miniconda3
•Start using PyCharm

9
NEW PROJECT
Create a new project. Name it “first_project”.

If needed set the conda executable path.

10
GUI
Menu Toolbar Run/Debug buttons

Project view
Editor

Console and Tool windows

11
INTERPRETER: DEFAULT CONFIGURATIONS
Is there a red X here?

Now you can run it!

12
PYTHON BASICS

13
INDENTATION
In python code blocks are not surrounded by curly brackets. Just use
the correct indentation!

14
BUILT-IN TYPES
Python is dynamically typed, i.e. types are determined at runtime.
Variables can freely change type during the execution.

In python there are a lot of built-in types, the most notables are:
•Boolean (bool)
•Strings (str)
•Numbers (int, float)
•Sequences (list, tuple)
•Mapping (dict)

15
VARIABLES
Variables can be assigned to given values…
pi = 3
name = “Pippo"
…Even multiple variables at once via iterable unpacking. Click for more
on iterable data structures (e.g. lists, tuples…)!
pi, name = 3, “Pippo"
first, second, third = SomeSequence
In Python everything is stored and passed as reference with the only
exception of Numbers.
a = [1, 2, 3]
b=a
b[0] = 5 # now a = [5, 2, 3]

16
CONDITIONAL INSTRUCTION 1/2
Simple conditional instruction with the if keyword.

Python uses and and or as logical operators instead of && and ||

Inline conditional instructions can be used as it follows

17
CONDITIONAL INSTRUCTION 2/2
The if-else statement is used as it follows

There is no switch case statement in Python. Just use if and elif

18
TRY IT YOURSELF!

19
LOOPS 1/2
There is no do-while loop, just while and for loops

Tuple unpacking can be used with loops iterations

20
LOOPS 2/2
zip() combines one-by-one the elements of two or more iterables

enumerate() returns a list of (index, element) tuples

For efficient loops an iterable object can leverage the itertools packages.
The simplest iterable can be a list created via list comprehension

21
FUNCTIONS: DEFINITION
A new function can be defined by using the keyword def

Default argument are indicated with =

Inline functions can be created by using the lambda keyword

22
FUNCTIONS: POSITIONAL ARGUMENTS
A variable number of arguments can be defined via the * symbol

A sequence can be passed as positional arguments as it follows

23
FUNCTIONS: KEYWORD ARGUMENTS
A function using keyword arguments needs to have the ** symbol as
last argument.

You can also pass a dict of keyword arguments using the symbol **
while calling the method

24
TRY IT YOURSELF!
Modify the print_hi function to accept a dict as an argument. Print:
• the first number squares, if number is greater than zero
• "Just a zero?!" if number is zero
• «Hi, my name is name», otherwise

def print_hi(**kwargs):
if kwargs["number"] > 0:
squares = [i**2 for i in range(0, kwargs["number"])]
for elem in squares:
print(elem)
elif kwargs["number"] == 0:
print("Just a zero?!")
else:
print("Hi, my name is " + kwargs["name"])

if __name__ == '__main__':
argv = dict(name="Luca", number=0)
print_hi(**argv)

25
CLASSES: METHODS
In python classes are defined with the class keyword. Class methods
are defined with the def keyword. Class method have the first
argument equal to self, in contrast with static method.

However, unless you want to use a decorator, Python does not know
about static/non-static methods, it is all about notation!

26
CLASSES: ATTRIBUTES
In python you can create, modify and retrieve instance attributes
using the dot (.) selector on the instance reference. You can create and
assign an instance attribute everywhere in a class method.

You can create class attributes specifying them after the class
declaration. You can modify and retrieve class attributes using the dot
(.) selector on the class reference

27
CLASSES: VISIBILITY
In python there is no such thing as a private method or attribute.
Everything is public. The naming convention for “private” methods
and attributes is to precede their name with the _ symbol.

28
CLASSES: CONSTRUCTOR
In python the construct function is named __init__ and it is called at
object instantiation.
You can specify one or more arguments. The first argument is the
object instance reference.

29
CLASSES: INHERITANCE
You can extend a base class with another specifying the base class
between the parenthesis at class definition. In order to get the base
class reference you need to use the super() function.

30
TRY IT YOURSELF!
Include the modified version of print_hi in the class Person, use the class attributes,
and derive the new class Student!

class Person: class Student(Person):


def __init__(self, name, number): def print_hi(self):
self.name = name print("I'm a student!")
self.number = number
if __name__ == '__main__':
def print_hi(self): p = Person("Luca", 0)
if self.number > 0: p.print_hi()
squares = [i**2 for i in range(0, self.number)] print(p.name)
for elem in squares:
print(elem) s = Student("Luca", -2)
elif self.number == 0: s.print_hi()
print("Just a zero?!") print(s.name)
else:
print("Hi, my name is " + self.name)

31
MORE ON CLASSES: DATA MODEL
The are a lot of built-in functions provided by the base class of all the
classes object. Each of which provide a specific behavior, a few are:
•__len__ (self)
Returns the “length” of the object (called by len())

•__str__ (self)
Returns the object as a string (called by str())

•__lt__ (self, other), __lt__ (self, other), __eq__ (self,other)


Called when the object is used in a comparison

•__getitem__ (self, key), __setitem__ (self, key, value)


Called in square brackets access

32
WORKING WITH EXISTING PROJECTS
Pycharm provides different functionalities for project and code
navigation.

Navigate the project with specialized project views, use shortcuts, jump
between files, classes, methods and usages.

You can create a Python project by opening a folder as a project or even


from scratch, by creating or importing the python files.

In this lecture we will not start from scratch…

33
OPEN A PROJECT

1. Unzip “simpleClassifier.rar”

2. Open the resulting folder “as a PyCharm


project”

34
ALTERNATIVE INTERPRETER CONFIGURATION
File > Settings > Project > Python interpreter > Show all

4
2

> Conda Environment > New environment


Location and conda executable may have slightly different paths (the first part) according
to your miniconda3 location.
6
5
Apply > Ok 7

8
35
PROJECT REQUIREMENTS 1/2
The requirements are all the packages that our software needs to run properly. Those
can be installed with a PyCharm plugin.
Double click on “requirements.txt” in the Project View > Install Plugin

Once the plugin is installed click on “Install requirements”, select all and click install.

36
PROJECT REQUIREMENTS 2/2
• If everything goes smoothly you might see the package installation status progress
at the bottom of the GUI.

• Once the package installation is done a notification appears, but it is still NOT
possible to go to next step, at least until PyCharm has finished "Updating
skeletons".

• Each package can also be installed via GUI or with the Terminal by using
• “pip install <name_lib>” to install a single package
• “pip install –r requirements.txt” to install the packages on the requirements.txt
37
CHECK THE PACKAGES AVAILABLE
It can take some minutes to complete the requirements installation. A restart may be
required before moving to the next step!
Once done you can see (add, eliminate and upgrade*) the packages and libraries
available in your virtual environment by checking :
File > Settings > Project > Python Interpreter

38
CONFIGURE THE FIRST RUN
1. Click “Add configuration” 3. Select “main.py” in your project folder.

2. Select “Python”

4. Click OK
39
RUN IT! Click RUN

Txt with evaluation score! The confusion matrix! 40


QUESTIONS?

41

You might also like