SlideShare a Scribd company logo
1 of 51
Download to read offline
Python Puzzlers




Tendayi Mawushe
PyCon Ireland 2010
Introduction
Eight Python Puzzles
  Short Python program with curious behaviour
  What is the output? (multiple choice)
  The correct answer given
  How to fix the problem (if there was one)
  The moral of the story
What will be covered
  Language and core libraries
  Python 2.6 & 3.x (some puzzles apply to 2.6 only)
1. Exceptional Circumstances

try:
    raise NameError('some_name')
except TypeError, NameError:
    print ('caught exception NameError')
except Exception:
    pass
1. What is the output?

try:
    raise NameError('some_name')
except TypeError, NameError:
    print ('caught exception NameError')
except Exception:
    pass


(a)   caught exception NameError
(b)   SyntaxError: invalid syntax
(c)   <no output>
(d)   caught exception TypeError
1. What is the output?

(a)   caught exception NameError
(b)   SyntaxError: invalid syntax
(c)   <no output>
(d)   caught exception TypeError
1. A closer look

try:
    raise NameError('some_name')
except TypeError, NameError:
    print ('caught exception NameError')
except Exception:
    pass
1. How do you fix it?

try:
    raise NameError('some_name')
except (TypeError, NameError):
    print ('caught exception NameError')
except Exception:
    pass


>>>
caught exception NameError
1. The moral of the story

When catching multiple exceptions in a single
except clause you must surround them in
parentheses
This problem is non-existent problem in Python
3.x because the problematic syntax is not
permitted:
  except SomeException, variable # not valid
  3.x syntax
  except SomeException as variable
2. Final Countdown

seconds = 10
for i in range(10):
    --seconds
if seconds:
    print('Wait for it.', seconds)
else:
    print('Happy New Year!', seconds)
2. What is the output?

seconds = 10
for i in range(10):
    --seconds
if seconds:
    print('Wait for it.', seconds)
else:
    print('Happy New Year!', seconds)


(a)   ('Wait for it.', 10)
(b)   -10
(c)   SyntaxError: invalid syntax
(d)   ('Happy New Year!', 0)
2. What is the output?

(a)   ('Wait for it.', 10)
(b)   -10
(c)   SyntaxError: invalid syntax
(d)   ('Happy New Year!', 0)
2. A closer look

seconds = 10
for i in range(10):
    --seconds
if seconds:
    print('Wait for it.', seconds)
else:
    print('Happy New Year!', seconds)
2. How do you fix it?

seconds = 10
for i in range(10):
    seconds -= 1
if seconds:
    print('Wait for it.', seconds)
else:
    print('Happy New Year!', seconds)




>>>
('Happy New Year!', 0)
2. The moral of the story

There is no -- or ++ operator in Python to
achieve that effect use -= 1 and += 1
--seconds is actually the same as -(-seconds)
3. Local News

def news(headline):
    sports = 'Soccer'
    for story in locals():
        print(locals()[story])
news('Politics')
3. What is the output?

def news(headline):
    sports = 'Soccer'
    for story in locals():
        print(locals()[story])
news('Politics')


(a) Politics
    Soccer
(b) {'sports': 'Soccer'}
(c) Soccer
(d) RuntimeError: dictionary changed size during
iteration
3. What is the output?

(a) Politics
    Soccer
(b) {'sports': 'Soccer'}
(c) Soccer
(d) RuntimeError: dictionary changed
size during iteration
3. A closer look

def news(headline):
    sports = 'Soccer'
    for story in locals():
        print(locals()[story])
news('Politics')
3. How do you fix it?

def news(headline):
    sports = 'Soccer'
    stories = locals()
    for story in stories:
        print(stories[story])
news('Politics')


>>>
Politics
Soccer
3. The moral of the story

When locals() is invoked it updates and returns
a dictionary representing the current local
symbol table
You should never attempt to update the locals
dictionary, however if you need to access it's
contents in a loop assign it to another name
first
4. TGIF

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',
'Sun']
weekend = enumerate(days)[5:]
for day in weekend:
    print(day[0], day[1])
4. What is the output?

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',
'Sun']
weekend = enumerate(days)[5:]
for day in weekend:
    print(day[0], day[1])


(a)   (5, 'Sat') (6, 'Sun')
(b)   ('Sat', 'Sun')
(c)   TypeError: object is unsubscriptable
(d)   (5, 6)
4. What is the output?

