SlideShare a Scribd company logo
Introduction to the basics of
Python programming
(PART 3)
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
 Recap of Parts 1 and 2
 import, Modules and Packages
 Python in action
 Note: get the code here:
https://dl.dropboxusercontent.com/u/10346356/session3.zip
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
 Iterables are container objects capable of returning their elements one at a time
 Iterators implement the methods __iter__ and __next__
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
 Iterables are container objects capable of returning their elements one at a time
 Iterators implement the methods __iter__ and __next__
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
 Iterables are container objects capable of returning their elements one at a time
 Iterators implement the methods __iter__ and __next__
A little recap
>>> 2 + 2
4
>>> 4 / 2
2.0
>>> 4 > 2
True
>>> x = 1, 2
>>> x
(1, 2)
A little recap
>>> x = [1, 2]
>>> x
[1, 2]
>>> x = {1, 2}
>>> x
{1, 2}
>>> x = {"one": 1, "two": 2}
>>> x
{'two': 2, 'one': 1}
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
 Iterables are container objects capable of returning their elements one at a time
 Iterators implement the methods __iter__ and __next__
A little recap
if x % 3 == 0 and x % 5 == 0:
return "FizzBuzz"
elif x % 3 == 0:
return "Fizz"
elif x % 5 == 0:
return "Buzz"
else:
return x
A little recap
colors = ["red", "green", "blue", "yellow", "purple"]
for color in colors:
if len(color) > 4:
print(color)
stack = [1, 2, 3]
while len(stack) > 0:
print(stack.pop())
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
 Iterables are container objects capable of returning their elements one at a time
 Iterators implement the methods __iter__ and __next__
A little recap
>>> colors = ["red", "green", "blue", "yellow", "purple"]
>>> colors_iter = colors.__iter__()
>>> colors_iter
<list_iterator object at 0x100c7a160>
>>> colors_iter.__next__()
'red'
…
>>> colors_iter.__next__()
'purple'
>>> colors_iter.__next__()
Traceback (most recent call last): File "<stdin>", line 1, in
<module>
StopIteration
A little recap
colors = [(0, "red"), (1, "blue"), (2, "green"), (3, "yellow")]
for index, color in colors:
print(index, " --> ", color)
colors = ["red", "blue", "green", "yellow", "purple"]
for index, color in enumerate(colors):
print(index, " --> ", color)
A little recap
 List comprehensions
 Dictionary comprehensions
 Functions
 Positional Arguments
 Keyword Arguments
 Default parameters
 Variable number of arguments
A little recap
colors = ["red", "green", "blue", "yellow", "purple"]
new_colors = []
for color in colors:
if len(color) > 4:
new_colors.append(color)
new_colors = [color for color in colors if len(color) > 4]
Challenge
 Given a list of colors, create a new list with all the colors in uppercase. Use list
comprehensions.
colors = ["red", "green", "blue", "yellow", "purple"]
upper_colors = []
for color in colors:
upper_colors.append(color.upper())
A little recap
 List comprehensions
 Dictionary comprehensions
 Functions
 Positional Arguments
 Keyword Arguments
 Default parameters
 Variable number of arguments
A little recap
squares = {}
for i in range(10):
squares[i] = i**2
squares = {i:i**2 for i in range(10)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9:
81}
Challenge
 Given a list of colors, create a dictionary where each key is a color and the value is
the color written backwards. Use dict comprehensions.
colors = ["red", "green", "blue", "yellow", "purple"]
backwards_colors = {}
for color in colors:
backwards_colors[color] = color[::-1]
A little recap
 List comprehensions
 Dictionary comprehensions
 Functions
 Positional Arguments
 Keyword Arguments
 Default parameters
 Variable number of arguments
