SlideShare a Scribd company logo
Introduction to the basics of
Python programming
(PART 1)
by Pedro Rodrigues (pedro@startacareerwithpython.com)
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
Why this Meetup Group?
๏ต Promote the usage of Python
๏ต Gather people from different industries and backgrounds
๏ต Teach and Learn
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
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
Python interpreter
๏ต CPython: reference, written in C
๏ต PyPy, Jython, IronPython
๏ต help()
๏ต dir()
Hello, world!
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
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()
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)
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
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 more
than one line. This can also be used
for comments.
โ€œโ€โ€
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
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)
Control Flow (pt. 1): if statement
๏ต Compound statement
if <expression>:
suite
elif <expression2>:
suite
else:
suite
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โ€)
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
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()
Control Flow: for loop
๏ต Also compound statement
๏ต Iterates over the elements of an iterable object
for <target> in <expression>:
suite
else:
suite
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)
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
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)
Control Flow: for loop (continuation)
๏ต range: represents a sequence of integers
๏ต range(stop)
๏ต range(start, stop)
๏ต range(start, stop, step)
Control Flow: for loop (continuation)
colors = [โ€œredโ€, โ€œgreenโ€, โ€œorangeโ€, โ€œblueโ€]
for color in colors:
print(color)
else:
print(โ€œDone!โ€)
Control Flow: while loop
๏ต Executes the suite of statements as long as the expression evaluates to True
while <expression>:
suite
else:
suite
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!โ€)
Challenge
๏ต Rewrite the following code using a for loop and range:
counter = 5
while counter > 0:
print(counter)
counter = counter - 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)
Control Flow: break and (continue)
colors = [โ€œredโ€, โ€œgreenโ€, โ€œblueโ€, โ€œpurpleโ€, โ€œorangeโ€]
for color in colors:
if len(color) > 5:
break
else:
print(color)
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)
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
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
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
tuple
๏ต x = 1,
๏ต x = (1,)
๏ต x = 1, 2, 3
๏ต x = (1, 2, 3)
๏ต x = (1, โ€œHello, world!โ€)
๏ต You can also slice tuples
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โ€™โ€™โ€™
bytearray
๏ต Mutable counterpart of bytes
๏ต x = bytearray()
๏ต x = bytearray(10)
๏ต x = bytearray(bโ€Hello, world!โ€)

More Related Content

What's hot (20)

PPTX
Python
Aashish Jain
ย 
PPTX
Python Tutorial Part 1
Haitham El-Ghareeb
ย 
PPTX
Fundamentals of Python Programming
Kamal Acharya
ย 
PPTX
Python - An Introduction
Swarit Wadhe
ย 
PPTX
Python basics
RANAALIMAJEEDRAJPUT
ย 
PPTX
Python basics
Jyoti shukla
ย 
PDF
Introduction To Python | Edureka
Edureka!
ย 
PPTX
Python variables and data types.pptx
AkshayAggarwal79
ย 
PDF
Python programming
Prof. Dr. K. Adisesha
ย 
PDF
Python Basics | Python Tutorial | Edureka
Edureka!
ย 
PPT
Python ppt
Mohita Pandey
ย 
PPTX
Basics of python
SurjeetSinghSurjeetS
ย 
PDF
Variables & Data Types In Python | Edureka
Edureka!
ย 
PPTX
introduction to python
Jincy Nelson
ย 
PPSX
Programming with Python
Rasan Samarasinghe
ย 
PPTX
Python | What is Python | History of Python | Python Tutorial
QA TrainingHub
ย 
PDF
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
ย 
PDF
Introduction to python
Agung Wahyudi
ย 
Python
Aashish Jain
ย 
Python Tutorial Part 1
Haitham El-Ghareeb
ย 
Fundamentals of Python Programming
Kamal Acharya
ย 
Python - An Introduction
Swarit Wadhe
ย 
Python basics
RANAALIMAJEEDRAJPUT
ย 
Python basics
Jyoti shukla
ย 
Introduction To Python | Edureka
Edureka!
ย 
Python variables and data types.pptx
AkshayAggarwal79
ย 
Python programming
Prof. Dr. K. Adisesha
ย 
Python Basics | Python Tutorial | Edureka
Edureka!
ย 
Python ppt
Mohita Pandey
ย 
Basics of python
SurjeetSinghSurjeetS
ย 
Variables & Data Types In Python | Edureka
Edureka!
ย 
introduction to python
Jincy Nelson
ย 
Programming with Python
Rasan Samarasinghe
ย 
Python | What is Python | History of Python | Python Tutorial
QA TrainingHub
ย 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
ย 
Introduction to python
Agung Wahyudi
ย 

Viewers also liked (20)

