Basics of Python programming (part 2)

36
Introduction to the basics of Python programming (PART 2) by Pedro Rodrigues ([email protected])

Transcript of Basics of Python programming (part 2)

Page 1: Basics of Python programming (part 2)

Introduction to the basics of Python programming(PART 2)by Pedro Rodrigues ([email protected])

Page 2: Basics of Python programming (part 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”]}

Page 3: Basics of Python programming (part 2)

Why this Meetup Group?

Promote the usage of Python Gather people from different industries and backgrounds Teach and Learn

Page 4: Basics of Python programming (part 2)

What will be covered

List and Dictionary comprehensions Functions

Positional arguments Keyword arguments Default parameter values Variable number of arguments Names, namespaces and scope

Page 5: Basics of Python programming (part 2)

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__

Page 6: Basics of Python programming (part 2)

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]

Page 7: Basics of Python programming (part 2)

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']

Page 8: Basics of Python programming (part 2)

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)]

Page 9: Basics of Python programming (part 2)

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']

Page 10: Basics of Python programming (part 2)

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}

Page 11: Basics of Python programming (part 2)

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}

Page 12: Basics of Python programming (part 2)

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'}

Page 13: Basics of Python programming (part 2)

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'}

Page 14: Basics of Python programming (part 2)

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}

Page 15: Basics of Python programming (part 2)

Functions

Callable data type Control Flow construct

def function_name(params_list): suite

def print_hello_world(): print("Hello") print("World")

Page 16: Basics of Python programming (part 2)

Positional arguments

def function_name(param1, param2, ...): # do something with param1 and/or param2

>>> function_name(arg1, arg2)

Page 17: Basics of Python programming (part 2)

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

Page 18: Basics of Python programming (part 2)

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).

>>> import math >>> math.sqrt(16) 4.0 Sample input: 1 3 7 4 Sample output: 6.082762530298219

Page 19: Basics of Python programming (part 2)

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

Page 20: Basics of Python programming (part 2)

Keyword arguments

The order of the arguments doesn’t matterdef 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)

Page 21: Basics of Python programming (part 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

Page 22: Basics of Python programming (part 2)

Default parameter values

For parameters with default value, the corresponding argument can be omitteddef 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

Page 23: Basics of Python programming (part 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']

Page 24: Basics of Python programming (part 2)

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.

Page 25: Basics of Python programming (part 2)

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)

Page 26: Basics of Python programming (part 2)

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)

Page 27: Basics of Python programming (part 2)

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

Page 28: Basics of Python programming (part 2)

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

Page 29: Basics of Python programming (part 2)

Challenge

Sample input: x1=1 y1=3 x2=7 y2=4, x1=13 y1=10 x2=109 y2=45 Sample output:6.082762530298219102.18121158021175 Use dict comprehension and unpack the dictionary in distance.

Page 30: Basics of Python programming (part 2)

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.

Page 31: Basics of Python programming (part 2)

Names, Namespaces and Scope

Global module namespacex = 10 print(x)

Local namespace of a functionx = 10

def print_x(): x = 5 print(x) # prints 5

Page 32: Basics of Python programming (part 2)

Names, Namespaces and Scope

Local namespace of a functionx = 10

def print_x(): print(x) # prints 10

Page 33: Basics of Python programming (part 2)

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

Page 34: Basics of Python programming (part 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.

Page 36: Basics of Python programming (part 2)

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