A Tour of Python 3
A Tour of Python 3
300+ ready-to-use examples guiding you from the very beginning. Including Python 3.8
About the Book
This book is an overview of the features of the Python programming language. In the 36 chapters, there are more than 300 small programs, where you will learn many details about all main aspects of programming in this language.
The book is primarily intended to be used with the modern compiler of the third version of the language and highlights the differences between Python 2 and Python 3 where that makes sense. A number of sections explain the new features appeared in Python 3.8.
In general, the difficulty of the examples increases to the end of the book, but you can read the chapters and the sections in any order.
Table of Contents
Part 1
Chapter 1. Printing and Formatting
Hello, World!
Formatted output
Formatting strings
F-strings
More on formatting
Formatted strings with named arguments
Echo
Another echo
Using pprint
Printing in Python 2 vs Python 3
Format precision
Emoji
Chapter 2. Python Code
Indentation
Namespaces
Chapter 3. Variables
Variables
Variable names
Deleting a variable
Dummy variable
The global
keyword
How to swap the values
Star assignment
Chapter 4. Numbers
Integer vs floating-point division
Using complex numbers
Decimal calculations
Complex roots
Big integers
Size of an integer
Fractions
Equal floats
Round a number
Chapter 5. Strings
The length of a string
Multi-line strings
Indexing a string character
Taking the last character
The second-to-last character
Getting a substring
String repetition
Reversing a string
Splitting a string
Raw strings
More on raw strings
Removing accents from a string
Removing \n
A more complex stripping
Using lambdas to strip a line
ASCII values of the characters
Character Unicode names
Using casefolding
Unicode normalization
Split words
Chapter 6. Operators
Non-trivial assignments
Augmenting assignment
The +
operator
The in
keyword
Redefine +
More on redefining +
Walrus :=
Using *
Chapter 7. Functions
Creating a function
Default parameter values
Named arguments
More on default values
Passing a list to a function
Multiple return from a function
Return a tuple
Arbitrary number of function arguments
Using kwargs
Position of the variadic arguments
Positional parameters only
Default parameters are frozen
Simple documentation
Annotations
LRU cache
Decorators
Double decorator
Chapter 8. Built-in Functions
The built-in function len
reverse
and reversed
any
and all
Using enumerate
The map
function
The id
function
Using filter
Custom sort function
More on sort key
Part 2
Chapter 9. Types
Data types
Type casting
Tuples vs lists
None
Ordering None
is
vs ==
A tuple with a single element
Create a tuple
Chapter 10. Lists
Pushing to an array and popping back
Negative index
Last elements
Appending data to a list
Remove an item from a list
Another way of removing an element
Copying a list
Find a position in a list
Reverse a list
Rotating a list
Shuffle a list
Join list items
Clone a list
More on cloning lists
Append vs. extend
Beware of deleting items
Chapter 11. Dictionaries
Iterating a dictionary
The items
method of dictionaries
Keys and values of a dictionary
Using get
with dictionaries
Iterating over a dictionary
Sort by value
Merge dictionaries
More on merging dictionaries
Lists to dictionaries
Invert a dictionary
Chapter 12. Sets
Sets
Subtracting sets
Working with sets
Frozen sets
Set operations
Chapter 13. Ranges
Ranges
An open range
More on ranges
Counting backwards
Range properties
Sum of a range
Ranges and strings
Chapter 14. Regular Expressions
Getting a number using regular expressions
Date and regular expressions
Case-insensitive matching
Unicode digits
Compiled regular expressions
Extract the numbers and the words
Chapter 15. Date and Time
Daylight saving time
Leap year
Date difference
Weekday today
Measuring time
Another way of measuring time
Part 3
Chapter 16. Control Flow
Boolean if
The elif
keyword
Chained condition
Empty values
A string with a zero
for
… in
Using for
… in
with strings
The while
loop
Using else
in a while
loop
More on else
in a loop
Breaking a while
loop
Continuing a while
loop
Using pass
in loops
Variable state after the loop
Using finally
for
and else
Ternary operator
More on conditional statements
Breaking nested loops
Boolean shortcuts
if
vs. in
Functions in for
Chapter 17. Command Line
Getting user input
Command-line arguments
argv[0]
Integer as input
Read a password
Clear screen
Chapter 18. Modules
Installing a module
import
vs local
Testing the main code
Module alias
Path to the module
Chapter 19. Files
Reading a file
Write to a file
File size
Does the file exist?
Using with
to open files
Open two files in a single with
Using writelines
Temporary file
Compare files
Reading CSV
Remove empty lines
Get the line N from a file
Another way to read the Nth line
Last line of a file
Chapter 20. Working with the System
Using sys
Printing to STDERR
React to Ctlr+C
System calls
Capture system output
Capture lines
C interface
Fortran interface
Chapter 21. Exceptions
Using assert
Custom Exception
Exception with a message
Part 4
Chapter 22. List and Map Comprehensions
List comprehensions
Map comprehensions
Using list comprehension as a filter
Nested for
s in a list comprehension
Chapter 23. Operations with Lists
Adding up lists
Reversing a list
Add up two lists
How to zip the lists
Count list items
Increment items in a list
Another way to increment items in a list
Difference of the lists
Removing duplicates from a list
Another method of de-duplicating a list
Merge the lists and preserve the order
Another way of merging lists
Print indices and values of a list
Concatenate a list of strings
Chapter 24. Multi-dimensional Lists
Multi-dimensional lists
List of tuples
Select sublists based on criteria
Version 3 of converting list of tuples
Sort the lists by their second item
Nested subscripting
More on subscripting nested lists
Flatten a list
Flatting a list with iterators
Transpose a matrix
Transpose a matrix
Hello, World! with NumPy
Transpose a matrix in NumPy
The T
attribute in NumPy
Chapter 25. Iterators and Generators
Iterators
Using yield
Two generators
Custom iterator
Using StopIteration
Customr iterators in a loop
Chapter 26. Functional Programming
Lambda function
Currying
Closure
Closures in Python
Chapter 27. Concurrent programming
Coroutines
Asynchronous coroutines
Run a thread
Thread speed
Part 5
Chapter 28. Object-Oriented Programming
Classes
Class name
Count the objects
Objects to string
Empty objects
Using with
with classes
__init__
and __del__
The @classmethod
and @staticmethod
decorators
Using dir
with objects
Polymorphic methods
Using super
Using dir
with classes
A custom dir
Custom len
Using __repr__
__str__
vs. __repr__
Sorting objects
More on sorting objects
+
as a -
Cimparing objects
Matrix multiplication @
Class operators
Deep copy of a list
Part 6
Chapter 29. Numerical Sequences
Factorial
Recursive factorial
Another recursive factorial
Computing a factorial
Prime numbers
Fibonacci numbers
Armstrong number
Chapter 30. Algorithms
Bubble sort
Quick sort
Multiply by 2
Eratosthenes sieve
Chapter 31. Maths Problems
Euler problem #1
Minimum and maximum
Computing a product
Number of digits
Area of a triangle
More on area of a triangle
A recursive sum
Average value
Mean value
Median value
Compute the value of π
Approaching the value of π with Fraction
s
Chapter 32. String Problems
Strings to integers
Count capitals
Check if is a binary
Keep vowels
Reverse a number
Count letters
Reverse a sentence
Remove double spaces
Spell a number
Word to number
Balanced parentheses
Anagram test
Chapter 33. Interview Problems
Unique random values
Another version of unique randoms
Odd and even
Find a missing number
Another way to find a missing number
Find a duplicate
Calculator
Monte Carlo method
Count bits
Guess the number
Random histogram
Random Gauss
All unique
Find a repeating element
Are all items the same?
Compare the elements in two lists
Print a tree
Pascal’s triangle
Part 7
Chapter 34. Internet and Web
Load a page by URL
Web server
Chapter 35. Graphics
Simple drawing
Openning an image
Image size
Rotate an image
Thumbnails
Thumbnail vs. resize
Pixel’s colour
Chapter 36. Miscellaneous
Using the pickle
module
Working with JSON
UUID
UUID v4
The array
module
MySQL connection
Using memcached
Other books by this author
The Leanpub 60 Day 100% Happiness Guarantee
Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
Now, this is technically risky for us, since you'll have the book or course files either way. But we're so confident in our products and services, and in our authors and readers, that we're happy to offer a full money back guarantee for everything we sell.
You can only find out how good something is by trying it, and because of our 100% money back guarantee there's literally no risk to do so!
So, there's no reason not to click the Add to Cart button, is there?
See full terms...
Earn $8 on a $10 Purchase, and $16 on a $20 Purchase
We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.
(Yes, some authors have already earned much more than that on Leanpub.)
In fact, authors have earnedover $13 millionwriting, publishing and selling on Leanpub.
Learn more about writing on Leanpub
Free Updates. DRM Free.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).
Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.
Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.
Learn more about Leanpub's ebook formats and where to read them