PYTHON
TRAINING
NADHIR BEDANI
2021
Just like all our trainings, this Python Training will
allow you to proudly add “Python” to your
resume.
This course is for beginners who want to reach a
professional level in merely no time.
We’ll go straight to the point
We’ll use real life examples
Let’s get it started!
NADHIR BEDANI
PYTHON
TRAINING
OVERVIEW
NADHIR BEDANI 2021
DAY 1
OVERVIEW
• DISCOVER
PYTHON
• INSTALL IT
• MASTER THE
BASICS
DAY 2
• DATA
STRUCTURES
• COMPARISON
OPERATORS
• STATEMENTS
DAY 3
• METHODS &
FUNCTIONS
• OBJECT
ORIENTED
PROGRAMMING
DAY 4
• MODULES &
PACKAGES
• WORK WITH
DATA
DAY 5
• ERROR
HANDLING
• GRAPHICAL
USER INTERFACE
Practical exercices everyday
DAY1
• Discover Python
• Install it
• Master the Basics
DAY1
“COMPUTERPROGRAMMINGFOREVERYBODY”
DISCOVERPYTHON
Python was created in 1999 by Guido Van Rossum
He described it as an easy and intuitive language just
as powerful as major competitors
It is Open Source so anyone can contribute to its
development
“PYTHONISPOPULAR”
DISCOVERPYTHON
Python never stopped gaining popularity since it was
created
Today more and more non-programmer jobs require
Python as a skill:
• Python Developer (of course)
• Product Manager
• Data Analyst
• Educator
• Financial Advisors
• Others
“PYTHONCANDOITALL”
DISCOVERPYTHON
• Website development
Web frameworks like Django and Flask allow for a quick
and slick website creation
• Data Science
Python is an excellent language for Machine Learning,
Data Analysis and Data Visualization
It allows to make sense of the huge amount of data we
face in all industries
• Automation
Who wants to perform repetitive tasks all day?
Python does: web crawling, data mining, email sending
Just to mention a few…
• Discover Python
• Install it
• Master the Basics
DAY1
“WE’LLINSTALLPYTHONANDALLYOUNEEDTOCODE”
INSTALLIT
We’ll use “Anaconda” to install Python and
other useful resources to code
Available for all platforms
• Go to anaconda.com/products/individual
• Download a graphical installer for your
platform
• Follow the instructions
Python 3 vs Python 2 ?
Long story short:
Always use latest stable version:
Python 3
BREAK
15’
• Discover Python
• Install it
• Master the Basics
DAY1
“STARTPYTHON”
MASTERTHEBASICS
We’ll launch the Python Shell (IDLE) to start coding:
IDLE = Integrated Development and Learning
Environment
Run a few commands and type “Enter” one after the
other
1+1
print(“hello world”)
print(“2+2”)
print(2+2)
a = 2
b = 2
print(a)
print(a+b)
The IDLE displays your code with
different colours: it helps with clarity
first_name = “Bruce”
last_name = “Wayne”
print(first_name)
print(first_name+last_name)
print(first_name + “ “ + last_name)
“CREATEASCRIPT”
MASTERTHEBASICS
In the IDLE, click “File” > “New File”
This opens the IDLE Editor where you can save your
code as a script
Write and save your first script:
print(“hello world”)
Press “F5” to run your script
Update your script with the previous commands
Python scripts file names end
with .py
“EXECUTEYOURSCRIPTFROMCOMMANDLINE”
MASTERTHEBASICS
Open the command line terminal “CMD” and start
Python by typing:
python3
From here you can try code like in the Python Shell
print(2+2)
print(“a”+”b”)
middle_name = input(“What is your middle name? “)
print(middle_name)
Leave the command line Python session with
exit()
Go to the directory where you script is saved
cd Documents/
cd Python Code/
Run
python3 my script.py
For simplicity sake: avoid spaces in
file names, use underscores
BREAK
15’
“NUMBERS”
MASTERTHEBASICS
From the Shell or the Editor
# Python easily handles big numbers
2+2
5465+3424536
568497643*246577988
# Usual Operations
1/2
10/2
3+3*3
(1+1)+(2*2)
# Integer divisions and remainder
2//5
10//3
10%3
# Python power
2**4
10**9 More complex Maths will require the
“Math” module we’ll see later
“#COMMENTS”
MASTERTHEBASICS
It is good practice to comment your code
Because
• you may be working in a team where people
should be able to understand your code
• you may be changing your code after vacation
and not remember what part does what
# This is a comment
# It will be ignored when executing the code
# The code below should output 4
2+2
You may use comments to disable some parts of
your code: useful when trying things out
Always leave a space after #:
# This is the way
“WORKINGWITHVARIABLES”
MASTERTHEBASICS
# Assign a value to a variable
country = “Germany”
print(country)
# Check type of a variable, could be Integer, String, Float, etc.
type(country)
# Concatenate variables
company = “Airbus”
print(company + “ “ + country)
# Combine variables
customer = company + “ in “ + country
print(customer)
# Combine Strings and Integers
employees = 150000
print(company + “ has “ + employees + “ workers”)
# Cast an Integer as a String using str()
print(company + “ has “ + str(employees) + “ workers”)
# Cast with int()
turnover = input(“What was Airbus turnover last Year? “)
margin = 10/100
profit = margin*turnover
print(“Last year’s profit was “ + profit)
Use TypeCasting carefully when
combining variables
DAY2
• Data Structures
• Comparison Operators
• Statements
DAY2
“DATATYPES”
DATASTRUCTURES
# Text:
str
# Numeric:
int
float
complex
# Sequence:
list
tuple
range
# Mapping (Dictionary):
dict
# Set:
set
frozenset
# Boolean:
bool
# Binary
bytes
bytearray
memoryview
Most variables will be
either:
str = “apple”
int = 89
float = 89.32
bool = true
“LIST”
DATASTRUCTURES
List is a [collection] of items
# Initialize the following lists
even_numbers = [2,4,6,8,10,12]
aircraft_types = [“A320”, “A330”, “A340”, “A350”]
# Get the 3rd even number in the list
even_numbers[?]
# Get the 4th Aircraft type?
# Get the last even number from the list
even_numbers[-1]
# Get a sublist of the first 4 even numbers
even_numbers[0:5]
First element of a list is at index 0
Perform operations on lists
joined_lists = even_numbers + aircraft_types
even_numbers = even_numbers + [14]
aircraft_types = aircraft_types + [“A380”]
even_numbers.append(16)
aircraft_types.append(“A220”)
del even_numbers[0]
aircraft_types.remove(“A380”)
aircraft_types.insert(3, ”A280”)
aircraft_types.pop(3)
“TUPLE”
DATASTRUCTURES
Use round (brackets) to create a tuple
# Initialize the following tuples
working_days = (“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”)
# Get he 3rd working day of the week
working_days[2]
# Let’s create a list of tuples like Aircraft type and the family they belong to
fleet = [(“A300”,”WB”), (“A320”,”SA”), (“A330”,”LR”), (“A380”,”LA”)]
# Which family does the A330 belong to?
# Unpacking tuples
(aircraft_type, aircraft_family) = fleet[1]
# What will it print?
print(aircraft_type)
print(aircraft_family)
Tuples are identical to Lists, only
they cannot be changed
“DICTIONARY”
DATASTRUCTURES
Use curly {brackets} to create a dictionary
# Initialize the following dictionaries of Team Managers
department_managers = {“ASFP1”: “Torsten”, “ASFP2”: “Michaela”, “ASFP3”: “Marco”, “ASFP4”: “Arnaud” }
# Who is manager of ASFP3?
department_managers[“ASFP3”]
# Add an entry to a dictionary like this
department_managers[“ASFP”] = “Antoine”
# Remove an entry using del
del department_managers[“XXXX”]
In a dictionary the key must be
unique
“STRING”
DATASTRUCTURES
Splitting Strings
# Initialize the following string
text = “Hamburg Copenhagen Dubai Washington”
# Turn the string into a list
cities = text.split(“ “)
# Turn the following string into a list
months = “Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec”
months_list = ?
# Turn the alphabet into a list (split() or list())
alphabet = “abcde”
alphabet_list = ?
Joining Strings
gathered_letters = “”.join(alphabet_list)
# Join months and separate them with a comma
months_string = ?
Remember who you are coding for:
Human beings :)
Formatting Strings
# Use .capitalize() and .title()
text = “the lord of the rings”
# Instead of
print(“This year’s “ + “turnover” + “ is: “ + str(45) + “ billions”)
# Use formatting
first_value = “turnover”
second_value = 45
print(“This year’s {} is: {} billions”.format(first_value, second_value)
# It works with lists as well, note the *
quarters_revenue = [188, 190, 195, 200]
print(“Revenue by quarter: Q1 = {} Q2 = {} Q3 = {} Q4 = {}”.format(*quarters_revenue))
# Decide what to show where using the index
print(“Q4 is {3} Q1 is {0} Q3 is {2} Q2 is {1}”.format(*quarters_revenue))
BREAK
15’
• Data Structures
• Comparison Operators
• Statements
DAY2
“DETAILSCOUNT”
COMPARISONOPERATORS
Comparing values is the base for all logic
> greater than
< less then
>= greater than or equal to
<= less than or equal to
!= not equal
== equal
Double equal == to compare
Single equal = to assign
“OTHERCHECKS”
COMPARISONOPERATORS
Identity operators:
“is” returns True if both variables are the same object
“is not” checks the opposite
Membership operators:
“in” returns True if right variable contains left variable
“not in” does the opposite
The result of these checks is a
Boolean
• Data Structures
• Comparison Operators
• Statements
DAY2
“CONDITIONS”
STATEMENTS
Conditions are checked with if: else:
# check if a is greater than b
(a,b) = (4,8)
if a > b:
print(“a is greater than b”)
elif a == b:
print(“they are equal”)
else:
print(“a is less than b”)
Note the tab spacing before the print, this
is called indentation
Identation is crucial in Python!
and do not forget the
:
“LOOPS”
STATEMENTS
For loops
# Using range
for i in range(1, 10):
print(i)
# Looping through a list
week_list = [“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”]
for day in week_list:
print(day)
While loops
# Always increment a counter inside a while loop
r = 1
while r < 10
print(r)
r = r + 1
Use break to stop a loop
# If needed
break
you don’t want to be
stuck in an infinite loop
“LOOPS”
STATEMENTS
For loops
# Using range
for i in range(1, 10):
print(i)
# Looping through a list
week_list = [“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”]
for day in week_list:
print(day)
While loops
# Always increment a counter inside a while loop
r = 1
while r < 10
print(r)
r = r + 1
Use break to stop a loop
# If needed
break
you don’t want to be
stuck in an infinite loop
“LOOPS”
STATEMENTS
For loops
# Using range
for i in range(1, 10):
print(i)
# Looping through a list
week_list = [“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”]
for day in week_list:
print(day)
While loops
# Always increment a counter inside a while loop
r = 1
while r < 10
print(r)
r = r + 1
Use break to stop a loop
# If needed
break
you don’t want to be
stuck in an infinite loop
BREAK
15’
“MAKEUSEOFWHATYOULEARNED”
STATEMENTS
1) Print multiplication table from 1 to 10
# Expected Output
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
2) Iterate on a list and display numbers
which are divisible by 5 and if you find
number greater than 150 stop the loop
iteration
# Example List
base_list = [11, 15, 33, 41, 55, 75, 128, 132, 150, 180, 205]
“USINGPYTHONFORREAL”
STATEMENTS
3) Modify the first item (20) of a list inside
a following tuple to 220
# Example tuple
tuple_example = (10, [20, 30], 40, 50)
4) Change your salary
# Sample Dictionary
sampleDict = {
'emp1': {'name': 'Michael', 'salary': 7500},
'emp2': {'name': 'Diana', 'salary': 8000},
'emp3': {'name': 'Holger', 'salary': 6500}
}
DAY3
• Methods & Functions
• Object oriented Programming
DAY3
“PYTHONFUNCTIONS”
METHODS&FUNCTIONS
A function is a piece of code that can be
called anywhere in your program
A method is the same, but in the context of
object oriented programming
How to recognise a function:
function_name(argument1, argument2,…)
# Examples you know
print()
list()
type()
https://docs.python.org/3/library/functions.html
Scan to see all Python built-in
functions
“DEFINEYOURCUSTOMFUNCTION”
METHODS&FUNCTIONS
Python allows you to create functions
#No parameters, no return value
def Hello1():
print(“Hello”)
#With parameters, no return value
def Hello2(friend)
print(“Hello {}”.format(friend))
#With parameters, with return value
def multiply(a,b)
result = a*b
return result
Write the vending_machine() function
It sells soda cans, chocolate snacks and coffee for 2$
BREAK
15’
“EXERCISES”
METHODS&FUNCTIONS
1) Write a function to sum all the numbers in a list
param_list = [1,4,42,18]
2) Write a function that takes a list and returns a new list
with unique elements of the first list
param_list2 = [1,2,3,3,3,4,5,5,5,5,6,7,7,7,8]
3) Write a function to calculate the factorial of a number (a
non-negative integer)
#Hint: recursivity
• Methods & Functions
• Object oriented Programming
DAY3
“AQUESTIONOFCLASS”
OBJECTORIENTEDPROGRAMMING
Object oriented programming is a paradigm,
“a way of doing things”
One class can have
many instances
Class Aircraft:
its attributes are
aircraft_type
passenger_capacity
engine_technology
its methods are
move
take_off
land
“CREATEACLASS”
OBJECTORIENTEDPROGRAMMING
Create an Aircraft class:
# Aircraft