(a)   (5, 'Sat') (6, 'Sun')
(b)   ('Sat', 'Sun')
(c)   TypeError: object is unsubscriptable
(d)   (5, 6)
4. A closer look

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',
'Sun']
weekend = enumerate(days)[5:]
for day in weekend:
    print(day[0], day[1])
4. How do you fix it?

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',
'Sun']
weekend = list(enumerate(days))[5:]
for day in weekend:
    print(day[0], day[1])


>>>
(5, 'Sat')
(6, 'Sun')
4. The moral of the story

The enumerate built-in function is a generator,
that is it returns an iterator
Iterators are not sequences therefore they
cannot be indexed or sliced:
  If you need to index or slice an iterator
  you must first convert it to a list, this
  loads the entire dataset into memory
  Generators can represent infinite chain of
  values for example itertools.count(), these
  cannot be meaningfully sliced in reverse
5. Rabbits everywhere
a, b = 0, 1
def fibonacci(n):
    for i in range(n):
        a, b = b, a + b
    return a
fib8 = fibonacci(8)
print(fib8)
5. What is the output?

a, b = 0, 1
def fibonacci(n):
    for i in range(n):
        a, b = b, a + b
    return a
fib8 = fibonacci(8)
print(fib8)


(a)   UnboundLocalError: local variable
(b)   21
(c)   1
(d)   0
5. What is the output?

(a)   UnboundLocalError: local variable
(b)   21
(c)   1
(d)   0
5. A closer look

a, b = 0, 1
def fibonacci(n):
    for i in range(n):
        a, b = b, a + b
    return a
fib8 = fibonacci(8)
print(fib8)
5. How do you fix it?

a, b = 0, 1
def fibonacci(n):
    global a, b
    for i in range(n):
        a, b = b, a + b
    return a
fib8 = fibonacci(8)
print(fib8)


>>>
21
5. The moral of the story

The issue is local variable optimisation.
  If a variable is assigned in a function it is a local
  variable, the bytecode generated to access it is
  different to that for global variables.
A variable in a function can either be local or
global, but not both.
  Do not mix up global and local names in this way, it
  is confusing and problematic.
6. The Whole Truth

w = False
h = []
o = 0,
l = None
e = {}
print(any((w, h, o, l, e)))
6. What is the output?

w = False
h = []
o = 0,
l = None
e = {}
print(any((w, h, o, l, e)))


(a)   True
(b)   (w, h, o, l, e)
(c)   (False, [], 0, None, {})
(d)   False
6. What is the output?

(a)   True
(b)   (w, h, o, l, e)
(c)   (False, [], 0, None, {})
(d)   False
6. A closer look

w = False
h = []
O = 0,
l = None
e = {}
print(any((w, h, o, l, e)))
6. How do you fix it?

w = False
h = []
O = 0
l = None
e = {}
print(any((w, h, o, l, e)))


>>> False
6. The moral of the story

The comma is the tuple constructor, not the
parentheses
Though it is not required it is generally
considered good style to use parentheses when
creating a tuple:
  (0,) is better than 0,
7. Double or Nothing

def double(items, doubles=[]):
    for item in items:
        doubles.append(item * 2)
    return doubles
numbers = double([1, 2, 3])
words = double(['one', 'two', 'three'])
print(words)
7. What is the output?

def double(items, doubles=[]):
    for item in items:
        doubles.append(item * 2)
    return doubles
numbers = double([1, 2, 3])
words = double(['one', 'two', 'three'])
print(words)


(a)   [2, 4, 6, 'oneone', 'twotwo', 'threethree']
(b)   ['oneone', 'twotwo', 'threethree']
(c)   TypeError: unsupported operand type(s) for *
(d)   [2, 4, 6]
7. What is the output?

(a)   [2, 4, 6, 'oneone', 'twotwo', 'threethree']
(b)   ['oneone', 'twotwo', 'threethree']
(c)   TypeError: unsupported operand type(s) for *
(d)   [2, 4, 6]
7. A closer look

def double(items, doubles=[]):
    for item in items:
        doubles.append(item * 2)
    return doubles
numbers = double([1, 2, 3])
words = double(['one', 'two', 'three'])
print(words)
7. How do you fix it?