PDF
Python tutorial
Vijay Chaitanya
ย 
PPTX
Basics of Python programming (part 2)
Pedro Rodrigues
ย 
PPTX
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
ย 
PDF
Pythonๆ•™็จ‹ / Python tutorial
ee0703
ย 
PPTX
Python Tutorial Part 2
Haitham El-Ghareeb
ย 
PDF
Python - basics
Jรฉferson Machado
ย 
PDF
PythonIntro
webuploader
ย 
PDF
Python Tutorial
AkramWaseem
ย 
PPTX
Python Programming Essentials - M6 - Code Blocks and Indentation
P3 InfoTech Solutions Pvt. Ltd.
ย 
PDF
AmI 2015 - Python basics
Luigi De Russis
ย 
PDF
Python Workshop
Saket Choudhary
ย 
PDF
python codes
tusharpanda88
ย 
PPTX
Python basics
Hoang Nguyen
ย 
PDF
AmI 2016 - Python basics
Luigi De Russis
ย 
PDF
Introduction to python programming
Kiran Vadakkath
ย 
PPTX
Python basics
NexThoughts Technologies
ย 
PPT
Classification of computers
sunil kumar
ย 
PDF
Introduction to python 3 2nd round
Youhei Sakurai
ย 
PPTX
Evolution and classification of computers
AVINASH ANAND
ย 
PPTX
Python programming language
Ebrahim Shakhatreh
ย 
Python tutorial
Vijay Chaitanya
ย 
Basics of Python programming (part 2)
Pedro Rodrigues
ย 
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
ย 
Pythonๆ•™็จ‹ / Python tutorial
ee0703
ย 
Python Tutorial Part 2
Haitham El-Ghareeb
ย 
Python - basics
Jรฉferson Machado
ย 
PythonIntro
webuploader
ย 
Python Tutorial
AkramWaseem
ย 
Python Programming Essentials - M6 - Code Blocks and Indentation
P3 InfoTech Solutions Pvt. Ltd.
ย 
AmI 2015 - Python basics
Luigi De Russis
ย 
Python Workshop
Saket Choudhary
ย 
python codes
tusharpanda88
ย 
Python basics
Hoang Nguyen
ย 
AmI 2016 - Python basics
Luigi De Russis
ย 
Introduction to python programming
Kiran Vadakkath
ย 
Python basics
NexThoughts Technologies
ย 
Classification of computers
sunil kumar
ย 
Introduction to python 3 2nd round
Youhei Sakurai
ย 
Evolution and classification of computers
AVINASH ANAND
ย 
Python programming language
Ebrahim Shakhatreh
ย 
Ad

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

PPTX
python introductions2 to basics programmin.pptx
annacarson387
ย 
PPTX
introductionpart1-160906115340 (1).pptx
AsthaChaurasia4
ย 
PPTX
Keep it Stupidly Simple Introduce Python
SushJalai
ย 
PPTX
Introduction to learn and Python Interpreter
Alamelu
ย 
PPTX
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
ย 
PPTX
Python for Beginners(v1)
Panimalar Engineering College
ย 
PPTX
Python basics
Manisha Gholve
ย 
PPTX
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
ย 
PDF
Data Structure and Algorithms (DSA) with Python
epsilonice
ย 
PDF
PythonStudyMaterialSTudyMaterial.pdf
data2businessinsight
ย 
PDF
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
ย 
PPT
introduction to python in english presentation file
RujanTimsina1
ย 
DOCX
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
priestmanmable
ย 
PDF
Python_Fundamentals_for_Everyone_Usefull
rravipssrivastava
ย 
PPTX
Python-CH01L04-Presentation.pptx
ElijahSantos4
ย 
PPTX
Automation Testing theory notes.pptx
NileshBorkar12
ย 
PPTX
Python Interview Questions | Python Interview Questions And Answers | Python ...
Simplilearn
ย 
PPTX
Python programming
Ashwin Kumar Ramasamy
ย 
PPTX
Basic Python Programming: Part 01 and Part 02
Fariz Darari
ย 
PPTX
PPt Revision of the basics of python1.pptx
tcsonline1222
ย 
python introductions2 to basics programmin.pptx
annacarson387
ย 
introductionpart1-160906115340 (1).pptx
AsthaChaurasia4
ย 
Keep it Stupidly Simple Introduce Python
SushJalai
ย 
Introduction to learn and Python Interpreter
Alamelu
ย 
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
ย 
Python for Beginners(v1)
Panimalar Engineering College
ย 
Python basics
Manisha Gholve
ย 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
ย 
Data Structure and Algorithms (DSA) with Python
epsilonice
ย 
PythonStudyMaterialSTudyMaterial.pdf
data2businessinsight
ย 
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
ย 
introduction to python in english presentation file
RujanTimsina1
ย 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
priestmanmable
ย 
Python_Fundamentals_for_Everyone_Usefull
rravipssrivastava
ย 
Python-CH01L04-Presentation.pptx
ElijahSantos4
ย 
Automation Testing theory notes.pptx
NileshBorkar12
ย 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Simplilearn
ย 
Python programming
Ashwin Kumar Ramasamy
ย 
Basic Python Programming: Part 01 and Part 02
Fariz Darari
ย 
PPt Revision of the basics of python1.pptx
tcsonline1222
ย 
Ad

Recently uploaded (20)