A little recap
def say_hello():
print("Hello")
def add_squares(a, b):
return a**2 + b**2
>>> add_squares(2, 3)
13
def add_squares(a, b=3):
return a**2 + b**2
>>> add_squares(2)
13
A little recap
def add_squares(a, b):
return a**2 + b**2
>>> add_squares(b=3, a=2)
13
A little recap
def add_aquares(*args):
if len(args) == 2:
return args[0]**2 + args[1]**2
>>> add_squares(2, 3)
13
A little recap
def add_squares(**kwargs):
if len(kwargs) == 2:
return kwargs["a"]**2 + kwargs["b"]**2
>>> add_squares(a=2, b=3)
13
Challenge
 Define a function that turns a string into a list of int (operands) and strings (operators) and returns
the list.
>>> _convert_expression("4 3 +")
[4, 3, "+"]
>>> _convert_expression("4 3 + 2 *")
[4, 3, "+", 2, "*"]
 Hints:
 “a b”.split(“ “) = [“a”, “b”]
 “a”.isnumeric() = False
 int(“2”) = 2
 Kudos for who solves in one line using lambdas and list comprehensions.
Challenge
 RPN = Reverse Polish Notation
 4 3 + (7)
 4 3 + 2 * (14)
 Extend RPN calculator to support the operators *, / and sqrt (from math module).
import math
print(math.sqrt(4))
Modules and Packages
 A module is a file with definitions and statements
 It’s named after the file.
 Modules are imported with import statement
 import <module>
 from <module> import <name1>
 from <module> import <name1>, <name2>
 import <module> as <new_module_name>
 from <module> import <name1> as <new_name1>
 from <module> import *
Modules and Packages
 A package is a directory with a special file __init__.py (the file can be empty, and
it’s also not mandatory to exist)
 The file __init__.py is executed when importing a package.
 Packages can contain other packages.
Modules and Packages
api/
__init__.py
rest.py
server.py
services/
__init__.py
rpn.py
hello.py
$ python -m api.server
Modules and Packages
 import api
 from api import rest
 import api.services.rpn
 from api.services.hello import say_hello
Challenge
 Extend functionalities of the RESTful API:
 Add a handler for http://localhost:8080/calculate
 This handler should accept only the POST method.
 Put all the pieces together in the rpn module.
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 (19)

PPTX
Python
Gagandeep Nanda
 
PPT
Introduction to Python - Part Three
amiable_indian
 
PDF
Matlab and Python: Basic Operations
Wai Nwe Tun
 
PPTX
Programming in Python
Tiji Thomas
 
PPTX
Python-The programming Language
Rohan Gupta
 
PPTX
Python for Beginners(v1)
Panimalar Engineering College
 
PPTX
Python Datatypes by SujithKumar
Sujith Kumar
 
PDF
Python
대갑 김
 
PPTX
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
PDF
AmI 2015 - Python basics
Luigi De Russis
 
PPT
python.ppt
shreyas_test_1234
 
PDF
Python basic
Saifuddin Kaijar
 
PPSX
Programming with Python
Rasan Samarasinghe
 
PPTX
Learn python in 20 minutes
Sidharth Nadhan
 
PDF
An introduction to Python for absolute beginners
Kálmán "KAMI" Szalai
 
PPTX
Learn Python The Hard Way Presentation
Amira ElSharkawy
 
PPT
Python
Kumar Gaurav
 
PPTX
Python basics
Hoang Nguyen
 
Introduction to Python - Part Three
amiable_indian
 
Matlab and Python: Basic Operations
Wai Nwe Tun
 
Programming in Python
Tiji Thomas
 
Python-The programming Language
Rohan Gupta
 
Python for Beginners(v1)
Panimalar Engineering College
 
Python Datatypes by SujithKumar
Sujith Kumar
 
Python
대갑 김
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
AmI 2015 - Python basics
Luigi De Russis
 
python.ppt
shreyas_test_1234
 
Python basic
Saifuddin Kaijar
 
Programming with Python
Rasan Samarasinghe
 
Learn python in 20 minutes
Sidharth Nadhan
 
An introduction to Python for absolute beginners
Kálmán "KAMI" Szalai
 
Learn Python The Hard Way Presentation
Amira ElSharkawy
 
Python
Kumar Gaurav
 
Python basics
Hoang Nguyen
 

