SlideShare a Scribd company logo
Introduction to the basics of
Python programming
(PART 2)
by Pedro Rodrigues (pedro@startacareerwithpython.com)
A little about me
{
“Name”: “Pedro Rodrigues”,
“Origin”: {“Country”: “Angola”, “City”: “Luanda”},
“Lives”: [“Netherlands”, 2013],
“Past”: [“CTO”, “Senior Backend Engineer”],
“Present”: [“Freelance Software Engineer”, “Coach”],
“Other”: [“Book author”, “Start a Career with Python”]
}
Why this Meetup Group?
 Promote the usage of Python
 Gather people from different industries and backgrounds
 Teach and Learn
What will be covered
 List and Dictionary comprehensions
 Functions
 Positional arguments
 Keyword arguments
 Default parameter values
 Variable number of arguments
 Names, namespaces and scope
A little recap
 Python is an interpreted language (CPython is the reference interpreter)
 Variables are names bound to objects stored in memory
 Data Types: immutable or mutable
 Data Types: Numbers (int, float, bool), Sequences (str, tuple, list, bytes, bytearray),
set, dict
 Control Flow: if statement, for loop, while loop
 Indentation determines whether a statement belongs to a code block or not
 Iterables are container objects capable of returning their elements one at a time
 Iterators implement the methods __iter__ and __next__
List comprehensions
 Concise way to create lists
 Each element is a the result of a transformation applied to the original element
 Regular way of building lists:
new_list = []
for elem in some_sequence:
new_list.append(do_something(elem))
 With list comprehension:
new_list = [do_something(elem) for elem in some_sequence]
List comprehensions (examples)
names = ["John", "Mary", "Russell", "Devon", "Elizabeth"]
new_names = []
for name in names:
if len(name) > 4:
new_names.append(name)
>>> names = ["John", "Mary", "Russell", "Devon", "Elizabeth"]
>>> new_names = [name for name in names if len(name) > 4]
>>> new_names
['Russell', 'Devon', 'Elizabeth']
List comprehensions (examples)
pairs = []
for i in range(3):
for j in range(3):
if i != j:
pairs.append((i, j))
>>> pairs = [(i, j) for i in range(3) for j in range(3) if i != j]
>>> pairs
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
List comprehensions (challenge)
 Use split and sorted to print a sorted list of strings read from the standard input. Use a
list comprehension for build a list where the strings are in lowercase.
 Strings in the standard input are separated by commas (no spaces)
 Sample input: THIs,is,A,strING,WITH,COMmas
 Sample output: ['a', 'commas', 'is', 'string', 'this', 'with']
>>> "Hello,World,how,are,you".split(",")
['Hello', 'World', 'how', 'are', 'you']
>>> sorted(["b", "z", "a", "c", "l"])
['a', 'b', 'c', 'l', 'z']
Dictionary comprehensions
 Concise way to create dictionaries
 Keys and/or Values are the result of applying transformations to elements in the original sequence
 Regular way of building a dictionary:
d = {}
for k, v in some_seq:
key = do_something(k)
value = do_something(v)
d[key] = value
 With dict comprehension:
d = {do_something(k): do_something(v) for k, v in some_seq}
Dictionary comprehensions (examples)
d = {}
for i in range(2, 11, 2):
d[i] = i**2
d = {i: i**2 for i in range(2, 11, 2)}
>>> d
{8: 64, 2: 4, 4: 16, 10: 100, 6: 36}
Dictionary comprehensions (examples)
# example: name=Pedro age=34
info = input("> ")
info_list = [item.split("=") for item in info.split(" ")]
info_dict = {}
for k, v in info_list:
key = k.capitalize()
d[key] = v
>>> info_dict
{'Age': '34', 'Name': 'Pedro'}
Dictionary comprehensions (examples)
# With dict comprehension
>>> info = input("> ")
>>> d = {k.capitalize(): v for k, v in [item.split("=") for item in info.split(" ")]}
>>> d
{'Age': '34', 'Name': 'Pedro'}
Dictionary comprehensions (challenge)
 Build a dictionary where the keys are in lowercase and the values are integers,