def double(items, doubles=None):
    if doubles is None: doubles = []
    for item in items:
        doubles.append(item * 2)
    return doubles
numbers = double([1, 2, 3])
words = double(['one', 'two', 'three'])
print(words)




>>> ['oneone', 'twotwo', 'threethree']
7. The moral of the story

Do not use mutable types as default arguments
  Default arguments are evaluated when the function
  is defined not when the function is called
  If you want to use a mutable type as a default
  argument, set the default to None and initialise it
  properly inside the function
8. Evening Out the Odds

nums = [01, 02, 03, 04, 05, 06, 07, 08, 09, 10]
evens = []
for num in nums:
    if num % 2 != 0: # is the number odd
        evens.append(num + 1)
print(evens)
8. What is the output?

nums = [01, 02, 03, 04, 05, 06, 07, 08, 09, 10]
evens = []
for num in nums:
    if num % 2 != 0: # is the number odd
        evens.append(num + 1)
print(evens)


(a)   [2, 4, 6, 8,   10]
(b)   SyntaxError:   invalid token
(c)   [02, 04, 06,   08, 10]
(d)   [2, 2, 4, 4,   6, 6, 8, 8, 10, 10]
8. What is the output?

(a)   [2, 4, 6, 8,   10]
(b)   SyntaxError:   invalid token
(c)   [02, 04, 06,   08, 10]
(d)   [1, 2, 3, 4,   5]
8. A closer look

nums = [01, 02, 03, 04, 05, 06, 07, 08, 09, 10]
evens = []
for num in nums:
    if num % 2 != 0: # is the number odd
        evens.append(num + 1)
print(evens)
8. How do you fix it?

nums = [01, 02, 03, 04, 05, 06, 07, 010, 011, 012]
evens = []
for num in nums:
    if num % 2 != 0: # is the number odd
        evens.append(oct(num + 1))
print(evens)




>>> ['02', '04', '06', '010', '012']
8. The moral of the story

In Python 2.x a leading 0 specifies an octal
literal
If you want to work with octal numbers
remember the valid digits are 0 though 7
In Python 3.x octal literals are specified using
0o, which removes the ambiguity
  01 # not valid 3.x syntax
  0o1
Links
Slides:
insmallportions.com

Q & A:
stackoverflow.com
Inspiration:
javapuzzlers.com

More Related Content

What's hot

13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Matt Harrison
 
Metaprogramming in julia
Metaprogramming in juliaMetaprogramming in julia
Metaprogramming in julia岳華 杜
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonMarian Marinov
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
Introduction to julia
Introduction to juliaIntroduction to julia
Introduction to julia岳華 杜
 
Python programing
Python programingPython programing
Python programinghamzagame
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanWei-Yuan Chang
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and LibrariesVenugopalavarma Raja
 
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEFUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEVenugopalavarma Raja
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data StructureChan Shik Lim
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Logic programming a ruby perspective
Logic programming a ruby perspectiveLogic programming a ruby perspective
Logic programming a ruby perspectiveNorman Richards
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2RajKumar Rampelli
 

What's hot (20)

13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
 
Python
PythonPython
Python
 
Metaprogramming in julia
Metaprogramming in juliaMetaprogramming in julia
Metaprogramming in julia
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
Introduction to julia
Introduction to juliaIntroduction to julia
Introduction to julia
 
Python programing
Python programingPython programing
Python programing
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and Libraries
 
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEFUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Logic programming a ruby perspective
Logic programming a ruby perspectiveLogic programming a ruby perspective
Logic programming a ruby perspective
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
 

Viewers also liked

Comparison of Agent-based platforms
Comparison of Agent-based platformsComparison of Agent-based platforms
Comparison of Agent-based platformsKishoj Bajracharya
 
GIS and Agent-based modeling: Part 2
GIS and Agent-based modeling: Part 2GIS and Agent-based modeling: Part 2
GIS and Agent-based modeling: Part 2crooksAndrew
 
Agent Based Modeling and Simulation - Overview and Tools
Agent Based Modeling and Simulation - Overview and ToolsAgent Based Modeling and Simulation - Overview and Tools
Agent Based Modeling and Simulation - Overview and ToolsStathis Grigoropoulos
 
GIS and Agent-based modeling: Part 1
GIS and Agent-based modeling: Part 1GIS and Agent-based modeling: Part 1
GIS and Agent-based modeling: Part 1crooksAndrew
 