Viewers also liked (12)

PDF
Python教程 / Python tutorial
ee0703
 
PDF
Python tutorial
Vijay Chaitanya
 
PDF
Introduction to python 3
Youhei Sakurai
 
PPTX
Python 3 Programming Language
Tahani Al-Manie
 
PDF
Multithreading 101
Tim Penhey
 
PDF
Python Intro
Tim Penhey
 
PPTX
Python Tutorial Part 1
Haitham El-Ghareeb
 
PPTX
Python Programming Language
Laxman Puri
 
PPTX
Python Tutorial Part 2
Haitham El-Ghareeb
 
PPT
Introduction to Python
amiable_indian
 
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
PPT
Introduction to Python
Nowell Strite
 
Python教程 / Python tutorial
ee0703
 
Python tutorial
Vijay Chaitanya
 
Introduction to python 3
Youhei Sakurai
 
Python 3 Programming Language
Tahani Al-Manie
 
Multithreading 101
Tim Penhey
 
Python Intro
Tim Penhey
 
Python Tutorial Part 1
Haitham El-Ghareeb
 
Python Programming Language
Laxman Puri
 
Python Tutorial Part 2
Haitham El-Ghareeb
 
Introduction to Python
amiable_indian
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
Introduction to Python
Nowell Strite
 
Ad

Similar to Introduction to the basics of Python programming (part 3) (20)

PPTX
Python Training
TIB Academy
 
PDF
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Mohamed Abdallah
 
PPTX
introductionpart1-160906115340 (1).pptx
AsthaChaurasia4
 
PPTX
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
PPT
python language programming presentation
lbisht2
 
PPTX
Practical Python.pptx Practical Python.pptx
trwdcn
 
PDF
python.pdf
wekarep985
 
PDF
A tour of Python
Aleksandar Veselinovic
 
PDF
An overview of Python 2.7
decoupled
 
PDF
Python Usage (5-minute-summary)
Ohgyun Ahn
 
PDF
Python lecture 05
Tanwir Zaman
 
PDF
Intro to Python
OSU Open Source Lab
 
PPTX
python introductions2 to basics programmin.pptx
annacarson387
 
PDF
Talk Code
Agiliq Solutions
 
PDF
Python Part 1
Mohamed Ramadan
 
PPTX
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
PPT
Python tutorialfeb152012
Shani729
 
PDF
Python Cheat Sheet
Muthu Vinayagam
 
PDF
Intermediate python
NaphtaliOchonogor1
 
PDF
Introduction to python
Ahmed Salama
 
Python Training
TIB Academy
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Mohamed Abdallah
 
introductionpart1-160906115340 (1).pptx
AsthaChaurasia4
 
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
python language programming presentation
lbisht2
 
Practical Python.pptx Practical Python.pptx
trwdcn
 
python.pdf
wekarep985
 
A tour of Python
Aleksandar Veselinovic
 
An overview of Python 2.7
decoupled
 
Python Usage (5-minute-summary)
Ohgyun Ahn
 
Python lecture 05
Tanwir Zaman
 
Intro to Python
OSU Open Source Lab
 
python introductions2 to basics programmin.pptx
annacarson387
 
Talk Code
Agiliq Solutions
 
Python Part 1
Mohamed Ramadan
 
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
Python tutorialfeb152012
Shani729
 
Python Cheat Sheet
Muthu Vinayagam
 
Intermediate python
NaphtaliOchonogor1
 
Introduction to python
Ahmed Salama
 
Ad

Recently uploaded (20)

PPTX
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
PDF
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
PPTX
week 1-2.pptx yueojerjdeiwmwjsweuwikwswiewjrwiwkw
rebznelz
 
PDF
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PDF
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
PPTX
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
PDF
Andreas Schleicher_Teaching Compass_Education 2040.pdf
EduSkills OECD
 
PDF
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
PDF
Wikinomics How Mass Collaboration Changes Everything Don Tapscott
wcsqyzf5909
 
PDF
COM and NET Component Services 1st Edition Juval Löwy
kboqcyuw976
 