from a string read from the standard input
 Sample input: John=28 Martha=32 Stewart=46 Peter=30
 Sample output:
{'stewart': 46, 'peter': 30, 'john': 28, 'martha': 32}
Functions
 Callable data type
 Control Flow construct
def function_name(params_list):
suite
def print_hello_world():
print("Hello")
print("World")
Positional arguments
def function_name(param1, param2, ...):
# do something with param1 and/or param2
>>> function_name(arg1, arg2)
Positional arguments (examples)
def sum_squares(x, y):
return x**2 + y**2
>>> sum_squares(2, 3)
13
>>> numbers = [2, 3]
>>> sum_squares(*numbers)
13
>>> sum_squares(*[2, 3])
13
Challenge
 Read coordinates from standard input and print the distance between the two points.
Use list comprehension and sequence unpacking.
 Define a function that takes 4 integers (x1, y1, x2, y2) and returns the distance between
two points: Point 1 (x1, y1), Point 2 (x2, y2).
 (𝑥2 − 𝑥1)2+(𝑦2 − 𝑦1)2
>>> import math
>>> math.sqrt(16)
4.0
 Sample input: 1 3 7 4
 Sample output: 6.082762530298219
Challenge
 Sample input: 1 3 7 4
 Sample output: 6.082762530298219
def distance(x1, y1, x2, y2):
...
# coordinates = [1, 3, 7, 4]
>>> print(distance(*coordinates)) # coordinates is a list
>>> 6.082762530298219
Keyword arguments
 The order of the arguments doesn’t matter
def sum_squares(x, y):
return x**2 + y**2
>>> sum_squares(y=3, x=2)
13
 You cannot have a positional argument after a keyword argument
>>> sum_squares(y=3, 2)
Keyword arguments (examples)
def sum_squares(x, y):
return x**2 + y**2
>>> numbers = {"x": 2, "y": 3}
>>> sum_squares(**numbers)
13
>>> sum_squares(**{"x": 2, "y": 3})
13
Default parameter values
 For parameters with default value, the corresponding argument can be omitted
def sum_squares(x, y=3):
return x**2 + y**2
>>> sum_squares(2)
13
 After the first parameter with default value, all other parameters must have default
value
# Wrong!
def sum_squares(x=2, y):
return x**2 + y**2
Default parameter values
 Be careful with mutable default values!
names = ["John", "Louise"]
def print_hello(n=names):
for name in n:
print("Hello, ", name)
names.append("Something")
>>> print_hello()
Hello, John
Hello, Louise
>>> names
['John', 'Louise', 'Something']
Variable number of arguments
def function_name(*args, **kwargs):
pass
 args is initialized as a tuple with positional arguments
 kwargs is initialized as a dictionary with keyword arguments
 The words args and kwargs are just a convention, they are not reserved in
Python.
Variable number of arguments (examples)
def sum_squares(*args):
if len(args) == 2:
return args[0]**2 + args[1]**2
else:
return args
>>> sum_squares(4, 5) # args = (4, 5)
41
>>> sum_squares(6, "Hello", 7) # args = (6, "Hello", 7)
(6, "Hello", 7)
Variable number of arguments (examples)
def sum_squares(x, *args):
if len(args) == 1:
return x**2 + args[0]**2
else:
return args
>>> sum_squares(4, 5) # args = (5,)
41
>>> sum_squares(6, "Hello", 7) # args = ("Hello", 7)
("Hello", 7)
Variable number of arguments (examples)
def distance(x1, y1, x2, y2):
return math.sqrt((int(x2)-int(x1))**2 + (int(y2)-int(y1))**2)
def calculate_distance(**kwargs):
if len(kwargs) == 4:
return distance(**kwargs)
else:
return kwargs
Variable number of arguments (examples)
# kwargs = {"x1": 1, "y1": 3, "x2": 7, "y2": 4}
>>> calculate_distance(x1=1, y1=3, x2=7, y2=4)
6.082762530298219
Challenge
 Sample input: x1=1 y1=3 x2=7 y2=4, x1=13 y1=10 x2=109 y2=45
 Sample output:
