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

Introduction to the basics of Python programming (part 1)

Apr 11, 2017

Download

Software

Pedro Rodrigues
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to the basics of Python programming (part 1)

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

Page 2: Introduction to the basics of Python programming (part 1)

A little about me

Name: Pedro Rodrigues Origin: Luanda (Angola) In the Netherlands since 2013 Former CTO and Senior Backend Engineer Freelance Software Engineer Book author: Start a Career with Python Coach

Page 3: Introduction to the basics of Python programming (part 1)

Why this Meetup Group?

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

Page 4: Introduction to the basics of Python programming (part 1)

What will be covered

First steps with the interactive shell: CPython Variables and Data types

Single and Multi variable assignment Immutable: strings, tuples, bytes, frozensets Mutable: lists, bytearrays, sets, dictionaries

Control Flow if statement for statement

Range, Iterable and Iterators while statement break and continue

Page 5: Introduction to the basics of Python programming (part 1)

What is Python?

Dutch product: create by Guido van Rossum in the late 80s Interpreted language Multi-paradigm: Procedural (imperative), Object Oriented, Functional Dynamically Typed

Page 6: Introduction to the basics of Python programming (part 1)

Python interpreter

CPython: reference, written in C PyPy, Jython, IronPython help() dir()

Page 7: Introduction to the basics of Python programming (part 1)

Hello, world!

Page 8: Introduction to the basics of Python programming (part 1)

Variables

Binding between a name and an object Single variable assignment: x = 1 Multi variable assignment: x, y = 1, 2 Swap values: x, y = y, x

Page 9: Introduction to the basics of Python programming (part 1)

Data Types

Numbers: int (Integers), float (Real Numbers), bool (Boolean, a subset of int)

Immutable Types: str (string), tuple, bytes, frozenset Mutable Types: list, set, bytearray, dict (dictionary) Sequence Types: str, tuple, bytes, bytearray, list Determining the type of an object: type()

Page 10: Introduction to the basics of Python programming (part 1)

Numbers: int and float

1 + 2 (addition) 1 – 2 (subtraction) 1 * 2 (multiplication) 1 / 2 (division) 1 // 2 (integer or floor division) 3 % 2 (modulus or remainder of the division) 2**2 (power)

Page 11: Introduction to the basics of Python programming (part 1)

Numbers: bool (continuation)

1 > 2 1 < 2 1 == 2 Boolean operations: and, or, not Objects can also be tested for their truth value. The following values

are false: None, False, zero of any numeric type, empty sequences, empty mapping

Page 12: Introduction to the basics of Python programming (part 1)

str (String)

x = “This is a string” x = ‘This is also a string’ x = “””So is this one””” x = ‘’’And this one as well’’’ x = “””This is a string that spans morethan one line. This can also be usedfor comments.“””

Page 13: Introduction to the basics of Python programming (part 1)

str (continuation)

Indexing elements: x[0] is the first element, x[1] is the second, and so on

Slicing: [start:end:step] [start:] # end is the length of the sequence, step assumed to be 1 [:end] # start is the beginning of the sequence, step assumed to be 1 [::step] # start is the beginning of the sequence, end is the length [start::step] [:end:step]

These operations are common for all sequence types

Page 14: Introduction to the basics of Python programming (part 1)

str (continuation)

Some common string methods: join (concatenates the strings from an iterable using the string as glue) format (returns a formatted version of the string) strip (returns a copy of the string without leading and trailing whitespace)

Use help(str.<command>) in the interactive shell and dir(str)

Page 15: Introduction to the basics of Python programming (part 1)

Control Flow (pt. 1): if statement

Compound statement

if <expression>:

suite

elif <expression2>:

suite

else:

suite

Page 16: Introduction to the basics of Python programming (part 1)

Control Flow (pt. 2): if statement

age = int(input(“> “))

if age >= 30:

print(“You are 30 or above”)

elif 20 < age < 30:

print(“You are in your twenties”)

else:

print(“You are less than 20”)

Page 17: Introduction to the basics of Python programming (part 1)

list

x = [] # empty list x = [1, 2, 3] # list with 3 elements x = list(“Hello”) x.append(“something”) # append object to the end of the list x.insert(2, “something”) # append object before index 2

Page 18: Introduction to the basics of Python programming (part 1)

dict (Dictionaries)

Mapping between keys and values Values can be of whatever type Keys must be hashable x = {} # empty dictionary x = {“Name”: “John”, “Age”: 23} x.keys() x.values() x.items()

Page 19: Introduction to the basics of Python programming (part 1)

