96 Fun Facts About Python Programming
Learn something new, then test yourself with the quiz.
Know these facts? Prove it.
Take the 96-question quizWhich keyword chains a second test onto an `if` statement in Python?
`elif` is short for 'else if', and a ladder of elif branches was Python's stand-in for the switch statement of other languages until `match` arrived in version 3.10.
Which keyword ends a function call and hands a value back to the caller?
`return` ends the function and passes its value to the caller; a function that falls off the end without one returns None, and `exit` is not a keyword at all.
Van Rossum began Python as a hobby project to fill which holiday break in 1989?
Christmas: with his office closed for the week, van Rossum wanted a 'hobby' project to keep him occupied, and he posted the first public code just over a year later.
Which Python Enhancement Proposal is the language's official style guide?
PEP 8 rests on van Rossum's insight that code is read much more often than it is written, so it fixes details such as a 79-character line limit and snake_case names to make everyone's code look alike.
How does Python define code blocks, unlike languages that use curly braces?
Indentation marks out the blocks, and the interpreter is strict about it: Python 3 refuses to run a file whose tabs and spaces are mixed inconsistently, raising TabError.
What is the standard package installer for Python called?
pip has shipped inside Python's own installers since version 3.4, so the tool that fetches packages rarely has to be fetched itself; npm, gem and apt do the same job for JavaScript, Ruby and Debian.
Which Python data type is mutable?
List: `nums[0] = 9` changes a list in place, while the same assignment on a tuple or a string raises TypeError, because those types can never be altered once created.
In CPython, what does the Global Interpreter Lock (GIL) actually do?
The GIL lets only one thread run Python code at a time, which is why CPU-heavy programs spread work across separate processes instead; Python 3.13 added an experimental build that can switch the lock off.
Which OOP principle bundles data and the methods that operate on it into a single class?
Encapsulation bundles attributes and methods into one class and hides the object's internal state; Python signals 'private' only by convention, with a leading underscore.
In Python, `bool` is a subclass of which other built-in type?
`int`: True and False are just the integers 1 and 0 in disguise, so `True + True` evaluates to 2 and adding up a run of comparisons counts how many were true.
Which 'fully loaded' Python web framework handles authentication, admin and RSS out of the box?
Django ships so much because it was built in a newsroom, where developers had only hours to turn an idea into a live site; hence its tagline, 'the web framework for perfectionists with deadlines'.
What character is used to denote a single-line comment in Python?
The hash sign, #, makes the interpreter skip the rest of the line, with one exception: a comment such as `# -*- coding: latin-1 -*-` on the first or second line is read to learn the file's encoding.
Which of these aphorisms really is a line of 'The Zen of Python'?
Readability counts is one of 19 aphorisms Tim Peters posted in 1999; Perl's motto about more than one way is the line the Zen contradicts, asking for 'one-- and preferably only one --obvious way to do it'.
Which library supplies the fast multi-dimensional arrays that most of Python's scientific stack builds on?
NumPy's arrays beat plain lists because their element-by-element loops run in pre-compiled C, and pandas and Matplotlib both lean on them rather than reinventing the array.
Why was Python 2's retirement postponed from 2015 to 2020?
Many users had not moved to Python 3 by 2014, so the core team gave Python 2 five more years; support ended on 1 January 2020, with a last release, 2.7.18, bundling the final fixes that April.
Which keyword begins a function definition in Python?
`def` is an executable statement rather than a declaration: Python runs it when reached and binds the name to a new function object, so a function can be defined inside an `if` or inside another function.
What does the Python expression `5 + 2 * 3` evaluate to?
11, because * binds tighter than +, so Python works out 2 * 3 first; wrap the sum in parentheses, `(5 + 2) * 3`, and the same numbers give 21.
Which of these is a legal variable name in Python?
`total_2` is legal because digits are allowed anywhere except the first position; `2nd_total` starts with one, `my-total` reads as a subtraction, and `while` is a reserved keyword.
Which `open()` mode opens a file for writing and wipes any existing contents first?
'w' truncates an existing file and creates one if none exists, so opening the wrong path silently destroys data; 'a' also writes but appends, and 'x' refuses to touch a file that is already there.
What does a Python class's `__init__` method do?
`__init__` sets up a new object's attributes, but it does not create the object: `__new__` has already built the instance by the time `__init__` is called to fill it in.
Which keyword is used in Python to create a generator function?
`yield` hands back one value and freezes the function where it stands, resuming on the next request, so a generator can walk a huge or even endless sequence without holding it all in memory.
What is `super()` used for in Python?
`super()` lets a subclass call a parent class's methods without naming the parent, so swapping the base class later means editing one line rather than every call.
What does a Python decorator do?
A decorator wraps a function to extend or alter its behaviour: writing `@timer` above a function is shorthand for `func = timer(func)`, which is how the built-in staticmethod and classmethod are applied.
What does Python do at runtime if a function annotated `x: int` gets a string?
Python ignores the hint and runs the call: annotations are stored on the function but never enforced, so catching the mismatch is left to outside checkers and editors.
Which built-in type lets a set be stored as an element of another set?
`frozenset` is hashable because it can never change after creation, so Python lets it sit inside another set; put an ordinary set there and you get TypeError for an unhashable type.
What does `'hello'[-1]` evaluate to in Python?
`'o'`: a negative index counts back from the end, so -1 is always the last item and -2 the one before it; only an index beyond either end raises IndexError.
What does Python's `enumerate()` do to an iterable?
`enumerate()` pairs each item with a running count, starting at 0 unless told otherwise, so a loop gets position and value together without keeping a counter of its own.
In Python's `asyncio` library, what is the role of an 'event loop'?
The event loop runs tasks, callbacks and network I/O on a single thread, switching to another task whenever one pauses at an await, which is how one thread can serve many connections at once.
What is the purpose of `pass` in Python?
`pass` does nothing at all: its only job is to stand in where a statement is required, so an empty function, class or loop body still parses while you work out the rest.
Which operator is used for exponentiation in Python?
The double asterisk, **, raises to a power, so `2 ** 3` is 8; the caret is a trap, because in Python `^` means bitwise XOR and `2 ^ 3` quietly gives 1.
What is a 'comprehension' such as `[x*2 for x in nums]` in Python?
A concise way to build a collection: the expression runs once per item and an optional `if` filters them, so a single line replaces a loop that appends results one by one.
What will be the result of `type([])` in Python?
`<class 'list'>`: the brackets build an empty list, and the word 'class' is there because Python 2.2 merged built-in types with classes, which is why you can subclass the built-in types yourself.
Which of the following statements correctly handles an error in Python?
`try: ... except ErrorType: ...` is the pattern: risky code goes under try, because Python favours attempting first over checking beforehand, a style its glossary calls EAFP, 'easier to ask for forgiveness than permission'.
What does the `if __name__ == '__main__':` check let a Python file do?
The check lets a file run code only when executed directly: Python sets `__name__` to '__main__' for the script it was launched with, but to the module's own name when the file is imported.
Which built-in function waits for the user to type a line in Python 3?
`input()` always hands back a string, so typing 42 gives '42' until you convert it with int(); Python 2 called this function raw_input(), and its own input() evaluated whatever was typed.
After `import math`, which call gives the square root of 9?
`math.sqrt(9)` is the call, because `import math` binds only the module's name and leaves sqrt inside the module's own namespace, so a function of yours that is also called sqrt can never clash with it.
What is the output of `len('New York')` in Python?
8: len() counts every character, and the space is a character like any other, so the seven letters of 'New York' come to eight.
Which built-in type stores data as key-value pairs?
`dict` maps each unique key to a value; since Python 3.7 it is guaranteed to keep insertion order, a promise that began as a side effect of a memory-saving redesign in CPython 3.6.
What does the `break` statement do inside a `for` or `while` block?
`break` terminates the loop entirely, and it also skips the loop's `else` clause, which runs only when a loop finishes without hitting a break.
Which standard-library module supplies the classes for arithmetic on dates and times?
`datetime` supplies date, time and timedelta classes, so subtracting one date from another yields a timedelta you can read in days; `calendar` lays out months and `timeit` only times snippets of code.
What is a 'docstring' in Python?
A docstring is a string that opens a function, class or module; unlike a comment, the interpreter keeps it as `__doc__`, which is what help() prints.
What does the built-in `map()` do with an iterable in Python?
map() applies a function to every item, but lazily: in Python 3 it returns an iterator, so nothing is computed until you loop over it or collect the results.
Which of these is the correct syntax for starting a new type definition in Python?
`class MyClass:` needs no parentheses or base: a class written this way silently inherits from `object`, so in Python 3 everything you define shares one common ancestor.
What does Python do when an integer result is too big for 64 bits?
Python keeps it exact at any size, borrowing more memory as the number grows, so the factorial of 30 prints all 33 of its digits and integer arithmetic never overflows.
What does the expression `10 // 3` evaluate to in Python?
`3`: the // operator is floor division, so it rounds down to a whole number, and with a negative operand it rounds toward minus infinity, which is why `-7 // 2` gives -4.
What is the primary benefit of using a `virtual environment` in Python?
A virtual environment exists to keep each project's packages isolated, so two projects on one machine can depend on different versions of the same library without either breaking.
Running `import antigravity` in Python opens a comic from which webcomic?
XKCD strip 353 jokes that flying in Python takes nothing more than `import antigravity`, so the developers added a real module of that name which opens the strip in your web browser.
What is the purpose of the `zip()` function in Python?
zip() is there to pair up items from several iterables; it stops at the shortest, silently dropping the leftovers, unless you pass strict=True, added in Python 3.10 to raise an error instead.
Which method takes out the item at a given index and hands it back to you?
`pop()` removes the item at a given index and returns it; with no index it takes the last one, so append() and pop() together give you a ready-made stack, while `remove()` deletes by value.
What does the `continue` statement do in a loop?
`continue` skips ahead to the next iteration, abandoning whatever is left of the current pass: a `for` loop fetches its next item, and a `while` loop goes back to re-test its condition.
Which of these literals creates a set in Python?
`{1, 2, 3}` (curly braces) makes a set, but empty braces are the exception: `{}` is an empty dictionary, so an empty set has to be written `set()`.
What is the result of joining the literals `"hi"` and `" mom"` with `+` in Python?
`"hi mom"`: + joins strings exactly as written, so the space inside `" mom"` is the only one you get; Python never adds one, and trying to add a number to a string raises TypeError instead.
Which built-in exception does Python raise when code uses a variable that was never defined?
`NameError` is raised only at the moment the unknown name is reached, not before the program starts, so a typo in a rarely used branch can hide until that line finally runs.
What does the conventional first parameter `self` refer to inside a Python class body?
The object the call was made on arrives as `self` because `obj.method(x)` is really shorthand for `Class.method(obj, x)`; the name is not a keyword, and any other would work.
Which Python module handles operating system tasks like file paths and environment variables?
`os` wraps whatever system it runs on, so one script works on Windows and Linux alike: `os.environ` exposes environment variables, and `os.path.join` picks the right path separator for you.
How do you stop a mutable fallback value like `cache={}` being shared between calls?
Default to None and build it inside the function: a default is evaluated only once, when the function is defined, so every call that omits the argument would otherwise reuse and mutate the very same object.
A class's MRO decides where Python looks first among its ancestors: what does MRO stand for?
Method Resolution Order is the sequence Python follows when it looks a method up through a class's ancestors; since version 2.3 it has used the C3 algorithm, so in a diamond-shaped family the shared base is reached only once.
Which data type is optimized for fast lookup of unique elements and does not allow duplicates?
Set: it keeps its items in a hash table, so a membership test such as `x in s` does not slow down as the set grows, and `set(names)` is the classic one-liner for stripping duplicates.
What is the `with` statement for in Python?
Guaranteed clean-up, such as closing a file, is the point of `with`: the context manager's exit code runs when the block ends, even if an exception is thrown, so a file opened this way is never left open.
What is a 'metaclass' in Python?
A metaclass is a class whose instances are classes: the default one is `type`, which is why `type(str)` reports `<class 'type'>`, and a library can supply its own to change how classes get built.
Python was designed as a successor to which language that van Rossum had helped develop at CWI?
ABC, a teaching language from CWI, could not be extended, which van Rossum called one of its biggest problems, so he designed Python to be extensible from the start.
What is the nickname of the := syntax introduced in Python 3.8?
The walrus operator, so called because := looks like eyes and tusks, arrived with PEP 572 in Python 3.8; it assigns a value inside a larger expression so a result can be tested and reused in one line.
What informal title did Guido van Rossum hold over Python until he stepped down on 12 July 2018?
Benevolent Dictator for Life, or BDFL, was the title; after the fight over PEP 572 he wrote that he never wanted to battle so hard for a proposal again and gave himself a 'permanent vacation' from the role.
What kind of tool was Mondrian, which van Rossum wrote at Google and named after a Dutch painter?
A code-review tool: Mondrian, named for Piet Mondrian, ran inside Google only, so when van Rossum made a public successor he kept the theme and called it Rietveld, after the Dutch designer Gerrit Rietveld.
Which company did van Rossum join in November 2020, coming out of retirement?
Microsoft gave him the freedom to pick his own project when he ended a brief retirement, and he chose to make CPython faster, with a small team funded by the company.
What was the name of Google's 2009 project to speed up the Python interpreter five-fold using LLVM?
Unladen Swallow fell short of its fivefold goal, and the plan to merge it into CPython was withdrawn; the name nods to the argument about a swallow's airspeed in Monty Python and the Holy Grail.
Which feature, borrowed from Haskell, did Python 2.0 introduce?
List comprehensions headlined Python 2.0, yet its own release notes say the most important change may not have been to the code at all: development moved to SourceForge, opening bug reports and patches to everyone.
Python 3.0 broke much old code by turning which everyday statement into a function?
`print` became an ordinary function in Python 3.0, so the old form `print 'hi'` turned into a syntax error overnight; in exchange it gained keyword options such as sep and end.
What body did Python's core developers first elect in early 2019 to lead the project?
A five-member Steering Council won out over rival plans such as a three-person 'Trio of Pythonistas', and its first election, held in early 2019, put van Rossum himself back as one of the five.
Which code-migration utility came bundled with Python itself until its removal in version 3.13?
2to3 was retired because its old-style parser could no longer read modern Python: syntax added in 3.10, such as the match statement, was beyond it, so it was deprecated in 3.11 and removed in 3.13.
By van Rossum's account, Python got lambda, map, filter and reduce from a contributor who missed them from which language?
Lisp: van Rossum recalled that the four arrived as patches from, he believed, a Lisp hacker who missed them; years later he tried to drop them from Python 3 and managed only to move reduce into functools.
Which prefix letter lets a Python string literal evaluate expressions written inside curly braces?
f: since Python 3.6 an f-string works out whatever sits inside its braces on the spot, so f'{2 + 3}' produces '5'; r marks a raw string and b a bytes literal, while u is a leftover from Python 2.
Instead of foo and bar, which placeholder names are traditional in Python literature?
spam and eggs come from the Monty Python cafe sketch in which almost every dish includes Spam; the official tutorial says that references to the troupe's skits are 'not only allowed, it is encouraged'.
What indent size does Python's official style guide recommend?
Four spaces, and the same guide settles the old tabs-or-spaces argument: spaces are the preferred method, with tabs tolerated only in code that already uses them.
Which external tool uses Python's optional type annotations to catch errors?
mypy reads the annotations and reports mismatches before the code ever runs; Jukka Lehtosalo began it in 2012, and Python's official type-hint standard, PEP 484, says it was strongly inspired by mypy.
What does `-1 % 7` evaluate to in Python, where % always takes the divisor's sign?
6: Python's % takes the sign of the divisor, so stepping back one day from index 0 with `(day - 1) % 7` lands on 6 with no special case; the same expression in C gives -1.
Which symbol does Python reserve as its matrix-multiplication operator?
The at sign, @, was added in Python 3.5 for numerical code, so a chain of matrix products reads `A @ B @ C` instead of nested function calls; no built-in type implements it at all.
What does 5/2 evaluate to in Python 3?
2.5: Python 3 made / true division, which always returns a float, so even 4/2 gives 2.0; Python 2 quietly truncated 5/2 to 2, a trap PEP 238 was written to remove.
Which feature, added in Python 3.11, lets concurrent tasks report every failure rather than only the first?
Exception groups bundle several unrelated errors into one object, and asyncio's TaskGroup, added in the same release, relies on them: when sibling tasks fail, it raises all their errors together as a single group.
CPython first compiles source code into what before it is interpreted?
Bytecode: CPython compiles each module to instructions for its own virtual machine and caches them as .pyc files in __pycache__ folders, which is why it counts as both compiler and interpreter.
Which conference does the Python Software Foundation run as its leading community event?
PyCon US is produced and underwritten by the foundation itself, and the revenue it brings in is, in the PSF's words, essential to its community support, so the gathering also helps pay for the grants.
IronPython, a C# implementation started by Jython's creator Jim Hugunin, runs Python on which platform?
.NET: Hugunin had already put Python on the Java platform with Jython, and IronPython does the same for the runtime behind C#, so Python scripts can use .NET libraries and other .NET languages can call Python code.
Which Python microframework began as Armin Ronacher's April Fool's joke in 2010?
Flask's name plays on Bottle, an earlier microframework; the prank was a fake framework poking fun at single-file ones, and it drew so much interest that Ronacher went on to build a real one.
Django, the framework created at the Lawrence Journal-World newspaper, is named after what?
A Belgian-born jazz guitarist, Django Reinhardt, gave the framework its name: co-creator Adrian Holovaty plays guitar in Reinhardt's style himself, and the code went public in July 2005.
The pandas library takes its name from which econometrics term?
Panel data, an econometrics term for observations of the same subjects over many time periods, gave pandas its name, which also plays on 'Python data analysis'; Wes McKinney built it at an investment firm to analyse financial data.
Matplotlib's name blends 'plot' and 'library' with which numerical software?
MATLAB: John D. Hunter began matplotlib in 2003 to replicate MATLAB's plotting in Python; the Event Horizon Telescope team used it while producing the first black-hole image in 2019.
Project Jupyter's name refers to which three core programming languages?
Julia, Python and R were the three languages the 2014 spin-off from IPython first targeted, hence 'Jupyter'; the name and logo also nod to Galileo's notebooks on the moons of Jupiter.
The Requests HTTP library is implemented as a wrapper around which other library?
urllib3 does the heavy lifting, such as connection pooling, beneath Requests' friendlier interface; Kenneth Reitz released Requests in 2011 and handed control of it to the Python Software Foundation in 2019.
By what Monty Python-inspired nickname is the Python Package Index also known?
The Cheese Shop takes its name from the Monty Python sketch about a cheesemonger who turns out to have no cheese at all.
Tkinter translates its calls into commands for an interpreter of which embedded language?
Tcl: Tkinter's calls are translated into Tcl commands and fed to an interpreter embedded in the Python process, which is why a GUI mistake surfaces as an exception called TclError.
Python's bundled beginner editor is thought to partly honour which Monty Python member?
Eric Idle: van Rossum has joked that the editor is 'really named after' him, though officially IDLE stands for Integrated Development and Learning Environment, a reading its developers settled on in 2015.
Which beginner-friendly fork of MicroPython does Adafruit maintain?
CircuitPython boards show up as a small USB drive, so a beginner edits the code.py file in any text editor and the program reloads on save, with nothing else to install.
The pytest testing framework originated inside which alternative Python implementation?
PyPy: pytest was born inside that project because its developers put a heavy focus on testing and wanted tests that were easier to write; the tool was still called py.test until 2016.
The HTML parser Beautiful Soup is named after a poem from which book?
Alice in Wonderland: the Mock Turtle sings 'Beautiful Soup' in Lewis Carroll's book, and the parser's home page keeps the joke going under another of his lines, 'We called him Tortoise because he taught us'.
Scrapy builds crawling projects around self-contained crawlers it calls what?
Spiders are the classes that tell Scrapy which pages to request and how to parse them; because requests are scheduled asynchronously, a spider carries on with other pages while slow responses trickle in.
Mojo, a Python-like language, comes from a firm co-founded by which language's architect?
Swift's creator Chris Lattner, who also started LLVM, co-founded Modular, the firm behind Mojo; the language builds on the MLIR compiler framework so that it can target GPUs and other accelerators.
Think you know Python Programming?
Put these facts to the test with the interactive quiz.
Take the 96-question quizTeaching Python Programming?
Make a custom quiz — handy for classrooms and study groups.
Make a quiz on anything