6.082762530298219
102.18121158021175
 Use dict comprehension and unpack the dictionary in distance.
Names, Namespaces and Scope
 Namespace: place where the binding between names and objects are stored.
 Different namespaces: built-in, global module namespace, local namespace for
a function, objects namespace.
 Scope is a text region that determines whether a namespace is available or not.
 Scope influences name resolution.
Names, Namespaces and Scope
 Global module namespace
x = 10
print(x)
 Local namespace of a function
x = 10
def print_x():
x = 5
print(x) # prints 5
Names, Namespaces and Scope
 Local namespace of a function
x = 10
def print_x():
print(x) # prints 10
Names, Namespaces and Scope
 People coming from other languages, beware of for loops!
>>> for i in range(3):
... print(i)
...
0
1
2
>>> print(i)
2
Names, Namespaces and Scope
 Namespaces have different life times:
 Local namespace is created when a function is called and destroyed when the function
returns.
 Global module namespace is created when the module definition is read in.
 Built-in namespace is created when the interpreter starts and is never destroyed during
the program execution.
 Global namespace of a function is the global namespace of the module where the
function was defined.
Reading material
 List comprehensions: https://docs.python.org/3.5/tutorial/datastructures.html#list-
comprehensions
 Dict comprehensions:
https://docs.python.org/3.5/tutorial/datastructures.html#dictionaries
 Functions and parameters:
https://docs.python.org/3.5/reference/compound_stmts.html#function-definitions
 Names, Namespaces and Scopes:
https://docs.python.org/3.5/tutorial/classes.html#a-word-about-names-and-
objects
More resources
 Python Tutorial: https://docs.python.org/3/tutorial/index.html
 Python Language Reference: https://docs.python.org/3/reference/index.html
 Slack channel: https://startcareerpython.slack.com/
 Start a Career with Python newsletter: https://www.startacareerwithpython.com/
 Book: Start a Career with Python
 Book 15% off (NZ6SZFBL): https://www.createspace.com/6506874

More Related Content

What's hot (20)

Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutes
Sidharth Nadhan
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
Paige Bailey
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
Bayu Aldi Yansyah
 
Python Cheat Sheet
Python Cheat SheetPython Cheat Sheet
Python Cheat Sheet
Muthu Vinayagam
 
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEFUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
Narong Intiruk
 
python codes
python codespython codes
python codes
tusharpanda88
 
Python dictionary : past, present, future
Python dictionary: past, present, futurePython dictionary: past, present, future
Python dictionary : past, present, future
delimitry
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
Sumit Raj
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge
O T
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
Emertxe Information Technologies Pvt Ltd
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
Luigi De Russis
 
Functions in python
Functions in pythonFunctions in python
Functions in python
Ilian Iliev
 
Python and sysadmin I
Python and sysadmin IPython and sysadmin I
Python and sysadmin I
Guixing Bai
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutes
Sidharth Nadhan
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
Paige Bailey
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
Bayu Aldi Yansyah
 
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEFUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
Python dictionary : past, present, future
Python dictionary: past, present, futurePython dictionary: past, present, future
Python dictionary : past, present, future
delimitry
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
Sumit Raj
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge
O T
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
Luigi De Russis
 
Functions in python
Functions in pythonFunctions in python
Functions in python
Ilian Iliev
 
Python and sysadmin I
Python and sysadmin IPython and sysadmin I
Python and sysadmin I
Guixing Bai
 

Similar to Basics of Python programming (part 2) (20)

Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Becoming a Pythonist
Becoming a PythonistBecoming a Pythonist
Becoming a Pythonist
Raji Engg
 
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
Python Cheatsheet_A Quick Reference Guide for Data Science.pdfPython Cheatsheet_A Quick Reference Guide for Data Science.pdf
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)
Christopher Roach
 
Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
Python
PythonPython
Python
Vishal Sancheti
 