Agent-Based Modeling & Python @ PyData DC 2016
Agent-Based Modeling & Python @ PyData DC 2016Agent-Based Modeling & Python @ PyData DC 2016
Agent-Based Modeling & Python @ PyData DC 2016Jacqueline Kazil
 

Viewers also liked (6)

Agent Based Models
Agent Based ModelsAgent Based Models
Agent Based Models
 
Comparison of Agent-based platforms
Comparison of Agent-based platformsComparison of Agent-based platforms
Comparison of Agent-based platforms
 
GIS and Agent-based modeling: Part 2
GIS and Agent-based modeling: Part 2GIS and Agent-based modeling: Part 2
GIS and Agent-based modeling: Part 2
 
Agent Based Modeling and Simulation - Overview and Tools
Agent Based Modeling and Simulation - Overview and ToolsAgent Based Modeling and Simulation - Overview and Tools
Agent Based Modeling and Simulation - Overview and Tools
 
GIS and Agent-based modeling: Part 1
GIS and Agent-based modeling: Part 1GIS and Agent-based modeling: Part 1
GIS and Agent-based modeling: Part 1
 
Agent-Based Modeling & Python @ PyData DC 2016
Agent-Based Modeling & Python @ PyData DC 2016Agent-Based Modeling & Python @ PyData DC 2016
Agent-Based Modeling & Python @ PyData DC 2016
 

Similar to Python Puzzlers Explained

A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUadAccount
 
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
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School ProgrammersSiva Arunachalam
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In RubyRoss Lawley
 
re3 - modern regex syntax with a focus on adoption
re3 - modern regex syntax with a focus on adoptionre3 - modern regex syntax with a focus on adoption
re3 - modern regex syntax with a focus on adoptionAur Saraf
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Pythonpugpe
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slidejonycse
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Python Fundamentals - Basic
Python Fundamentals - BasicPython Fundamentals - Basic
Python Fundamentals - BasicWei-Yuan Chang
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonakaptur
 

Similar to Python Puzzlers Explained (20)

A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
 
Python slide
Python slidePython slide
Python slide
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
 
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!
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Python Tidbits
Python TidbitsPython Tidbits
Python Tidbits
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In Ruby
 
re3 - modern regex syntax with a focus on adoption
re3 - modern regex syntax with a focus on adoptionre3 - modern regex syntax with a focus on adoption
re3 - modern regex syntax with a focus on adoption
 
Pythonic Math
Pythonic MathPythonic Math
Pythonic Math
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Mcq cpup
Mcq cpupMcq cpup
Mcq cpup
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Python Fundamentals - Basic
Python Fundamentals - BasicPython Fundamentals - Basic
Python Fundamentals - Basic
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
 

Recently uploaded

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 