PPTX
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
PPTX
ESP 10 Edukasyon sa Pagpapakatao PowerPoint Lessons Quarter 1.pptx
Sir J.
 
PPTX
Comparing Translational and Rotational Motion.pptx
AngeliqueTolentinoDe
 
DOCX
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
PDF
Rapid Mathematics Assessment Score sheet for all Grade levels
DessaCletSantos
 
PPTX
Practice Gardens and Polytechnic Education: Utilizing Nature in 1950s’ Hu...
Lajos Somogyvári
 
PPTX
Urban Hierarchy and Service Provisions.pptx
Islamic University of Bangladesh
 
PPTX
How Physics Enhances Our Quality of Life.pptx
AngeliqueTolentinoDe
 
PPTX
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
DOCX
MUSIC AND ARTS 5 DLL MATATAG LESSON EXEMPLAR QUARTER 1_Q1_W1.docx
DianaValiente5
 
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
week 1-2.pptx yueojerjdeiwmwjsweuwikwswiewjrwiwkw
rebznelz
 
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
Andreas Schleicher_Teaching Compass_Education 2040.pdf
EduSkills OECD
 
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
Wikinomics How Mass Collaboration Changes Everything Don Tapscott
wcsqyzf5909
 
COM and NET Component Services 1st Edition Juval Löwy
kboqcyuw976
 
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
ESP 10 Edukasyon sa Pagpapakatao PowerPoint Lessons Quarter 1.pptx
Sir J.
 
Comparing Translational and Rotational Motion.pptx
AngeliqueTolentinoDe
 
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
Rapid Mathematics Assessment Score sheet for all Grade levels
DessaCletSantos
 
Practice Gardens and Polytechnic Education: Utilizing Nature in 1950s’ Hu...
Lajos Somogyvári
 
Urban Hierarchy and Service Provisions.pptx
Islamic University of Bangladesh
 
How Physics Enhances Our Quality of Life.pptx
AngeliqueTolentinoDe
 
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
MUSIC AND ARTS 5 DLL MATATAG LESSON EXEMPLAR QUARTER 1_Q1_W1.docx
DianaValiente5
 