Python basic
Python basic Python basic
Python basic
sewoo lee
 
python language programming presentation
python language  programming presentationpython language  programming presentation
python language programming presentation
lbisht2
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
Raghu nath
 
PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-
Yoshiki Satotani
 
Dictionaries in Python programming language
Dictionaries in Python programming languageDictionaries in Python programming language
Dictionaries in Python programming language
ssuserbad56d
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
decoupled
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
Aleksandar Veselinovic
 
C# programming
C# programming C# programming
C# programming
umesh patil
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
BAINIDA
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
UC San Diego
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Becoming a Pythonist
Becoming a PythonistBecoming a Pythonist
Becoming a Pythonist
Raji Engg
 
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
Python Cheatsheet_A Quick Reference Guide for Data Science.pdfPython Cheatsheet_A Quick Reference Guide for Data Science.pdf
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)
Christopher Roach
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
Python basic
Python basic Python basic
Python basic
sewoo lee
 
python language programming presentation
python language  programming presentationpython language  programming presentation
python language programming presentation
lbisht2
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
Raghu nath
 
PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-
Yoshiki Satotani
 
Dictionaries in Python programming language
Dictionaries in Python programming languageDictionaries in Python programming language
Dictionaries in Python programming language
ssuserbad56d
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
decoupled
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
BAINIDA
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
UC San Diego
 
Ad

Recently uploaded (20)

How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Ad