Class Aircraft:

# Attributes

aircraft_type = “”

capacity = 0

technology = “”

# Instantiation

def __init__(self, aircraft_type, capacity, technology):

self. aircraft_type = aircraft_type

self.capacity = capacity

self.technology = technology

Instantiate some Aircrafts:
ac1 = Aircraft(“A320”,150,”NEO”)

ac2 = Aircraft(“A350”,250,”Rolls Royce”)

__init__() is a reserved Python function:
2 underscores on each side
“ADDMETHODS”
OBJECTORIENTEDPROGRAMMING
Add methods to Aircraft class:
# move, take_off, land
def move(self, direction):
if direction == “forward”:
return “moving forward”
elif …
else
def take_off(self):
…
def land(self):
…
“self” is always the first argument of
a method in a class
“INHERITANCE”
OBJECTORIENTEDPROGRAMMING
You can make a “child” class to get its “parent” class
attributes and methods
# parent class: use the existing Aircraft class
# create a child class
class AerobaticJet(Aircraft):
def __init__(self):
# call super() function
super().__init__()
print("Jet is ready")
def whoisThis(self):
print("Jet")
def looping(self):
print(“Jet is looping now")
def release_smoke(self, color):
print(“Releasing {} smoke“.format(color))
super() allows us to call methods
from the parent class
“ENCAPSULATION”
OBJECTORIENTEDPROGRAMMING
You can protect variables that belong to an object
class Aircraft:
def __init__(self):
self.__price = 200000000
def sell(self):
print("Sales Price: {}".format(self.__price))
def setPrice(self, price_value):
self.__price = price_value
ac = Aircraft()
Aircraft.sell()
# Change the price directly
ac.__price = 1000
ac.sell()
# Change using setter function
ac.setPrice(300000000)
ac.sell()
You can’t just push the aircraft tail to make it move
You’d have to command it from the cockpit
DAY4
• Modules & Packages
• Work with Data
DAY4
“THERE’SAMODULEFOREVERYTHING”
MODULES&PACKAGES
A Python module is a source file that contains code for
classes, functions and global variables
It extends the capabilities of Python by addressing specific
purposes
# Import a module using:
import ModuleName
# Import and give an alias
import ModuleName as m
# Call a function from a module with:
ModuleName.module_function(param1, param2,…)
# It is also possible to import like this
from ModuleName import functionXYZ A Package is a collection of Modules
“DATE&TIME”
MODULES&PACKAGES
Let’s work with dates and times
# Import the module
import datetime
# Print date and time
print(datetime.datetime.now())
# only time
print(datetime.datetime.now().time())
# Format a date like Wednesday 27 January 2021
from datetime import datetime
given_date = datetime(2021, 1, 27)
print("Given date is")
print(given_date.strftime('%A %d %B %Y'))
# Opearations on dates
from datetime import datetime, timedelta
days_difference = 7
new_date = given_date - timedelta(days=days_difference)
print("New Date")
print(new_date)
A Package is a collection of Modules
“MATH”
MODULES&PACKAGES
The Math Module
# Import the module
import math as m
# try these functions
sin()
floor()
ceil()
trunc()
exp()
factorial()
pow()
# try these constants:
pi
tau
e
Numpy is another module, like Math but
optimized for N-dimensions
“NUMPY”
MODULES&PACKAGES
NumPy adds support for large multidimensional arrays
# Import the module
import numpy as np
# Create an list versus an np array
list_quarter_revenue = [400,420,450,470] # “normal” list without NumPy
a_quarter_revenue = np.array([400,420,450,470]) # array using NumPy
# Initialize a multidimensional array
a_zero = np.zeros(2,5)
a_one = np.ones(2,4,6)
a_year = np.arange(12)
a_year = a_year(4,3)
# Get information about this array:
a_year.shape
a_year.ndim
a_year.dtype.name
a_year.size
type(a_year)
Operate high level mathematical functions on arrays
# Make months tart at 1
a_year = a_year +1
# Operations between np arrays
primes = np.array([2,3,5,7,11])
square_primes = primes**2
angles = 10*(np.arange(0,4)+1) # guess first
cosinus = np.cos(angles)
“NUMPYFIELDSOFAPPLICATION”
MODULES&PACKAGES
More on numpy.org
BREAK
15’
• Modules & Packages
• Work with Data
DAY4
“FILES”
WORKWITHDATA
Open files
# Python can open text files and binary files
# Locate or create a text file e.g. ending with .txt or .csv
example = open(“C:/Documents/file.txt”)
example.read() # wait and try again
print(example.read())
example.read(10)
example.readline() # wait and try again
lines = example.readlines()
lines[0]
lines[x]
Write to files
article = open(“C:/Documents/file2.txt”, “w”) # w for write mode
article.write(“This is History in the writing!”)
article.close()
article = open(“C:/Documents/file2.txt”, “a”) # a for append mode
article.write(“n”)
article.write(‘I’m adding a new line to the legend’)
today = dt.now() # write variable to text
article.write(“This book was written on {}”.format(today))
article.close()
CSV files are text files
Binary files can be images for example
“PANDAS”
WORKWITHDATA
You can assign a file’s content to an array or a dataframe
# Array
import numpy as np
t1 = np.genfromtxt(“C:/Documents/table.csv", delimiter=“,”)
# Dataframe
import pandas as pd
t2 = pd.read_csv(“C:/Documents/table.csv”, sep=“,”)
t2.head()
Pandas is useful when working with tabular data, such as
data stored in spreadsheets or databases
# Download: https://raw.githubusercontent.com/pandas-dev/pandas/master/doc/data/titanic.csv
“PANDASDATAFRAMES”
WORKWITHDATA
Working with Pandas
ferry = pd.read_csv("data/titanic.csv")
ferry.head()
# Select a subset (Column, Row, Subset)
fares = ferry[“Fare”]
type(fares)
class_fares = ferry[[“Pclass”, “Fare”]]
type(class_fares)
# Filter a dataframe: dfFiltered = dfOriginal[CONDITION]
youngsters = ferry[ferry[“Age”] < 26 ]
youngsters_of_third_class = ferry[( ferry[“Age”] < 26 & ferry[“Pclass”] == 3 )] #and &
women_and_children = ? # or |
# Other filter conditions
.isin([2,3])
.notna()
#Loc and iloc
adult_names = ferry.loc[ferry["Age"] >= 26, “Name"]
subset = ferry.iloc[9:20, 3:6]
“DATAANALYTICSBASICS”
WORKWITHDATA
Update Dataframes and create new columns
# Set a yearly price escalation of 10%
ferry[“New_Price”] = ferry[“Fare”] * 1.1
# Compute a ratio
ferry[“r1”] = ferry[“Age”] / ferry[“New_Price”]
# Rename Columns: use a dictionary as parameter
ferry2 = ferry.rename(
columns={
“Fare”: “ticket_price”,
“Age”: “years”,
}
)
# Compute Statistics
ferry[“New_Price”].mean()
ferry[[“Age”,”New_Price”]].median()
ferry[[“Age”,”New_Price”]].describe()
# Compute Aggregates
ferry.agg(
{
“Age”: [“min”, “max”, “median”, “skew”],
“New_Price”: [“min”, “max”, “median”, “mean”],
}
)
# Group By
ferry[["Pclass", “Fare”]].groupby(“Pclass").mean()
ferry.groupby(“Pclass”).mean()
ferry.groupby(“Pclass”)[“Age”].mean()
ferry.groupby([“Pclass”, “Sex”])[“Age”].mean()
ferry.groupby(“Pclass”)[“Pclass”].count()
ferry[“Pclass”].value_counts() # what’s the difference ?
# Sort the dataframe
ferry.sort_values(by=“Age")
ferry.sort_values(by=[“Pclass”, “Age”], ascending=False)
# Combine data from multiple dataframes
ferryS1 = ferry[“Pclass”]
ferryS2 = ferry[[“Age”,“Fare”]]
combo1 = pd.concat([ferryS1, ferryS2], axis=0)
# Join dataframes (like in SQL)
joindf = pd.merge(df1, df2, how="left", on=“key_collumn”)
joindf = pd.merge(df1, df2, how="left", left_on='key1', right_on=‘key2')
axis = 0
axis = 1
DAY5
• Error Handling
• Graphical User Interface
DAY5
“TOERRISHUMAN…”
ERRORHANDLING
Errors happen for several reasons, Python helps you anticipate
them using Exceptions and act accordingly.
# Do something crazy:
1/0
# Handle exceptions to prevent your code from crashing:
try:
a=int(input(“Enter the first number: “))
b=int(input(“Enter the second number: “)
print(a/b)
except ZeroDivisionError:
print(“Sorry, can’t divide by zero!”)
else:
print(“Operation performed successfully!”)
# Handle errors with files
try:
txt = open(“C:/Documents/textfile.txt”, “r”)
txt.write(“This is a test. Normal service will shortly resume!”)
except IOError:
print(“Error: unable to write the file. Check permissions”)
else:
print(“Content written to file successfully. Have a nice day.”)
txt.close() There are always some exceptions
# The try / finally clause
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can't find file or read data"
“WHATCANHAPPENWILLHAPPEN”
ERRORHANDLING
Python has plenty of exceptions and you can define your
own on top
# Raise your own exception:
raise Exception(“Someone tried to fly with a car”)
#
def flyWith( vehicle ):
if vehicle == “car”:
raise “Someone tried to fly with a car"
# The code below to this would not be executed
# if we raise the exception
else if vehicle == “bike”:
raise “Someone tried to fly with a bike”
else:
print(vehicle, “ is a good choice!”)
Exceptions prevent your program from
crashing when an error occurs
• Error Handling
• Graphical User Interface
DAY5
“IT’SALLABOUTTHEUSER”
GRAPHICALUSERINTERFACE
The GUI is what users will see when using your app:
windows, buttons, icons, displayed text, etc.
A good GUI will help your users navigate through your app
easily (not like in this picture)
Python has a great choice of modules to build GUIs:
• Tkinter
• wxPython
• PyQt
“TKINTER”
GRAPHICALUSERINTERFACE
Tkinter is the most commonly used GUI for Python
It is based on customizable visual elements called
“widgets”
• Frame: to provide a structure to your application
• Buttons: to gtake inputs from the user
• Checkbuttons: for selections
• Labels: to display text
• File Dialogs: to upload and download files
• Canvas: provides a space to draw things like graphs
“PYQT”
GRAPHICALUSERINTERFACE
PyQt5 is based on the Qt framework and it is fully cross-
platform: Windows, Mac, Linux, iOs, Android and more
The Qt library is popular among developpers and not just
for Python but many other languages.
Good to know: you will have access to the Qt Designer!
Orange: (Data Analysis) Openshot: (Video editor)
“WXPYTHON”
GRAPHICALUSERINTERFACE
WxPython looks more native than Tkinter and PyQt across
different operating systems. This is because it uses the
host system's widgets to construct a GUI.
It is less standard as it is not installed with Python by
default, so you’ll need to bundle it with your app
Dicompyler below is a radiation therapy
research platform:
DisplayCAL on the right
is a display calibration tool
BREAK
15’
“EXERCISEWITHTKINTER”
GRAPHICALUSERINTERFACE
Let’s create a gui with Tkinter
# Import Tkinter
import tkinter as tk
# A window is an instance of Tkinter’s Tk class
window = tk.Tk()
# Create a widget
hello = tk.Label(text=“Hello World")
# Add it to the window
hello.pack()
# Make your window ready to react
window.mainloop()
Let’s start with a window
Handle events
# Let’s rewrite the input in capital letters when the button is clicked, using “.upper()”
import tkinter as tk

window = tk.Tk()

def handle_button_clicked(event):

print("The button was clicked!”)

button = tk.Button(text="Click here!")

button.bind("<Button-1>", handle_button_clicked)

window.mainloop()

“EXERCISEWITHTKINTER”
GRAPHICALUSERINTERFACE
Working with widgets
# The label widget
label = tk.Label(
text=“Hello world",
fg="white",
bg="black",
width=15,
height=15
)
# In Tkinter, the width and height are based on the character “0”, that’s why you won’t get a square
button = tk.Button(
text="Click here!”,
width=30,
height=3,
bg="blue",
fg="white",
)
# Let’s get user input, we’ll give them a space for 50 characters
label = tk.Label(text=“What’s your name?”)
input = tk.Entry(fg="black", bg="white", width=50)
label.pack()
input.pack()
# Save the entry in a variable
name = input.get()
# Delete the entry:
input.delete(0)
input.delete(0,5)
input.delete(0,tk.END)
# Insert a value in the textfield:
input.insert(0, “Out of the blue”)
input.insert(0, “First of all. ”)
Make a simple form
if(you.interest(“Web development”):
print(“try out a web framework like flask or
django”)
elif(you.interest(“Data Analytics”):
print(“get the Udacity nanodegree for data
analytics”)
In any case, practice with tutorials about cool
things you’d like to do with Python
NADHIR BEDANI
YOUMADEIT.
CONGRATULATIONS!
WHERE TO GO NEXT?
ITWASPYTHON
TRAINING
BY LADONNEE CONSULTING
BOOK YOUR NEXT TRAINING WITH US ON: HTTPS://LADONNEE.COM
CREDITS
Image credits by page number:
1. karsten-winegeart-0Wra5YYVQJE-unsplash
2. amy-hirschi-W7aXY5F2pBo-unsplash
5. nicolas-hoizey--4trKf0Kbow-unsplash
6. Guido Von Rossum
7. https://stackoverflow.com
8. sorbetto-getty-images
9. nicolas-hoizey--4trKf0Kbow-unsplash
11. ryan-wilson-YdpDztAnW9w-unsplash / nathan-dumlao-Ic8RmXGyfNc-unsplash
12. nicolas-hoizey--4trKf0Kbow-unsplash
16. amelie-niklas-ohlrogge-Vnves2tovCs-unsplash / nathan-dumlao-6VhPY27jdps-unsplash
18. binh-dang-nam-bzK0qeeoBJo-unsplash
19. ashley-trethowan-UnuDkMptwZc-unsplash
21. the-bialons-UnVKGdXolwA-unsplash
22. markus-spiske-iar-afB0QQw-unsplash
24. jason-leung-d8uR-7ELKgI-unsplash
25. aaron-burden-fgmf2Eyrwm4-unsplash
26. yurii-stupen-I0yx_SKZXOw-unsplash
27. oliver-sjostrom-VxmT_MMlTfI-unsplash / nathan-dumlao-TBuuAE1lvqs-unsplash
28. the-bialons-UnVKGdXolwA-unsplash
29. roman-kraft-RtDwtRDvYQg-unsplash
30. randy-tarampi-fckhR4mysac-unsplash
31. the-bialons-UnVKGdXolwA-unsplash
32. jukan-tateisi-bJhT_8nbUA0-unsplash
33. ludde-lorentz-YfCVCPMNd38-unsplash
34. ludde-lorentz-YfCVCPMNd38-unsplash
35. ludde-lorentz-YfCVCPMNd38-unsplash
36. ryan-wilson-YdpDztAnW9w-unsplash / nathan-dumlao-Ic8RmXGyfNc-unsplash
37. christina-wocintechchat-com-YCrgxs3e9lY-unsplash
38. jeshoots-com--2vD8lIhdnw-unsplash
40. natali-quijano-N79MYsd2Ce4-unsplash
41. markus-spiske-sEkELvjksew-unsplash
42. markus-spiske-sEkELvjksew-unsplash
43. oliver-sjostrom-VxmT_MMlTfI-unsplash / nathan-dumlao-TBuuAE1lvqs-unsplash
44. max-larochelle-c-vWdiICscA-unsplash
45. natali-quijano-N79MYsd2Ce4-unsplash
46. swag-photography-A3haJzhr1Ec-unsplash
47. stephen-leonardi-XqAhfJz_KZU-unsplash
48. clay-banks-O5hfuVWgsS8-unsplash
49. richard-r-schunemann-lAJH-IKAo2s-unsplash
50. tyler-g-kmgOi9qqzbM-unsplash
52. elias-8QOpH6i3eQI-unsplash
53. history-in-hd-e5eDHbmHprg-unsplash
54. erik-witsoe-IXpuRZvhCT0-unsplash
55. science-in-hd-aYxQrt5J6jM-unsplash
56. chris-liverani-ViEBSoZH6M4-unsplash
57. https://numpy.org
58. ryan-wilson-YdpDztAnW9w-unsplash / nathan-dumlao-Ic8RmXGyfNc-unsplash
59. elias-8QOpH6i3eQI-unsplash
60. jeremy-zero-wpxr-qSDQJM-unsplash
61. max-titov-uDGezPIhZfU-unsplash
62. max-titov-uDGezPIhZfU-unsplash
65. shandell-venegas-QeNAJHpBFtk-unsplash
67. joseph-pearson-0emIdqhdUrk-unsplash
68. shandell-venegas-QeNAJHpBFtk-unsplash
73. ryan-wilson-YdpDztAnW9w-unsplash / nathan-dumlao-Ic8RmXGyfNc-unsplash
76. upal-patel-vaTKbTVFOM0-unsplash
77. bram-naus-oqnVnI5ixHg-unsplash

More Related Content

PDF
Scala in practice
PDF
ActiveRecord Query Interface (2), Season 2
PDF
DOCX
descriptive programming
PDF
Refactoring
PDF
Graphql, REST and Apollo
PDF
Nativescript angular
PPTX
Typed? Dynamic? Both! Cross-platform DSLs in C#
Scala in practice
ActiveRecord Query Interface (2), Season 2
descriptive programming
Refactoring
Graphql, REST and Apollo
Nativescript angular
Typed? Dynamic? Both! Cross-platform DSLs in C#

What's hot (20)

PPTX
Art of Javascript
PPTX
Database security
PDF
How to become an Android dev starting from iOS (and vice versa)
PDF
Integrating React.js with PHP projects
PPTX
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
PPTX
SPFx working with SharePoint data
PPTX
SPFx: Working with SharePoint Content
PDF
API first with Swagger and Scala by Slava Schmidt
PDF
PDF
The Ring programming language version 1.5.1 book - Part 13 of 180
PDF
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
PDF
An introduction to property-based testing
ODP
Session 2- day 3
PPTX
Java script
PDF
Pragmatic Real-World Scala (short version)
PDF
Angular 2 introduction
KEY
Why ruby
PDF
Software Language Design & Engineering
PDF
A evolução da persistência de dados (com sqlite) no android
KEY
Ruby/Rails
Art of Javascript
Database security
How to become an Android dev starting from iOS (and vice versa)
Integrating React.js with PHP projects
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
SPFx working with SharePoint data
SPFx: Working with SharePoint Content
API first with Swagger and Scala by Slava Schmidt
The Ring programming language version 1.5.1 book - Part 13 of 180
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
An introduction to property-based testing
Session 2- day 3
Java script
Pragmatic Real-World Scala (short version)
Angular 2 introduction
Why ruby
Software Language Design & Engineering
A evolução da persistência de dados (com sqlite) no android
Ruby/Rails
Ad

Similar to Python training for beginners (20)

PPTX
Python For Data Science.pptx
PDF
Python: An introduction A summer workshop
PDF
Python Part 1
PPTX
Integrating Python with SQL (12345).pptx
PPT
introduction to python in english presentation file
PPTX
Python PPT.pptx
PPT
Introduction to Python For Diploma Students
PPTX
1664611760basics-of-python-for begainer1 (3).pptx
PPTX
funadamentals of python programming language (right from scratch)
PPTX
Python Conditional and Looping statements.pptx
ODP
Introduction to Python3 Programming Language
PDF
CPPDS Slide.pdf
PPTX
Python-The programming Language
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
PPTX
Python chapter presentation details.pptx
DOCX
A Introduction Book of python For Beginners.docx
PDF
Introduction to python
PPTX
python_module_.................................................................
PDF
ppt_pspp.pdf
PPTX
Python Course for Beginners
Python For Data Science.pptx
Python: An introduction A summer workshop
Python Part 1
Integrating Python with SQL (12345).pptx
introduction to python in english presentation file
Python PPT.pptx
Introduction to Python For Diploma Students
1664611760basics-of-python-for begainer1 (3).pptx
funadamentals of python programming language (right from scratch)
Python Conditional and Looping statements.pptx
Introduction to Python3 Programming Language
CPPDS Slide.pdf
Python-The programming Language
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
Python chapter presentation details.pptx
A Introduction Book of python For Beginners.docx
Introduction to python
python_module_.................................................................
ppt_pspp.pdf
Python Course for Beginners
Ad

Recently uploaded (20)

PPTX
observCloud-Native Containerability and monitoring.pptx
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
Enhancing emotion recognition model for a student engagement use case through...
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
CloudStack 4.21: First Look Webinar slides
PPT
Geologic Time for studying geology for geologist
PPTX
Chapter 5: Probability Theory and Statistics
PDF
Getting Started with Data Integration: FME Form 101
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
Hindi spoken digit analysis for native and non-native speakers
PPTX
The various Industrial Revolutions .pptx
PDF
A review of recent deep learning applications in wood surface defect identifi...
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PPTX
Web Crawler for Trend Tracking Gen Z Insights.pptx
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
WOOl fibre morphology and structure.pdf for textiles
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PDF
A comparative study of natural language inference in Swahili using monolingua...
observCloud-Native Containerability and monitoring.pptx
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Enhancing emotion recognition model for a student engagement use case through...
O2C Customer Invoices to Receipt V15A.pptx
1 - Historical Antecedents, Social Consideration.pdf
CloudStack 4.21: First Look Webinar slides
Geologic Time for studying geology for geologist
Chapter 5: Probability Theory and Statistics
Getting Started with Data Integration: FME Form 101
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
Hindi spoken digit analysis for native and non-native speakers
The various Industrial Revolutions .pptx
A review of recent deep learning applications in wood surface defect identifi...
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
sustainability-14-14877-v2.pddhzftheheeeee
Web Crawler for Trend Tracking Gen Z Insights.pptx
Group 1 Presentation -Planning and Decision Making .pptx
WOOl fibre morphology and structure.pdf for textiles
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
A comparative study of natural language inference in Swahili using monolingua...

Python training for beginners

  • 2. Just like all our trainings, this Python Training will allow you to proudly add “Python” to your resume. This course is for beginners who want to reach a professional level in merely no time. We’ll go straight to the point We’ll use real life examples Let’s get it started! NADHIR BEDANI PYTHON TRAINING OVERVIEW
  • 3. NADHIR BEDANI 2021 DAY 1 OVERVIEW • DISCOVER PYTHON • INSTALL IT • MASTER THE BASICS DAY 2 • DATA STRUCTURES • COMPARISON OPERATORS • STATEMENTS DAY 3 • METHODS & FUNCTIONS • OBJECT ORIENTED PROGRAMMING DAY 4 • MODULES & PACKAGES • WORK WITH DATA DAY 5 • ERROR HANDLING • GRAPHICAL USER INTERFACE Practical exercices everyday
  • 5. • Discover Python • Install it • Master the Basics DAY1
  • 6. “COMPUTERPROGRAMMINGFOREVERYBODY” DISCOVERPYTHON Python was created in 1999 by Guido Van Rossum He described it as an easy and intuitive language just as powerful as major competitors It is Open Source so anyone can contribute to its development
  • 7. “PYTHONISPOPULAR” DISCOVERPYTHON Python never stopped gaining popularity since it was created Today more and more non-programmer jobs require Python as a skill: • Python Developer (of course) • Product Manager • Data Analyst • Educator • Financial Advisors • Others
  • 8. “PYTHONCANDOITALL” DISCOVERPYTHON • Website development Web frameworks like Django and Flask allow for a quick and slick website creation • Data Science Python is an excellent language for Machine Learning, Data Analysis and Data Visualization It allows to make sense of the huge amount of data we face in all industries • Automation Who wants to perform repetitive tasks all day? Python does: web crawling, data mining, email sending Just to mention a few…
  • 9. • Discover Python • Install it • Master the Basics DAY1
  • 10. “WE’LLINSTALLPYTHONANDALLYOUNEEDTOCODE” INSTALLIT We’ll use “Anaconda” to install Python and other useful resources to code Available for all platforms • Go to anaconda.com/products/individual • Download a graphical installer for your platform • Follow the instructions Python 3 vs Python 2 ? Long story short: Always use latest stable version: Python 3
  • 12. • Discover Python • Install it • Master the Basics DAY1
  • 13. “STARTPYTHON” MASTERTHEBASICS We’ll launch the Python Shell (IDLE) to start coding: IDLE = Integrated Development and Learning Environment Run a few commands and type “Enter” one after the other 1+1 print(“hello world”) print(“2+2”) print(2+2) a = 2 b = 2 print(a) print(a+b) The IDLE displays your code with different colours: it helps with clarity first_name = “Bruce” last_name = “Wayne” print(first_name) print(first_name+last_name) print(first_name + “ “ + last_name)
  • 14. “CREATEASCRIPT” MASTERTHEBASICS In the IDLE, click “File” > “New File” This opens the IDLE Editor where you can save your code as a script Write and save your first script: print(“hello world”) Press “F5” to run your script Update your script with the previous commands Python scripts file names end with .py
  • 15. “EXECUTEYOURSCRIPTFROMCOMMANDLINE” MASTERTHEBASICS Open the command line terminal “CMD” and start Python by typing: python3 From here you can try code like in the Python Shell print(2+2) print(“a”+”b”) middle_name = input(“What is your middle name? “) print(middle_name) Leave the command line Python session with exit() Go to the directory where you script is saved cd Documents/ cd Python Code/ Run python3 my script.py For simplicity sake: avoid spaces in file names, use underscores
  • 17. “NUMBERS” MASTERTHEBASICS From the Shell or the Editor # Python easily handles big numbers 2+2 5465+3424536 568497643*246577988 # Usual Operations 1/2 10/2 3+3*3 (1+1)+(2*2) # Integer divisions and remainder 2//5 10//3 10%3 # Python power 2**4 10**9 More complex Maths will require the “Math” module we’ll see later
  • 18. “#COMMENTS” MASTERTHEBASICS It is good practice to comment your code Because • you may be working in a team where people should be able to understand your code • you may be changing your code after vacation and not remember what part does what # This is a comment # It will be ignored when executing the code # The code below should output 4 2+2 You may use comments to disable some parts of your code: useful when trying things out Always leave a space after #: # This is the way
  • 19. “WORKINGWITHVARIABLES” MASTERTHEBASICS # Assign a value to a variable country = “Germany” print(country) # Check type of a variable, could be Integer, String, Float, etc. type(country) # Concatenate variables company = “Airbus” print(company + “ “ + country) # Combine variables customer = company + “ in “ + country print(customer) # Combine Strings and Integers employees = 150000 print(company + “ has “ + employees + “ workers”) # Cast an Integer as a String using str() print(company + “ has “ + str(employees) + “ workers”) # Cast with int() turnover = input(“What was Airbus turnover last Year? “) margin = 10/100 profit = margin*turnover print(“Last year’s profit was “ + profit) Use TypeCasting carefully when combining variables
  • 20. DAY2
  • 21. • Data Structures • Comparison Operators • Statements DAY2
  • 22. “DATATYPES” DATASTRUCTURES # Text: str # Numeric: int float complex # Sequence: list tuple range # Mapping (Dictionary): dict # Set: set frozenset # Boolean: bool # Binary bytes bytearray memoryview Most variables will be either: str = “apple” int = 89 float = 89.32 bool = true
  • 23. “LIST” DATASTRUCTURES List is a [collection] of items # Initialize the following lists even_numbers = [2,4,6,8,10,12] aircraft_types = [“A320”, “A330”, “A340”, “A350”] # Get the 3rd even number in the list even_numbers[?] # Get the 4th Aircraft type? # Get the last even number from the list even_numbers[-1] # Get a sublist of the first 4 even numbers even_numbers[0:5] First element of a list is at index 0 Perform operations on lists joined_lists = even_numbers + aircraft_types even_numbers = even_numbers + [14] aircraft_types = aircraft_types + [“A380”] even_numbers.append(16) aircraft_types.append(“A220”) del even_numbers[0] aircraft_types.remove(“A380”) aircraft_types.insert(3, ”A280”) aircraft_types.pop(3)
  • 24. “TUPLE” DATASTRUCTURES Use round (brackets) to create a tuple # Initialize the following tuples working_days = (“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”) # Get he 3rd working day of the week working_days[2] # Let’s create a list of tuples like Aircraft type and the family they belong to fleet = [(“A300”,”WB”), (“A320”,”SA”), (“A330”,”LR”), (“A380”,”LA”)] # Which family does the A330 belong to? # Unpacking tuples (aircraft_type, aircraft_family) = fleet[1] # What will it print? print(aircraft_type) print(aircraft_family) Tuples are identical to Lists, only they cannot be changed
  • 25. “DICTIONARY” DATASTRUCTURES Use curly {brackets} to create a dictionary # Initialize the following dictionaries of Team Managers department_managers = {“ASFP1”: “Torsten”, “ASFP2”: “Michaela”, “ASFP3”: “Marco”, “ASFP4”: “Arnaud” } # Who is manager of ASFP3? department_managers[“ASFP3”] # Add an entry to a dictionary like this department_managers[“ASFP”] = “Antoine” # Remove an entry using del del department_managers[“XXXX”] In a dictionary the key must be unique
  • 26. “STRING” DATASTRUCTURES Splitting Strings # Initialize the following string text = “Hamburg Copenhagen Dubai Washington” # Turn the string into a list cities = text.split(“ “) # Turn the following string into a list months = “Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec” months_list = ? # Turn the alphabet into a list (split() or list()) alphabet = “abcde” alphabet_list = ? Joining Strings gathered_letters = “”.join(alphabet_list) # Join months and separate them with a comma months_string = ? Remember who you are coding for: Human beings :) Formatting Strings # Use .capitalize() and .title() text = “the lord of the rings” # Instead of print(“This year’s “ + “turnover” + “ is: “ + str(45) + “ billions”) # Use formatting first_value = “turnover” second_value = 45 print(“This year’s {} is: {} billions”.format(first_value, second_value) # It works with lists as well, note the * quarters_revenue = [188, 190, 195, 200] print(“Revenue by quarter: Q1 = {} Q2 = {} Q3 = {} Q4 = {}”.format(*quarters_revenue)) # Decide what to show where using the index print(“Q4 is {3} Q1 is {0} Q3 is {2} Q2 is {1}”.format(*quarters_revenue))
  • 28. • Data Structures • Comparison Operators • Statements DAY2
  • 29. “DETAILSCOUNT” COMPARISONOPERATORS Comparing values is the base for all logic > greater than < less then >= greater than or equal to <= less than or equal to != not equal == equal Double equal == to compare Single equal = to assign
  • 30. “OTHERCHECKS” COMPARISONOPERATORS Identity operators: “is” returns True if both variables are the same object “is not” checks the opposite Membership operators: “in” returns True if right variable contains left variable “not in” does the opposite The result of these checks is a Boolean
  • 31. • Data Structures • Comparison Operators • Statements DAY2
  • 32. “CONDITIONS” STATEMENTS Conditions are checked with if: else: # check if a is greater than b (a,b) = (4,8) if a > b: print(“a is greater than b”) elif a == b: print(“they are equal”) else: print(“a is less than b”) Note the tab spacing before the print, this is called indentation Identation is crucial in Python! and do not forget the :
  • 33. “LOOPS” STATEMENTS For loops # Using range for i in range(1, 10): print(i) # Looping through a list week_list = [“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”] for day in week_list: print(day) While loops # Always increment a counter inside a while loop r = 1 while r < 10 print(r) r = r + 1 Use break to stop a loop # If needed break you don’t want to be stuck in an infinite loop
  • 34. “LOOPS” STATEMENTS For loops # Using range for i in range(1, 10): print(i) # Looping through a list week_list = [“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”] for day in week_list: print(day) While loops # Always increment a counter inside a while loop r = 1 while r < 10 print(r) r = r + 1 Use break to stop a loop # If needed break you don’t want to be stuck in an infinite loop
  • 35. “LOOPS” STATEMENTS For loops # Using range for i in range(1, 10): print(i) # Looping through a list week_list = [“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”] for day in week_list: print(day) While loops # Always increment a counter inside a while loop r = 1 while r < 10 print(r) r = r + 1 Use break to stop a loop # If needed break you don’t want to be stuck in an infinite loop
  • 37. “MAKEUSEOFWHATYOULEARNED” STATEMENTS 1) Print multiplication table from 1 to 10 # Expected Output 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100 2) Iterate on a list and display numbers which are divisible by 5 and if you find number greater than 150 stop the loop iteration # Example List base_list = [11, 15, 33, 41, 55, 75, 128, 132, 150, 180, 205]
  • 38. “USINGPYTHONFORREAL” STATEMENTS 3) Modify the first item (20) of a list inside a following tuple to 220 # Example tuple tuple_example = (10, [20, 30], 40, 50) 4) Change your salary # Sample Dictionary sampleDict = { 'emp1': {'name': 'Michael', 'salary': 7500}, 'emp2': {'name': 'Diana', 'salary': 8000}, 'emp3': {'name': 'Holger', 'salary': 6500} }
  • 39. DAY3
  • 40. • Methods & Functions • Object oriented Programming DAY3
  • 41. “PYTHONFUNCTIONS” METHODS&FUNCTIONS A function is a piece of code that can be called anywhere in your program A method is the same, but in the context of object oriented programming How to recognise a function: function_name(argument1, argument2,…) # Examples you know print() list() type() https://docs.python.org/3/library/functions.html Scan to see all Python built-in functions
  • 42. “DEFINEYOURCUSTOMFUNCTION” METHODS&FUNCTIONS Python allows you to create functions #No parameters, no return value def Hello1(): print(“Hello”) #With parameters, no return value def Hello2(friend) print(“Hello {}”.format(friend)) #With parameters, with return value def multiply(a,b) result = a*b return result Write the vending_machine() function It sells soda cans, chocolate snacks and coffee for 2$
  • 44. “EXERCISES” METHODS&FUNCTIONS 1) Write a function to sum all the numbers in a list param_list = [1,4,42,18] 2) Write a function that takes a list and returns a new list with unique elements of the first list param_list2 = [1,2,3,3,3,4,5,5,5,5,6,7,7,7,8] 3) Write a function to calculate the factorial of a number (a non-negative integer) #Hint: recursivity
  • 45. • Methods & Functions • Object oriented Programming DAY3
  • 46. “AQUESTIONOFCLASS” OBJECTORIENTEDPROGRAMMING Object oriented programming is a paradigm, “a way of doing things” One class can have many instances Class Aircraft: its attributes are aircraft_type passenger_capacity engine_technology its methods are move take_off land
  • 47. “CREATEACLASS” OBJECTORIENTEDPROGRAMMING Create an Aircraft class: # Aircraft Class Aircraft: # Attributes aircraft_type = “” capacity = 0 technology = “” # Instantiation def __init__(self, aircraft_type, capacity, technology): self. aircraft_type = aircraft_type self.capacity = capacity self.technology = technology Instantiate some Aircrafts: ac1 = Aircraft(“A320”,150,”NEO”) ac2 = Aircraft(“A350”,250,”Rolls Royce”) __init__() is a reserved Python function: 2 underscores on each side
  • 48. “ADDMETHODS” OBJECTORIENTEDPROGRAMMING Add methods to Aircraft class: # move, take_off, land def move(self, direction): if direction == “forward”: return “moving forward” elif … else def take_off(self): … def land(self): … “self” is always the first argument of a method in a class
  • 49. “INHERITANCE” OBJECTORIENTEDPROGRAMMING You can make a “child” class to get its “parent” class attributes and methods # parent class: use the existing Aircraft class # create a child class class AerobaticJet(Aircraft): def __init__(self): # call super() function super().__init__() print("Jet is ready") def whoisThis(self): print("Jet") def looping(self): print(“Jet is looping now") def release_smoke(self, color): print(“Releasing {} smoke“.format(color)) super() allows us to call methods from the parent class
  • 50. “ENCAPSULATION” OBJECTORIENTEDPROGRAMMING You can protect variables that belong to an object class Aircraft: def __init__(self): self.__price = 200000000 def sell(self): print("Sales Price: {}".format(self.__price)) def setPrice(self, price_value): self.__price = price_value ac = Aircraft() Aircraft.sell() # Change the price directly ac.__price = 1000 ac.sell() # Change using setter function ac.setPrice(300000000) ac.sell() You can’t just push the aircraft tail to make it move You’d have to command it from the cockpit
  • 51. DAY4
  • 52. • Modules & Packages • Work with Data DAY4
  • 53. “THERE’SAMODULEFOREVERYTHING” MODULES&PACKAGES A Python module is a source file that contains code for classes, functions and global variables It extends the capabilities of Python by addressing specific purposes # Import a module using: import ModuleName # Import and give an alias import ModuleName as m # Call a function from a module with: ModuleName.module_function(param1, param2,…) # It is also possible to import like this from ModuleName import functionXYZ A Package is a collection of Modules
  • 54. “DATE&TIME” MODULES&PACKAGES Let’s work with dates and times # Import the module import datetime # Print date and time print(datetime.datetime.now()) # only time print(datetime.datetime.now().time()) # Format a date like Wednesday 27 January 2021 from datetime import datetime given_date = datetime(2021, 1, 27) print("Given date is") print(given_date.strftime('%A %d %B %Y')) # Opearations on dates from datetime import datetime, timedelta days_difference = 7 new_date = given_date - timedelta(days=days_difference) print("New Date") print(new_date) A Package is a collection of Modules
  • 55. “MATH” MODULES&PACKAGES The Math Module # Import the module import math as m # try these functions sin() floor() ceil() trunc() exp() factorial() pow() # try these constants: pi tau e Numpy is another module, like Math but optimized for N-dimensions
  • 56. “NUMPY” MODULES&PACKAGES NumPy adds support for large multidimensional arrays # Import the module import numpy as np # Create an list versus an np array list_quarter_revenue = [400,420,450,470] # “normal” list without NumPy a_quarter_revenue = np.array([400,420,450,470]) # array using NumPy # Initialize a multidimensional array a_zero = np.zeros(2,5) a_one = np.ones(2,4,6) a_year = np.arange(12) a_year = a_year(4,3) # Get information about this array: a_year.shape a_year.ndim a_year.dtype.name a_year.size type(a_year) Operate high level mathematical functions on arrays # Make months tart at 1 a_year = a_year +1 # Operations between np arrays primes = np.array([2,3,5,7,11]) square_primes = primes**2 angles = 10*(np.arange(0,4)+1) # guess first cosinus = np.cos(angles)
  • 59. • Modules & Packages • Work with Data DAY4
  • 60. “FILES” WORKWITHDATA Open files # Python can open text files and binary files # Locate or create a text file e.g. ending with .txt or .csv example = open(“C:/Documents/file.txt”) example.read() # wait and try again print(example.read()) example.read(10) example.readline() # wait and try again lines = example.readlines() lines[0] lines[x] Write to files article = open(“C:/Documents/file2.txt”, “w”) # w for write mode article.write(“This is History in the writing!”) article.close() article = open(“C:/Documents/file2.txt”, “a”) # a for append mode article.write(“n”) article.write(‘I’m adding a new line to the legend’) today = dt.now() # write variable to text article.write(“This book was written on {}”.format(today)) article.close() CSV files are text files Binary files can be images for example
  • 61. “PANDAS” WORKWITHDATA You can assign a file’s content to an array or a dataframe # Array import numpy as np t1 = np.genfromtxt(“C:/Documents/table.csv", delimiter=“,”) # Dataframe import pandas as pd t2 = pd.read_csv(“C:/Documents/table.csv”, sep=“,”) t2.head() Pandas is useful when working with tabular data, such as data stored in spreadsheets or databases # Download: https://raw.githubusercontent.com/pandas-dev/pandas/master/doc/data/titanic.csv
  • 62. “PANDASDATAFRAMES” WORKWITHDATA Working with Pandas ferry = pd.read_csv("data/titanic.csv") ferry.head() # Select a subset (Column, Row, Subset) fares = ferry[“Fare”] type(fares) class_fares = ferry[[“Pclass”, “Fare”]] type(class_fares) # Filter a dataframe: dfFiltered = dfOriginal[CONDITION] youngsters = ferry[ferry[“Age”] < 26 ] youngsters_of_third_class = ferry[( ferry[“Age”] < 26 & ferry[“Pclass”] == 3 )] #and & women_and_children = ? # or | # Other filter conditions .isin([2,3]) .notna() #Loc and iloc adult_names = ferry.loc[ferry["Age"] >= 26, “Name"] subset = ferry.iloc[9:20, 3:6]
  • 63. “DATAANALYTICSBASICS” WORKWITHDATA Update Dataframes and create new columns # Set a yearly price escalation of 10% ferry[“New_Price”] = ferry[“Fare”] * 1.1 # Compute a ratio ferry[“r1”] = ferry[“Age”] / ferry[“New_Price”] # Rename Columns: use a dictionary as parameter ferry2 = ferry.rename( columns={ “Fare”: “ticket_price”, “Age”: “years”, } ) # Compute Statistics ferry[“New_Price”].mean() ferry[[“Age”,”New_Price”]].median() ferry[[“Age”,”New_Price”]].describe() # Compute Aggregates ferry.agg( { “Age”: [“min”, “max”, “median”, “skew”], “New_Price”: [“min”, “max”, “median”, “mean”], } ) # Group By ferry[["Pclass", “Fare”]].groupby(“Pclass").mean() ferry.groupby(“Pclass”).mean() ferry.groupby(“Pclass”)[“Age”].mean() ferry.groupby([“Pclass”, “Sex”])[“Age”].mean() ferry.groupby(“Pclass”)[“Pclass”].count() ferry[“Pclass”].value_counts() # what’s the difference ? # Sort the dataframe ferry.sort_values(by=“Age") ferry.sort_values(by=[“Pclass”, “Age”], ascending=False) # Combine data from multiple dataframes ferryS1 = ferry[“Pclass”] ferryS2 = ferry[[“Age”,“Fare”]] combo1 = pd.concat([ferryS1, ferryS2], axis=0) # Join dataframes (like in SQL) joindf = pd.merge(df1, df2, how="left", on=“key_collumn”) joindf = pd.merge(df1, df2, how="left", left_on='key1', right_on=‘key2') axis = 0 axis = 1
  • 64. DAY5
  • 65. • Error Handling • Graphical User Interface DAY5
  • 66. “TOERRISHUMAN…” ERRORHANDLING Errors happen for several reasons, Python helps you anticipate them using Exceptions and act accordingly. # Do something crazy: 1/0 # Handle exceptions to prevent your code from crashing: try: a=int(input(“Enter the first number: “)) b=int(input(“Enter the second number: “) print(a/b) except ZeroDivisionError: print(“Sorry, can’t divide by zero!”) else: print(“Operation performed successfully!”) # Handle errors with files try: txt = open(“C:/Documents/textfile.txt”, “r”) txt.write(“This is a test. Normal service will shortly resume!”) except IOError: print(“Error: unable to write the file. Check permissions”) else: print(“Content written to file successfully. Have a nice day.”) txt.close() There are always some exceptions # The try / finally clause try: fh = open("testfile", "w") try: fh.write("This is my test file for exception handling!!") finally: print "Going to close the file" fh.close() except IOError: print "Error: can't find file or read data"
  • 67. “WHATCANHAPPENWILLHAPPEN” ERRORHANDLING Python has plenty of exceptions and you can define your own on top # Raise your own exception: raise Exception(“Someone tried to fly with a car”) # def flyWith( vehicle ): if vehicle == “car”: raise “Someone tried to fly with a car" # The code below to this would not be executed # if we raise the exception else if vehicle == “bike”: raise “Someone tried to fly with a bike” else: print(vehicle, “ is a good choice!”) Exceptions prevent your program from crashing when an error occurs
  • 68. • Error Handling • Graphical User Interface DAY5
  • 69. “IT’SALLABOUTTHEUSER” GRAPHICALUSERINTERFACE The GUI is what users will see when using your app: windows, buttons, icons, displayed text, etc. A good GUI will help your users navigate through your app easily (not like in this picture) Python has a great choice of modules to build GUIs: • Tkinter • wxPython • PyQt
  • 70. “TKINTER” GRAPHICALUSERINTERFACE Tkinter is the most commonly used GUI for Python It is based on customizable visual elements called “widgets” • Frame: to provide a structure to your application • Buttons: to gtake inputs from the user • Checkbuttons: for selections • Labels: to display text • File Dialogs: to upload and download files • Canvas: provides a space to draw things like graphs
  • 71. “PYQT” GRAPHICALUSERINTERFACE PyQt5 is based on the Qt framework and it is fully cross- platform: Windows, Mac, Linux, iOs, Android and more The Qt library is popular among developpers and not just for Python but many other languages. Good to know: you will have access to the Qt Designer! Orange: (Data Analysis) Openshot: (Video editor)
  • 72. “WXPYTHON” GRAPHICALUSERINTERFACE WxPython looks more native than Tkinter and PyQt across different operating systems. This is because it uses the host system's widgets to construct a GUI. It is less standard as it is not installed with Python by default, so you’ll need to bundle it with your app Dicompyler below is a radiation therapy research platform: DisplayCAL on the right is a display calibration tool
  • 74. “EXERCISEWITHTKINTER” GRAPHICALUSERINTERFACE Let’s create a gui with Tkinter # Import Tkinter import tkinter as tk # A window is an instance of Tkinter’s Tk class window = tk.Tk() # Create a widget hello = tk.Label(text=“Hello World") # Add it to the window hello.pack() # Make your window ready to react window.mainloop() Let’s start with a window
  • 75. Handle events # Let’s rewrite the input in capital letters when the button is clicked, using “.upper()” import tkinter as tk window = tk.Tk() def handle_button_clicked(event): print("The button was clicked!”) button = tk.Button(text="Click here!") button.bind("<Button-1>", handle_button_clicked) window.mainloop() “EXERCISEWITHTKINTER” GRAPHICALUSERINTERFACE Working with widgets # The label widget label = tk.Label( text=“Hello world", fg="white", bg="black", width=15, height=15 ) # In Tkinter, the width and height are based on the character “0”, that’s why you won’t get a square button = tk.Button( text="Click here!”, width=30, height=3, bg="blue", fg="white", ) # Let’s get user input, we’ll give them a space for 50 characters label = tk.Label(text=“What’s your name?”) input = tk.Entry(fg="black", bg="white", width=50) label.pack() input.pack() # Save the entry in a variable name = input.get() # Delete the entry: input.delete(0) input.delete(0,5) input.delete(0,tk.END) # Insert a value in the textfield: input.insert(0, “Out of the blue”) input.insert(0, “First of all. ”) Make a simple form
  • 76. if(you.interest(“Web development”): print(“try out a web framework like flask or django”) elif(you.interest(“Data Analytics”): print(“get the Udacity nanodegree for data analytics”) In any case, practice with tutorials about cool things you’d like to do with Python NADHIR BEDANI YOUMADEIT. CONGRATULATIONS! WHERE TO GO NEXT?
  • 77. ITWASPYTHON TRAINING BY LADONNEE CONSULTING BOOK YOUR NEXT TRAINING WITH US ON: HTTPS://LADONNEE.COM
  • 78. CREDITS Image credits by page number: 1. karsten-winegeart-0Wra5YYVQJE-unsplash 2. amy-hirschi-W7aXY5F2pBo-unsplash 5. nicolas-hoizey--4trKf0Kbow-unsplash 6. Guido Von Rossum 7. https://stackoverflow.com 8. sorbetto-getty-images 9. nicolas-hoizey--4trKf0Kbow-unsplash 11. ryan-wilson-YdpDztAnW9w-unsplash / nathan-dumlao-Ic8RmXGyfNc-unsplash 12. nicolas-hoizey--4trKf0Kbow-unsplash 16. amelie-niklas-ohlrogge-Vnves2tovCs-unsplash / nathan-dumlao-6VhPY27jdps-unsplash 18. binh-dang-nam-bzK0qeeoBJo-unsplash 19. ashley-trethowan-UnuDkMptwZc-unsplash 21. the-bialons-UnVKGdXolwA-unsplash 22. markus-spiske-iar-afB0QQw-unsplash 24. jason-leung-d8uR-7ELKgI-unsplash 25. aaron-burden-fgmf2Eyrwm4-unsplash 26. yurii-stupen-I0yx_SKZXOw-unsplash 27. oliver-sjostrom-VxmT_MMlTfI-unsplash / nathan-dumlao-TBuuAE1lvqs-unsplash 28. the-bialons-UnVKGdXolwA-unsplash 29. roman-kraft-RtDwtRDvYQg-unsplash 30. randy-tarampi-fckhR4mysac-unsplash 31. the-bialons-UnVKGdXolwA-unsplash 32. jukan-tateisi-bJhT_8nbUA0-unsplash 33. ludde-lorentz-YfCVCPMNd38-unsplash 34. ludde-lorentz-YfCVCPMNd38-unsplash 35. ludde-lorentz-YfCVCPMNd38-unsplash 36. ryan-wilson-YdpDztAnW9w-unsplash / nathan-dumlao-Ic8RmXGyfNc-unsplash 37. christina-wocintechchat-com-YCrgxs3e9lY-unsplash 38. jeshoots-com--2vD8lIhdnw-unsplash 40. natali-quijano-N79MYsd2Ce4-unsplash 41. markus-spiske-sEkELvjksew-unsplash 42. markus-spiske-sEkELvjksew-unsplash 43. oliver-sjostrom-VxmT_MMlTfI-unsplash / nathan-dumlao-TBuuAE1lvqs-unsplash 44. max-larochelle-c-vWdiICscA-unsplash 45. natali-quijano-N79MYsd2Ce4-unsplash 46. swag-photography-A3haJzhr1Ec-unsplash 47. stephen-leonardi-XqAhfJz_KZU-unsplash 48. clay-banks-O5hfuVWgsS8-unsplash 49. richard-r-schunemann-lAJH-IKAo2s-unsplash 50. tyler-g-kmgOi9qqzbM-unsplash 52. elias-8QOpH6i3eQI-unsplash 53. history-in-hd-e5eDHbmHprg-unsplash 54. erik-witsoe-IXpuRZvhCT0-unsplash 55. science-in-hd-aYxQrt5J6jM-unsplash 56. chris-liverani-ViEBSoZH6M4-unsplash 57. https://numpy.org 58. ryan-wilson-YdpDztAnW9w-unsplash / nathan-dumlao-Ic8RmXGyfNc-unsplash 59. elias-8QOpH6i3eQI-unsplash 60. jeremy-zero-wpxr-qSDQJM-unsplash 61. max-titov-uDGezPIhZfU-unsplash 62. max-titov-uDGezPIhZfU-unsplash 65. shandell-venegas-QeNAJHpBFtk-unsplash 67. joseph-pearson-0emIdqhdUrk-unsplash 68. shandell-venegas-QeNAJHpBFtk-unsplash 73. ryan-wilson-YdpDztAnW9w-unsplash / nathan-dumlao-Ic8RmXGyfNc-unsplash 76. upal-patel-vaTKbTVFOM0-unsplash 77. bram-naus-oqnVnI5ixHg-unsplash