PDF
Difference Between Kubernetes and Docker .pdf
Kindlebit Solutions
ย 
PDF
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
ย 
PPTX
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
ย 
PDF
IDM Crack with Internet Download Manager 6.42 Build 41
utfefguu
ย 
PDF
WholeClear Split vCard Software for Split large vCard file
markwillsonmw004
ย 
PPTX
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
ย 
PDF
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
ย 
PPTX
For my supp to finally picking supp that work
necas19388
ย 
PPTX
How Can Recruitment Management Software Improve Hiring Efficiency?
HireME
ย 
PPTX
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
ย 
PPTX
Quality on Autopilot: Scaling Testing in Uyuni
Oscar Barrios Torrero
ย 
PPTX
EO4EU Ocean Monitoring: Maritime Weather Routing Optimsation Use Case
EO4EU
ย 
PDF
Building scalbale cloud native apps with .NET 8
GillesMathieu10
ย 
PPTX
Automatic_Iperf_Log_Result_Excel_visual_v2.pptx
Chen-Chih Lee
ย 
PDF
Rewards and Recognition (2).pdf
ethan Talor
ย 
PDF
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
ย 
PDF
Code Once; Run Everywhere - A Beginnerโ€™s Journey with React Native
Hasitha Walpola
ย 
PPTX
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
ย 
PPTX
NeuroStrata: Harnessing Neuro-Symbolic Paradigms for Improved Testability and...
Ivan Ruchkin
ย 
PPTX
ManageIQ - Sprint 264 Review - Slide Deck
ManageIQ
ย 
Difference Between Kubernetes and Docker .pdf
Kindlebit Solutions
ย 
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
ย 
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
ย 
IDM Crack with Internet Download Manager 6.42 Build 41
utfefguu
ย 
WholeClear Split vCard Software for Split large vCard file
markwillsonmw004
ย 
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
ย 
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
ย 
For my supp to finally picking supp that work
necas19388
ย 
How Can Recruitment Management Software Improve Hiring Efficiency?
HireME
ย 
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
ย 
Quality on Autopilot: Scaling Testing in Uyuni
Oscar Barrios Torrero
ย 
EO4EU Ocean Monitoring: Maritime Weather Routing Optimsation Use Case
EO4EU
ย 
Building scalbale cloud native apps with .NET 8
GillesMathieu10
ย 
Automatic_Iperf_Log_Result_Excel_visual_v2.pptx
Chen-Chih Lee
ย 
Rewards and Recognition (2).pdf
ethan Talor
ย 
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
ย 
Code Once; Run Everywhere - A Beginnerโ€™s Journey with React Native
Hasitha Walpola
ย 
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
ย 
NeuroStrata: Harnessing Neuro-Symbolic Paradigms for Improved Testability and...
Ivan Ruchkin
ย 
ManageIQ - Sprint 264 Review - Slide Deck
ManageIQ
ย 

Introduction to the basics of Python programming (part 1)

  • 1. Introduction to the basics of Python programming (PART 1) by Pedro Rodrigues ([email protected])
  • 2. 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
  • 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 ๏ต 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
  • 5. 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
  • 6. Python interpreter ๏ต CPython: reference, written in C ๏ต PyPy, Jython, IronPython ๏ต help() ๏ต dir()
  • 8. 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
  • 9. 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()
  • 10. 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)
  • 11. 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
  • 12. 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 more than one line. This can also be used for comments. โ€œโ€โ€
  • 13. 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
  • 14. 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)
  • 15. Control Flow (pt. 1): if statement ๏ต Compound statement if <expression>: suite elif <expression2>: suite else: suite
  • 16. 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โ€)
  • 17. 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
  • 18. 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()
  • 19. Control Flow: for loop ๏ต Also compound statement ๏ต Iterates over the elements of an iterable object for <target> in <expression>: suite else: suite
  • 20. 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)
  • 21. 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
  • 22. 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)
  • 23. Control Flow: for loop (continuation) ๏ต range: represents a sequence of integers ๏ต range(stop) ๏ต range(start, stop) ๏ต range(start, stop, step)
  • 24. Control Flow: for loop (continuation) colors = [โ€œredโ€, โ€œgreenโ€, โ€œorangeโ€, โ€œblueโ€] for color in colors: print(color) else: print(โ€œDone!โ€)
  • 25. Control Flow: while loop ๏ต Executes the suite of statements as long as the expression evaluates to True while <expression>: suite else: suite
  • 26. 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!โ€)
  • 27. Challenge ๏ต Rewrite the following code using a for loop and range: counter = 5 while counter > 0: print(counter) counter = counter - 1
  • 28. 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)
  • 29. Control Flow: break and (continue) colors = [โ€œredโ€, โ€œgreenโ€, โ€œblueโ€, โ€œpurpleโ€, โ€œorangeโ€] for color in colors: if len(color) > 5: break else: print(color)
  • 30. 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)
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. tuple ๏ต x = 1, ๏ต x = (1,) ๏ต x = 1, 2, 3 ๏ต x = (1, 2, 3) ๏ต x = (1, โ€œHello, world!โ€) ๏ต You can also slice tuples
  • 35. 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โ€™โ€™โ€™
  • 36. bytearray ๏ต Mutable counterpart of bytes ๏ต x = bytearray() ๏ต x = bytearray(10) ๏ต x = bytearray(bโ€Hello, world!โ€)