Introduction to the basics of Python programming (part 3)

  • 1. Introduction to the basics of Python programming (PART 3) 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  Recap of Parts 1 and 2  import, Modules and Packages  Python in action  Note: get the code here: https://dl.dropboxusercontent.com/u/10346356/session3.zip
  • 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  Iterables are container objects capable of returning their elements one at a time  Iterators implement the methods __iter__ and __next__
  • 6. 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  Iterables are container objects capable of returning their elements one at a time  Iterators implement the methods __iter__ and __next__
  • 7. 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  Iterables are container objects capable of returning their elements one at a time  Iterators implement the methods __iter__ and __next__
  • 8. A little recap >>> 2 + 2 4 >>> 4 / 2 2.0 >>> 4 > 2 True >>> x = 1, 2 >>> x (1, 2)
  • 9. A little recap >>> x = [1, 2] >>> x [1, 2] >>> x = {1, 2} >>> x {1, 2} >>> x = {"one": 1, "two": 2} >>> x {'two': 2, 'one': 1}
  • 10. 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  Iterables are container objects capable of returning their elements one at a time  Iterators implement the methods __iter__ and __next__
  • 11. A little recap if x % 3 == 0 and x % 5 == 0: return "FizzBuzz" elif x % 3 == 0: return "Fizz" elif x % 5 == 0: return "Buzz" else: return x
  • 12. A little recap colors = ["red", "green", "blue", "yellow", "purple"] for color in colors: if len(color) > 4: print(color) stack = [1, 2, 3] while len(stack) > 0: print(stack.pop())
  • 13. 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  Iterables are container objects capable of returning their elements one at a time  Iterators implement the methods __iter__ and __next__
  • 14. A little recap >>> colors = ["red", "green", "blue", "yellow", "purple"] >>> colors_iter = colors.__iter__() >>> colors_iter <list_iterator object at 0x100c7a160> >>> colors_iter.__next__() 'red' … >>> colors_iter.__next__() 'purple' >>> colors_iter.__next__() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
  • 15. A little recap colors = [(0, "red"), (1, "blue"), (2, "green"), (3, "yellow")] for index, color in colors: print(index, " --> ", color) colors = ["red", "blue", "green", "yellow", "purple"] for index, color in enumerate(colors): print(index, " --> ", color)
  • 16. A little recap  List comprehensions  Dictionary comprehensions  Functions  Positional Arguments  Keyword Arguments  Default parameters  Variable number of arguments
  • 17. A little recap colors = ["red", "green", "blue", "yellow", "purple"] new_colors = [] for color in colors: if len(color) > 4: new_colors.append(color) new_colors = [color for color in colors if len(color) > 4]
  • 18. Challenge  Given a list of colors, create a new list with all the colors in uppercase. Use list comprehensions. colors = ["red", "green", "blue", "yellow", "purple"] upper_colors = [] for color in colors: upper_colors.append(color.upper())
  • 19. A little recap  List comprehensions  Dictionary comprehensions  Functions  Positional Arguments  Keyword Arguments  Default parameters  Variable number of arguments
  • 20. A little recap squares = {} for i in range(10): squares[i] = i**2 squares = {i:i**2 for i in range(10)} {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
  • 21. Challenge  Given a list of colors, create a dictionary where each key is a color and the value is the color written backwards. Use dict comprehensions. colors = ["red", "green", "blue", "yellow", "purple"] backwards_colors = {} for color in colors: backwards_colors[color] = color[::-1]
  • 22. A little recap  List comprehensions  Dictionary comprehensions  Functions  Positional Arguments  Keyword Arguments  Default parameters  Variable number of arguments
  • 23. A little recap def say_hello(): print("Hello") def add_squares(a, b): return a**2 + b**2 >>> add_squares(2, 3) 13 def add_squares(a, b=3): return a**2 + b**2 >>> add_squares(2) 13
  • 24. A little recap def add_squares(a, b): return a**2 + b**2 >>> add_squares(b=3, a=2) 13
  • 25. A little recap def add_aquares(*args): if len(args) == 2: return args[0]**2 + args[1]**2 >>> add_squares(2, 3) 13
  • 26. A little recap def add_squares(**kwargs): if len(kwargs) == 2: return kwargs["a"]**2 + kwargs["b"]**2 >>> add_squares(a=2, b=3) 13
  • 27. Challenge  Define a function that turns a string into a list of int (operands) and strings (operators) and returns the list. >>> _convert_expression("4 3 +") [4, 3, "+"] >>> _convert_expression("4 3 + 2 *") [4, 3, "+", 2, "*"]  Hints:  “a b”.split(“ “) = [“a”, “b”]  “a”.isnumeric() = False  int(“2”) = 2  Kudos for who solves in one line using lambdas and list comprehensions.
  • 28. Challenge  RPN = Reverse Polish Notation  4 3 + (7)  4 3 + 2 * (14)  Extend RPN calculator to support the operators *, / and sqrt (from math module). import math print(math.sqrt(4))
  • 29. Modules and Packages  A module is a file with definitions and statements  It’s named after the file.  Modules are imported with import statement  import <module>  from <module> import <name1>  from <module> import <name1>, <name2>  import <module> as <new_module_name>  from <module> import <name1> as <new_name1>  from <module> import *
  • 30. Modules and Packages  A package is a directory with a special file __init__.py (the file can be empty, and it’s also not mandatory to exist)  The file __init__.py is executed when importing a package.  Packages can contain other packages.
  • 32. Modules and Packages  import api  from api import rest  import api.services.rpn  from api.services.hello import say_hello
  • 33. Challenge  Extend functionalities of the RESTful API:  Add a handler for http://localhost:8080/calculate  This handler should accept only the POST method.  Put all the pieces together in the rpn module.
  • 34. 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
  • 35. 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

  • #20: Similar to list comprehensions