Control Flow: for loop

Also compound statement Iterates over the elements of an iterable object

for <target> in <expression>:

suite

else:

suite

Page 20: Introduction to the basics of Python programming (part 1)

Control Flow: for loop (continuation)

colors = [“red”, “green”, “blue”, “orange”]

for color in colors:

print(color)

colors = [[1, “red”], [2, “green”], [3, “blue”], [4, “orange”]]

for i, color in colors:

print(i, “ ---> “, color)

Page 21: Introduction to the basics of Python programming (part 1)

Control Flow: for loop (continuation)

Iterable is a container object able to return its elements one at a time Iterables use iterators to return their elements one at a time Iterator is an object that represents a stream of data Must implement two methods: __iter__ and __next__ (Iterator protocol) Raises StopIteration when elements are exhausted Lazy evaluation

Page 22: Introduction to the basics of Python programming (part 1)

Challenge

Rewrite the following code using enumerate and the following list of colors: [“red”, “green”, “blue”, “orange”] . (hint: help(enumerate))

colors = [[1, “red”], [2, “green”], [3, “blue”], [4, “orange”]]

for i, color in colors:

print(i, “ ---> “, color)

Page 23: Introduction to the basics of Python programming (part 1)

Control Flow: for loop (continuation)

range: represents a sequence of integers range(stop) range(start, stop) range(start, stop, step)

Page 24: Introduction to the basics of Python programming (part 1)

Control Flow: for loop (continuation)

colors = [“red”, “green”, “orange”, “blue”]

for color in colors:

print(color)

else:

print(“Done!”)

Page 25: Introduction to the basics of Python programming (part 1)

Control Flow: while loop

Executes the suite of statements as long as the expression evaluates to True

while <expression>:

suite

else:

suite

Page 26: Introduction to the basics of Python programming (part 1)

Control Flow: while loop (continuation)

counter = 5

while counter > 0:

print(counter)

counter = counter - 1

counter = 5

while counter > 0:

print(counter)

counter = counter – 1

else:

print(“Done!”)

Page 27: Introduction to the basics of Python programming (part 1)

Challenge

Rewrite the following code using a for loop and range:

counter = 5

while counter > 0:

print(counter)

counter = counter - 1

Page 28: Introduction to the basics of Python programming (part 1)

Control Flow: break and continue

Can only occur nested in a for or while loop Change the normal flow of execution of a loop:

break stops the loop continue skips to the next iteration

for i in range(10):

if i % 2 == 0:

continue

else:

print(i)

Page 29: Introduction to the basics of Python programming (part 1)

Control Flow: break and (continue)

colors = [“red”, “green”, “blue”, “purple”, “orange”]

for color in colors:

if len(color) > 5:

break

else:

print(color)

Page 30: Introduction to the basics of Python programming (part 1)

Challenge

Rewrite the following code without the if statement (hint: use the step in range)

for i in range(10):

if i % 2 == 0:

continue

else:

print(i)

Page 31: Introduction to the basics of Python programming (part 1)

Reading material

Data Model (Python Language Reference): https://docs.python.org/3/reference/datamodel.html

The if statement (Python Language Reference): https://docs.python.org/3/reference/compound_stmts.html#the-if-statement

The for statement (Python Language Reference): https://docs.python.org/3/reference/compound_stmts.html#the-for-statement

The while statement (Python Language Reference): https://docs.python.org/3/reference/compound_stmts.html#the-while-statement

Page 32: Introduction to the basics of Python programming (part 1)

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 15% off (NZ6SZFBL): https://www.createspace.com/6506874

Page 33: Introduction to the basics of Python programming (part 1)

set

Unordered mutable collection of elements Doesn’t allow duplicate elements Elements must be hashable Useful to test membership x = set() # empty set x = {1, 2, 3} # set with 3 integers 2 in x # membership test

Page 34: Introduction to the basics of Python programming (part 1)

tuple

x = 1, x = (1,) x = 1, 2, 3 x = (1, 2, 3) x = (1, “Hello, world!”) You can also slice tuples

Page 35: Introduction to the basics of Python programming (part 1)

bytes

Immutable sequence of bytes Each element is an ASCII character Integers greater than 127 must be properly escaped x = b”This is a bytes object” x = b’This is also a bytes object’ x = b”””So is this””” x = b’’’or even this’’’

Page 36: Introduction to the basics of Python programming (part 1)

bytearray

Mutable counterpart of bytes x = bytearray() x = bytearray(10) x = bytearray(b”Hello, world!”)