Basics of Python programming (part 2)

  • 1. Introduction to the basics of Python programming (PART 2) by Pedro Rodrigues ([email protected])
  • 2. A little about me { “Name”: “Pedro Rodrigues”, “Origin”: {“Country”: “Angola”, “City”: “Luanda”}, “Lives”: [“Netherlands”, 2013], “Past”: [“CTO”, “Senior Backend Engineer”], “Present”: [“Freelance Software Engineer”, “Coach”], “Other”: [“Book author”, “Start a Career with Python”] }
  • 3. Why this Meetup Group?  Promote the usage of Python  Gather people from different industries and backgrounds  Teach and Learn
  • 4. What will be covered  List and Dictionary comprehensions  Functions  Positional arguments  Keyword arguments  Default parameter values  Variable number of arguments  Names, namespaces and scope
  • 5. A little recap  Python is an interpreted language (CPython is the reference interpreter)  Variables are names bound to objects stored in memory  Data Types: immutable or mutable  Data Types: Numbers (int, float, bool), Sequences (str, tuple, list, bytes, bytearray), set, dict  Control Flow: if statement, for loop, while loop  Indentation determines whether a statement belongs to a code block or not  Iterables are container objects capable of returning their elements one at a time  Iterators implement the methods __iter__ and __next__
  • 6. List comprehensions  Concise way to create lists  Each element is a the result of a transformation applied to the original element  Regular way of building lists: new_list = [] for elem in some_sequence: new_list.append(do_something(elem))  With list comprehension: new_list = [do_something(elem) for elem in some_sequence]
  • 7. List comprehensions (examples) names = ["John", "Mary", "Russell", "Devon", "Elizabeth"] new_names = [] for name in names: if len(name) > 4: new_names.append(name) >>> names = ["John", "Mary", "Russell", "Devon", "Elizabeth"] >>> new_names = [name for name in names if len(name) > 4] >>> new_names ['Russell', 'Devon', 'Elizabeth']
  • 8. List comprehensions (examples) pairs = [] for i in range(3): for j in range(3): if i != j: pairs.append((i, j)) >>> pairs = [(i, j) for i in range(3) for j in range(3) if i != j] >>> pairs [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
  • 9. List comprehensions (challenge)  Use split and sorted to print a sorted list of strings read from the standard input. Use a list comprehension for build a list where the strings are in lowercase.  Strings in the standard input are separated by commas (no spaces)  Sample input: THIs,is,A,strING,WITH,COMmas  Sample output: ['a', 'commas', 'is', 'string', 'this', 'with'] >>> "Hello,World,how,are,you".split(",") ['Hello', 'World', 'how', 'are', 'you'] >>> sorted(["b", "z", "a", "c", "l"]) ['a', 'b', 'c', 'l', 'z']
  • 10. Dictionary comprehensions  Concise way to create dictionaries  Keys and/or Values are the result of applying transformations to elements in the original sequence  Regular way of building a dictionary: d = {} for k, v in some_seq: key = do_something(k) value = do_something(v) d[key] = value  With dict comprehension: d = {do_something(k): do_something(v) for k, v in some_seq}
  • 11. Dictionary comprehensions (examples) d = {} for i in range(2, 11, 2): d[i] = i**2 d = {i: i**2 for i in range(2, 11, 2)} >>> d {8: 64, 2: 4, 4: 16, 10: 100, 6: 36}
  • 12. Dictionary comprehensions (examples) # example: name=Pedro age=34 info = input("> ") info_list = [item.split("=") for item in info.split(" ")] info_dict = {} for k, v in info_list: key = k.capitalize() d[key] = v >>> info_dict {'Age': '34', 'Name': 'Pedro'}
  • 13. Dictionary comprehensions (examples) # With dict comprehension >>> info = input("> ") >>> d = {k.capitalize(): v for k, v in [item.split("=") for item in info.split(" ")]} >>> d {'Age': '34', 'Name': 'Pedro'}
  • 14. Dictionary comprehensions (challenge)  Build a dictionary where the keys are in lowercase and the values are integers, from a string read from the standard input  Sample input: John=28 Martha=32 Stewart=46 Peter=30  Sample output: {'stewart': 46, 'peter': 30, 'john': 28, 'martha': 32}
  • 15. Functions  Callable data type  Control Flow construct def function_name(params_list): suite def print_hello_world(): print("Hello") print("World")
  • 16. Positional arguments def function_name(param1, param2, ...): # do something with param1 and/or param2 >>> function_name(arg1, arg2)
  • 17. Positional arguments (examples) def sum_squares(x, y): return x**2 + y**2 >>> sum_squares(2, 3) 13 >>> numbers = [2, 3] >>> sum_squares(*numbers) 13 >>> sum_squares(*[2, 3]) 13
  • 18. Challenge  Read coordinates from standard input and print the distance between the two points. Use list comprehension and sequence unpacking.  Define a function that takes 4 integers (x1, y1, x2, y2) and returns the distance between two points: Point 1 (x1, y1), Point 2 (x2, y2).  (𝑥2 − 𝑥1)2+(𝑦2 − 𝑦1)2 >>> import math >>> math.sqrt(16) 4.0  Sample input: 1 3 7 4  Sample output: 6.082762530298219
  • 19. Challenge  Sample input: 1 3 7 4  Sample output: 6.082762530298219 def distance(x1, y1, x2, y2): ... # coordinates = [1, 3, 7, 4] >>> print(distance(*coordinates)) # coordinates is a list >>> 6.082762530298219
  • 20. Keyword arguments  The order of the arguments doesn’t matter def sum_squares(x, y): return x**2 + y**2 >>> sum_squares(y=3, x=2) 13  You cannot have a positional argument after a keyword argument >>> sum_squares(y=3, 2)
  • 21. Keyword arguments (examples) def sum_squares(x, y): return x**2 + y**2 >>> numbers = {"x": 2, "y": 3} >>> sum_squares(**numbers) 13 >>> sum_squares(**{"x": 2, "y": 3}) 13
  • 22. Default parameter values  For parameters with default value, the corresponding argument can be omitted def sum_squares(x, y=3): return x**2 + y**2 >>> sum_squares(2) 13  After the first parameter with default value, all other parameters must have default value # Wrong! def sum_squares(x=2, y): return x**2 + y**2
  • 23. Default parameter values  Be careful with mutable default values! names = ["John", "Louise"] def print_hello(n=names): for name in n: print("Hello, ", name) names.append("Something") >>> print_hello() Hello, John Hello, Louise >>> names ['John', 'Louise', 'Something']
  • 24. Variable number of arguments def function_name(*args, **kwargs): pass  args is initialized as a tuple with positional arguments  kwargs is initialized as a dictionary with keyword arguments  The words args and kwargs are just a convention, they are not reserved in Python.
  • 25. Variable number of arguments (examples) def sum_squares(*args): if len(args) == 2: return args[0]**2 + args[1]**2 else: return args >>> sum_squares(4, 5) # args = (4, 5) 41 >>> sum_squares(6, "Hello", 7) # args = (6, "Hello", 7) (6, "Hello", 7)
  • 26. Variable number of arguments (examples) def sum_squares(x, *args): if len(args) == 1: return x**2 + args[0]**2 else: return args >>> sum_squares(4, 5) # args = (5,) 41 >>> sum_squares(6, "Hello", 7) # args = ("Hello", 7) ("Hello", 7)
  • 27. Variable number of arguments (examples) def distance(x1, y1, x2, y2): return math.sqrt((int(x2)-int(x1))**2 + (int(y2)-int(y1))**2) def calculate_distance(**kwargs): if len(kwargs) == 4: return distance(**kwargs) else: return kwargs
  • 28. Variable number of arguments (examples) # kwargs = {"x1": 1, "y1": 3, "x2": 7, "y2": 4} >>> calculate_distance(x1=1, y1=3, x2=7, y2=4) 6.082762530298219
  • 29. Challenge  Sample input: x1=1 y1=3 x2=7 y2=4, x1=13 y1=10 x2=109 y2=45  Sample output: 6.082762530298219 102.18121158021175  Use dict comprehension and unpack the dictionary in distance.
  • 30. Names, Namespaces and Scope  Namespace: place where the binding between names and objects are stored.  Different namespaces: built-in, global module namespace, local namespace for a function, objects namespace.  Scope is a text region that determines whether a namespace is available or not.  Scope influences name resolution.
  • 31. Names, Namespaces and Scope  Global module namespace x = 10 print(x)  Local namespace of a function x = 10 def print_x(): x = 5 print(x) # prints 5
  • 32. Names, Namespaces and Scope  Local namespace of a function x = 10 def print_x(): print(x) # prints 10
  • 33. Names, Namespaces and Scope  People coming from other languages, beware of for loops! >>> for i in range(3): ... print(i) ... 0 1 2 >>> print(i) 2
  • 34. Names, Namespaces and Scope  Namespaces have different life times:  Local namespace is created when a function is called and destroyed when the function returns.  Global module namespace is created when the module definition is read in.  Built-in namespace is created when the interpreter starts and is never destroyed during the program execution.  Global namespace of a function is the global namespace of the module where the function was defined.
  • 35. Reading material  List comprehensions: https://docs.python.org/3.5/tutorial/datastructures.html#list- comprehensions  Dict comprehensions: https://docs.python.org/3.5/tutorial/datastructures.html#dictionaries  Functions and parameters: https://docs.python.org/3.5/reference/compound_stmts.html#function-definitions  Names, Namespaces and Scopes: https://docs.python.org/3.5/tutorial/classes.html#a-word-about-names-and- objects
  • 36. More resources  Python Tutorial: https://docs.python.org/3/tutorial/index.html  Python Language Reference: https://docs.python.org/3/reference/index.html  Slack channel: https://startcareerpython.slack.com/  Start a Career with Python newsletter: https://www.startacareerwithpython.com/  Book: Start a Career with Python  Book 15% off (NZ6SZFBL): https://www.createspace.com/6506874

Editor's Notes

  • #3: I speak a bit fast, but don’t worry because the presentation will be available online, as well as a Slack channel.
  • #12: Note that the keys are not ordered, which is normal. If you depend on the order of the keys, use OrderedDict instead.