Recently uploaded (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 

Python Puzzlers Explained

  • 2. Introduction Eight Python Puzzles Short Python program with curious behaviour What is the output? (multiple choice) The correct answer given How to fix the problem (if there was one) The moral of the story What will be covered Language and core libraries Python 2.6 & 3.x (some puzzles apply to 2.6 only)
  • 3. 1. Exceptional Circumstances try: raise NameError('some_name') except TypeError, NameError: print ('caught exception NameError') except Exception: pass
  • 4. 1. What is the output? try: raise NameError('some_name') except TypeError, NameError: print ('caught exception NameError') except Exception: pass (a) caught exception NameError (b) SyntaxError: invalid syntax (c) <no output> (d) caught exception TypeError
  • 5. 1. What is the output? (a) caught exception NameError (b) SyntaxError: invalid syntax (c) <no output> (d) caught exception TypeError
  • 6. 1. A closer look try: raise NameError('some_name') except TypeError, NameError: print ('caught exception NameError') except Exception: pass
  • 7. 1. How do you fix it? try: raise NameError('some_name') except (TypeError, NameError): print ('caught exception NameError') except Exception: pass >>> caught exception NameError
  • 8. 1. The moral of the story When catching multiple exceptions in a single except clause you must surround them in parentheses This problem is non-existent problem in Python 3.x because the problematic syntax is not permitted: except SomeException, variable # not valid 3.x syntax except SomeException as variable
  • 9. 2. Final Countdown seconds = 10 for i in range(10): --seconds if seconds: print('Wait for it.', seconds) else: print('Happy New Year!', seconds)
  • 10. 2. What is the output? seconds = 10 for i in range(10): --seconds if seconds: print('Wait for it.', seconds) else: print('Happy New Year!', seconds) (a) ('Wait for it.', 10) (b) -10 (c) SyntaxError: invalid syntax (d) ('Happy New Year!', 0)
  • 11. 2. What is the output? (a) ('Wait for it.', 10) (b) -10 (c) SyntaxError: invalid syntax (d) ('Happy New Year!', 0)
  • 12. 2. A closer look seconds = 10 for i in range(10): --seconds if seconds: print('Wait for it.', seconds) else: print('Happy New Year!', seconds)
  • 13. 2. How do you fix it? seconds = 10 for i in range(10): seconds -= 1 if seconds: print('Wait for it.', seconds) else: print('Happy New Year!', seconds) >>> ('Happy New Year!', 0)
  • 14. 2. The moral of the story There is no -- or ++ operator in Python to achieve that effect use -= 1 and += 1 --seconds is actually the same as -(-seconds)
  • 15. 3. Local News def news(headline): sports = 'Soccer' for story in locals(): print(locals()[story]) news('Politics')
  • 16. 3. What is the output? def news(headline): sports = 'Soccer' for story in locals(): print(locals()[story]) news('Politics') (a) Politics Soccer (b) {'sports': 'Soccer'} (c) Soccer (d) RuntimeError: dictionary changed size during iteration
  • 17. 3. What is the output? (a) Politics Soccer (b) {'sports': 'Soccer'} (c) Soccer (d) RuntimeError: dictionary changed size during iteration
  • 18. 3. A closer look def news(headline): sports = 'Soccer' for story in locals(): print(locals()[story]) news('Politics')
  • 19. 3. How do you fix it? def news(headline): sports = 'Soccer' stories = locals() for story in stories: print(stories[story]) news('Politics') >>> Politics Soccer
  • 20. 3. The moral of the story When locals() is invoked it updates and returns a dictionary representing the current local symbol table You should never attempt to update the locals dictionary, however if you need to access it's contents in a loop assign it to another name first
  • 21. 4. TGIF days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] weekend = enumerate(days)[5:] for day in weekend: print(day[0], day[1])
  • 22. 4. What is the output? days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] weekend = enumerate(days)[5:] for day in weekend: print(day[0], day[1]) (a) (5, 'Sat') (6, 'Sun') (b) ('Sat', 'Sun') (c) TypeError: object is unsubscriptable (d) (5, 6)
  • 23. 4. What is the output? (a) (5, 'Sat') (6, 'Sun') (b) ('Sat', 'Sun') (c) TypeError: object is unsubscriptable (d) (5, 6)
  • 24. 4. A closer look days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] weekend = enumerate(days)[5:] for day in weekend: print(day[0], day[1])
  • 25. 4. How do you fix it? days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] weekend = list(enumerate(days))[5:] for day in weekend: print(day[0], day[1]) >>> (5, 'Sat') (6, 'Sun')
  • 26. 4. The moral of the story The enumerate built-in function is a generator, that is it returns an iterator Iterators are not sequences therefore they cannot be indexed or sliced: If you need to index or slice an iterator you must first convert it to a list, this loads the entire dataset into memory Generators can represent infinite chain of values for example itertools.count(), these cannot be meaningfully sliced in reverse
  • 27. 5. Rabbits everywhere a, b = 0, 1 def fibonacci(n): for i in range(n): a, b = b, a + b return a fib8 = fibonacci(8) print(fib8)
  • 28. 5. What is the output? a, b = 0, 1 def fibonacci(n): for i in range(n): a, b = b, a + b return a fib8 = fibonacci(8) print(fib8) (a) UnboundLocalError: local variable (b) 21 (c) 1 (d) 0
  • 29. 5. What is the output? (a) UnboundLocalError: local variable (b) 21 (c) 1 (d) 0
  • 30. 5. A closer look a, b = 0, 1 def fibonacci(n): for i in range(n): a, b = b, a + b return a fib8 = fibonacci(8) print(fib8)
  • 31. 5. How do you fix it? a, b = 0, 1 def fibonacci(n): global a, b for i in range(n): a, b = b, a + b return a fib8 = fibonacci(8) print(fib8) >>> 21
  • 32. 5. The moral of the story The issue is local variable optimisation. If a variable is assigned in a function it is a local variable, the bytecode generated to access it is different to that for global variables. A variable in a function can either be local or global, but not both. Do not mix up global and local names in this way, it is confusing and problematic.
  • 33. 6. The Whole Truth w = False h = [] o = 0, l = None e = {} print(any((w, h, o, l, e)))
  • 34. 6. What is the output? w = False h = [] o = 0, l = None e = {} print(any((w, h, o, l, e))) (a) True (b) (w, h, o, l, e) (c) (False, [], 0, None, {}) (d) False
  • 35. 6. What is the output? (a) True (b) (w, h, o, l, e) (c) (False, [], 0, None, {}) (d) False
  • 36. 6. A closer look w = False h = [] O = 0, l = None e = {} print(any((w, h, o, l, e)))
  • 37. 6. How do you fix it? w = False h = [] O = 0 l = None e = {} print(any((w, h, o, l, e))) >>> False
  • 38. 6. The moral of the story The comma is the tuple constructor, not the parentheses Though it is not required it is generally considered good style to use parentheses when creating a tuple: (0,) is better than 0,
  • 39. 7. Double or Nothing def double(items, doubles=[]): for item in items: doubles.append(item * 2) return doubles numbers = double([1, 2, 3]) words = double(['one', 'two', 'three']) print(words)
  • 40. 7. What is the output? def double(items, doubles=[]): for item in items: doubles.append(item * 2) return doubles numbers = double([1, 2, 3]) words = double(['one', 'two', 'three']) print(words) (a) [2, 4, 6, 'oneone', 'twotwo', 'threethree'] (b) ['oneone', 'twotwo', 'threethree'] (c) TypeError: unsupported operand type(s) for * (d) [2, 4, 6]
  • 41. 7. What is the output? (a) [2, 4, 6, 'oneone', 'twotwo', 'threethree'] (b) ['oneone', 'twotwo', 'threethree'] (c) TypeError: unsupported operand type(s) for * (d) [2, 4, 6]
  • 42. 7. A closer look def double(items, doubles=[]): for item in items: doubles.append(item * 2) return doubles numbers = double([1, 2, 3]) words = double(['one', 'two', 'three']) print(words)
  • 43. 7. How do you fix it? def double(items, doubles=None): if doubles is None: doubles = [] for item in items: doubles.append(item * 2) return doubles numbers = double([1, 2, 3]) words = double(['one', 'two', 'three']) print(words) >>> ['oneone', 'twotwo', 'threethree']
  • 44. 7. The moral of the story Do not use mutable types as default arguments Default arguments are evaluated when the function is defined not when the function is called If you want to use a mutable type as a default argument, set the default to None and initialise it properly inside the function
  • 45. 8. Evening Out the Odds nums = [01, 02, 03, 04, 05, 06, 07, 08, 09, 10] evens = [] for num in nums: if num % 2 != 0: # is the number odd evens.append(num + 1) print(evens)
  • 46. 8. What is the output? nums = [01, 02, 03, 04, 05, 06, 07, 08, 09, 10] evens = [] for num in nums: if num % 2 != 0: # is the number odd evens.append(num + 1) print(evens) (a) [2, 4, 6, 8, 10] (b) SyntaxError: invalid token (c) [02, 04, 06, 08, 10] (d) [2, 2, 4, 4, 6, 6, 8, 8, 10, 10]
  • 47. 8. What is the output? (a) [2, 4, 6, 8, 10] (b) SyntaxError: invalid token (c) [02, 04, 06, 08, 10] (d) [1, 2, 3, 4, 5]
  • 48. 8. A closer look nums = [01, 02, 03, 04, 05, 06, 07, 08, 09, 10] evens = [] for num in nums: if num % 2 != 0: # is the number odd evens.append(num + 1) print(evens)
  • 49. 8. How do you fix it? nums = [01, 02, 03, 04, 05, 06, 07, 010, 011, 012] evens = [] for num in nums: if num % 2 != 0: # is the number odd evens.append(oct(num + 1)) print(evens) >>> ['02', '04', '06', '010', '012']
  • 50. 8. The moral of the story In Python 2.x a leading 0 specifies an octal literal If you want to work with octal numbers remember the valid digits are 0 though 7 In Python 3.x octal literals are specified using 0o, which removes the ambiguity 01 # not valid 3.x syntax 0o1