The Self-Taught Programmer - The Definitive Guide To Programming Professionally
The Self-Taught Programmer - The Definitive Guide To Programming Professionally
Title
Part I Introduction to Programming
Chapter 1. Introduction
Chapter 2. Getting Started
Chapter 3. Introduction to Programming
Chapter 4. Functions
Chapter 5. Containers
Chapter 6. String Manipulation
Chapter 7. Loops
Chapter 8. Modules
Chapter 9. Files
Chapter 10. Bringing It All Together
Chapter 11. Practice
Part II Introduction to Object-Oriented Programming
Chapter 12. Programming Paradigms
Chapter 13. The Four Pillars of Object-Oriented Programming
Chapter 14. More Object-Oriented Programming
Chapter 15. Bringing It All Together
Part III Introduction to Programming Tools
Chapter 16. Bash
Chapter 17. Regular Expressions
Chapter 18. Package Managers
Chapter 19. Version Control
Chapter 20. Bringing It All Together
Part IV Introduction to Computer Science
Chapter 21. Data Structures
Chapter 22. Algorithms
Part V Landing a Job
Chapter 23. Best Programming Practices
Chapter 24. Your First Programming Job
Chapter 25. Working on a Team
Chapter 26. Further Learning
Chapter 27. Next Steps
Acknowledgements
Citations
Copyright © 2016 by Cory Althoff.
All rights reserved. This book or any portion thereof may not be reproduced
or used in any manner whatsoever without the express written permission of
the publisher except for the use of brief quotations in a book review.
Version 3
Facebook - https://www.facebook.com/coryalthoff/
Instagram - https://www.instagram.com/coryalthoff
Medium - https://medium.com/@coryalthoff
Get The Self-Taught Programmer Course
goselftaught.com
I dedicate this book to my parents,
Abby and James Althoff,
for always supporting me.
Chapter 1.
Introduction
"Most good programmers do programming not because they expect to get
paid or get adulation by the public, but because it is fun to program."
~Linus Torvalds
Learning a programming language is only part of the battle. There are other
skills you need in order to speak the language of computer scientists. I will
teach you everything I learned on my journey from programming novice to
professional software engineer. I wrote this book to give aspiring
programmers an outline of what they need to know. As a self-taught
programmer, I didn't know what I needed to learn. The introductions to
programming books are all the same. They teach you the basics of how to
program in either Python or Ruby, and send you on your way. The feedback
I've heard from people finishing these books is "What do I do now? I am not
a programmer yet, and I don't know what to learn next." This book is my
answer to that question.
Part III: Introduction to Programming Tools. You learn to use different tools
to take your programming productivity to the next level. At this point, you
are hooked on programming and want to get even better. You will learn more
about your operating system, how to use regular expressions to boost your
productivity, how to install and manage other people's programs, and how to
collaborate with other engineers using version control.
Part V: Landing a Job. The final section is about best programming practices,
getting a job as a software engineer, working on a team, and improving as a
programmer. I provide tips on how to pass a technical interview and work on
a team, as well as advice on how to further enhance your skills.
In The Art of Learning, Josh Waitzkin of Searching for Bobby Fischer fame
describes how he learned how to play chess in reverse. Instead of studying
opening moves, he started learning the endgame (when there are only a few
pieces left on the board) first. This strategy gave him a better understanding
of the game, and he went on to win many championships. Similarly, I think it
is more efficient to learn to program first, then learn theory later, once you
are dying to know how everything works. That is why I wait until Part IV of
the book to introduce computer science theory, and I keep it to a minimum.
While theory is important, it will be even more valuable once you already
have programming experience.
Programming will also make you better at everything else you do. There
aren't many subjects that don't benefit from finely tuned problem-solving
skills. Recently, I had the very tedious task of searching for housing on
Craigslist. I was able to write a program to do the work for me and email me
the results. Learning to program will free you from repetitive tasks forever.
Sticking with It
If you don't have any programming experience and are nervous about making
this journey, I want you to know you are capable of it. There are some
common misconceptions about programmers like they all are great at math.
They aren't. You don't need to be great at math to learn to program, but it
does take hard work. With that said, a lot of the material covered in this book
is easier to learn than you think.
When I was getting started, I used a checklist to ensure I practiced every day,
and it helped me stay focused.
If you need extra help, Tim Ferriss, a productivity expert, recommends the
following technique to stay motivated: give money to a friend or family
member with instructions to return it to you upon completion of your goal
within a given time frame, or donate it to an organization you dislike if you
fail.
There are three popular operating systems for desktop and laptop computers:
Windows, Unix, and Linux. Windows is Microsoft's operating system. Unix
is an operating system created in the 1970s. Apple's current operating system
is based on Unix. From here on out, when I refer to Unix, I am referring to
Apple's desktop operating system. Linux is an open-source operating system
used by the majority of the world's servers. A server is a computer or
computer program that performs tasks, like hosting a website. Open-source
means a company or individual does not own the software and it may be
redistributed and modified. Linux and Unix are both Unix-like operating
systems, which means they are very similar. This book assumes you are
using a computer running Windows, Unix, or Ubuntu (a popular version of
Linux) as your operating system.
Vocabulary
FizzBuzz: A programming test used in interviews to weed out candidates.
Operating system: A program that is the middleman between the physical
components of the computer and you.
Graphical user interface (GUI): The part of your operating system you see
when you look at your computer screen.
Windows: Microsoft's operating system.
Unix: An operating system created in the 1970s. Apple's operating system is
based on Unix.
Linux: An open-source operating system used by the majority of the world's
servers.
Open-source: Software that is not owned by a company or individual, but is
instead maintained by a group of volunteers.
Server: A computer or computer program that performs tasks, like hosting a
website.
Unix-like operating systems: Unix and Linux.
Challenge
1. Create a daily checklist that includes practicing programming.
for me.
Chapter 2.
Getting Started
"A good programmer is someone who always looks both ways before
crossing a one-way street."
~Doug Linder
What Is Programming
Programming is writing instructions for a computer to execute. The
instructions might tell the computer to print Hello, World!, scrape data
from the Internet, or read the contents of a file and save them to a database.
These instructions are called code. Programmers write code in many different
programming languages. In the past, programming was much harder, as
programmers were forced to use cryptic, low-level programming languages
like assembly language. When a programming language is low-level, it is
closer to being written in binary (0s and 1s) than a high-level programming
language (a programming language that reads more like English), and thus is
harder to understand. Here is a simple program written in an assembly
language:
# http://tinyurl.com/z6facmk
global _start
section .text
_start:
mov rax, 1
mov rdi, 1
mov rsi, message
mov rdx, 13
syscall
; exit(0)
mov eax, 60
xor rdi, rdi
syscall
message:
db "Hello, World!", 10
1 # http://tinyurl.com/zhj8ap6
2
3
4 print("Hello, World!")
As you can see, programmers today have it much easier. You won't need to
spend time learning cryptic, low-level programming languages to program.
Instead, you will learn an easy-to-read programming language called Python.
What Is Python
Python is an open-source programming language created by Dutch
programmer Guido van Rossum, named after the British sketch comedy
group Monty Python. One of van Rossum's key insights was that
programmers spend more time reading code than writing it, so he created an
easy-to-read language. Python is one of the most popular and easiest to learn
programming languages in the world. It runs on all the major operating
systems and computers and is used to build web servers, create desktop
applications, and everything in between. Because of its popularity, there is a
significant demand for Python programmers.
Installing Python
To follow the examples in this book, you need to have Python Version 3
installed. You can download Python for Windows and Unix at
http://python.org/downloads . If you are on Ubuntu, Python 3 comes installed
by default. Make sure you download Python 3, not Python 2. Some of the
examples in this book will not work if you are using Python 2.
Python is available for 32-bit and 64-bit computers. If you purchased your
computer after 2007, it is most likely a 64-bit computer. If you aren't sure, an
Internet search should help you figure it out.
Troubleshooting
From this point forward, you need to have Python installed. If you are having
problems installing Python, please skip ahead to Chapter 11 to the section
titled "Getting Help."
Click on the IDLE icon, and a program with the following lines will open
(although this could change, so don't worry if the message is absent or
different):
1 print("Hello, World!")
IDLE might reject code copied from Kindle, other eBooks, or word
processors like Microsoft Word. If you copy and paste code and get an
unexplainable error message, try typing the code directly into the shell. You
must type the code exactly as written in the example, including quotation
marks, parentheses, and any other punctuation.
Saving Programs
The interactive shell is useful for quick computations, testing small bits of
code and writing short programs you don't plan on using again. You can also
use IDLE to save a program for reuse. Start the IDLE application, click "File"
(in the menu bar on the top left of the IDLE editor), then select "New File."
Selecting this option will open up a text editor, which usually has a blank
white background. You can write code in this text editor and save it to run
later. When you run your code, the output will appear in the interactive shell.
You need to save changes while editing code before running it again. Type
the Hello, World! program into the text editor:
Go to "File" again and select "Save As." Name your file "hello_world.py"
and save it. Python file names have to end with .py. Once you've saved your
file, click "Run" (in the menu bar in the top left corner of the IDLE editor),
and select "Run Module." Alternatively, you can press the F5 key command,
the equivalent of selecting "Run Module" from the menu bar. Hello,
World! will print in the interactive shell, as if you had typed this line of
code. But now, since you saved your program, you can run it as many times
as you like.
The program you created is simply a file with a .py extension, located on
your computer wherever you saved it. The name I chose for the file
—"hello_world.py"—is completely arbitrary, you can name the file anything.
Like this example, writing programs in Python simply involves typing text
into files and running them using the interactive shell. Easy, right?
Short examples are best run using the shell, and the text editor is better for
longer programs you want to save and edit. If you make a mistake in your
code in the interactive shell—a typo for example—and the code doesn't work,
you have to type everything over again. Using the text editor lets you save
your work, so if you make a mistake, you simply fix it and rerun the program.
Vocabulary
Programming: Writing instructions for a computer to execute.
Code: The instructions programmers write for a computer to execute.
Low-level programming language: A programming language closer to
being written in binary (0s and 1s) than a high-level programming language.
Assembly language: A type of difficult-to-read programming language.
High-level programming language: A programming language that reads
more like English than a low-level programming language.
Python: The easy-to-read, open-source programming language you will learn
to use in this book. Created by Guido van Rossum and named after the
British sketch comedy group Monty Python.
Challenge
1. Try to print something other than Hello, World!.
Solution: http://tinyurl.com/noeujfu.
example.
Chapter 3.
Introduction to Programming
"It's the only job I can think of where I get to be both an engineer and an
artist. There's an incredible, rigorous, technical element to it, which I like
because you have to do very precise thinking. On the other hand, it has a
wildly creative side where the boundaries of imagination are the only real
limitation."
~Andy Hertzfeld
Our first program printed Hello, World! Let's print it a hundred times.
Type the following code into the interactive shell (print needs to be indented
exactly four spaces):
1 # http://tinyurl.com/h79ob7s
2
3
4 for i in range(100):
5 print("Hello, World!")
Your shell should print Hello, World! a hundred times. Even though
you will probably never need to print Hello, World! a hundred times,
this example shows you how powerful programming is. Can you think of
anything else you can do a hundred times so easily? I can't. That is the power
of programming.
Examples
From now on, code examples will look like this:
1 # http://tinyurl.com/h4qntgk
2
3
4 for i in range(100):
5 print("Hello, World!")
You can run examples from either the shell or a .py file. Be aware that, as I
mentioned earlier, the output from the shell is slightly different so if you are
not getting the same output, that is why. If an example prints an output but
doesn't have the word print in it, you should enter the code into the shell. If
the word print is in an example, you should run the code from a .py file.
Comments
A comment is a line (or part of a line) of code written in English (or another
language), preceded by a symbol telling the programming language you are
using to ignore that line (or part of a line) of code. In Python, the pound
symbol is used to create comments.
1 # http://tinyurl.com/hut6nwu
2
3 # This is a comment
4 print("Hello, World!")
Only write a comment if you are doing something unusual in your code, or
explaining something that is not obvious in the code itself. Use comments
sparingly—do not comment on every line of code you write—save them for
special situations. Here is an example of an unnecessary comment:
1 # http://tinyurl.com/jpzlwqq
2
3
4 # print Hello, World!
5 print("Hello, World!")
It is unnecessary because it is already very clear what the line of code does.
Here is an example of a good comment:
1 # http://tinyurl.com/z52c8z8
2
3
4 import math
5
6
7 # length of a diagonal
8 l = 4
9 w = 10
10 d = math.sqrt(l**2 + w**2)
Even if you understood exactly how this code works, you still might not
know how to calculate the length of a diagonal of a rectangle, so the
comment is useful.
Printing
You are not limited to printing Hello, World! in your programs. You
can print whatever you'd like, as long as you surround it with quotes:
1 # http://tinyurl.com/zh5g2a3
2
3
4 print("Python")
>> Python
1 # http://tinyurl.com/hhwqva2
2
3
4 print("Hola!")
>> Hola!
Lines
Python programs are made up of lines of code. Take a look at this program:
1 # http://tinyurl.com/jq2w5ro
2
3
4 # line1
5 # line2
6 # line3
There are three lines of code. It is useful to refer to each piece of code by the
line it is on. In IDLE, you can go to "Edit" and select "Go to Line" to jump to
a particular line in your program. You can only enter one line of code into the
shell at once. You cannot copy and paste multiple lines.
Sometimes a piece of code is long and takes up more than one line. Code
surrounded by three quotes, parentheses, brackets and braces can extend to a
new line:
1 # http://tinyurl.com/zcdx3yo
2
3
4 print("""This is a really really
5 really really long line of
6 code.""")
You can use a backward slash \ to extend code to the next line when you
wouldn't normally be able to:
1 # http://tinyurl.com/hjcf2sa
2
3
4 print\
5 ("""This is a really really
6 really long line of code.""")
This example and the previous example have the same output. The slash
allowed me to put ("""This is a really really really long
line of code.""") and print on separate lines, which otherwise is
not allowed. This practice is not very common in, but I do it throughout the
book to make examples narrow so that they will fit on eBook readers with
small screens.
Keywords
Programming languages like Python have words with special meanings,
called keywords. for, a keyword you've already seen, is used to execute
code multiple times. You will learn more keywords throughout this chapter.
Spacing
Let's take another look at your program that prints Hello, World! a
hundred times:
1 # http://tinyurl.com/glp9xq6
2
3
4 for i in range(100):
5 print("Hello, World!")
As I noted earlier, print is indented four spaces. I will cover why shortly,
but it lets Python know when blocks of code begin and end. In the meantime,
please be aware that whenever you see an indent in an example, it is an
indent of four spaces. Without proper spacing, your program will not work.
Other programming languages do not use spacing like this; they use
keywords or brackets instead. Here is the same program written in another
programming language called JavaScript:
1 # http://tinyurl.com/hwa2zae
2
3
4 # This is a JavaScript program.
5 # It will not work.
6
7
8 for (i = 0; i < 100; i++) {
9 console.log("Hello, World!");
10 }
Python proponents believe the required use of proper spacing makes Python
less tedious to read and write than other languages. Like in the example
above, even when space is not part of the programming language,
programmers include it to make their code easier to read.
Data Types
Python groups data into different categories called data types. In Python,
each data value, like 2 or "Hello, World!", is called an object. You
will learn more about objects in Part II, but for now think of an object as a
data value in Python with three properties: identity, data type, and value. An
object's identity is its location in your computer's memory, which never
changes. The data type of an object is the category of data the object belongs
to, which determines the properties the object has and never changes. The
value of an object is the data it represents—the number 2, for example, has a
value of 2.
"Hello, World!" is an object with the data type str, short for string,
and the value "Hello, World!". When you refer to an object with the
data type str, you call it a string. A string is a sequence of one or more
characters surrounded by quotes. A character is a single symbol like a or 1.
You can use single quotes or double quotes, but the quotes at the beginning
and end of a string must match:
1 # http://tinyurl.com/hh5kjwp
2
3
4 "Hello, World!"
1 # http://tinyurl.com/heaxhsh
2
3
4 'Hello, World!'
Strings are used to represent text, and they have unique properties.
The numbers you used to do math in the previous section are also objects—
but they are not strings. Whole numbers (1, 2, 3, 4, etc.) have the data type
int, short for integer. Like strings, integers have unique properties. For
example, you can multiply two integers, but you cannot multiply two strings.
Decimal numbers (numbers with a decimal point) have a data type called
float. 2.1, 8.2, and 9.9999 are all objects with the float data type.
They are called floating-point numbers. Like all data types, floating-point
numbers have unique properties and behave in a certain way, similarly to
integers:
1 # http://tinyurl.com/guoc4gy
2
3
4 2.2 + 2.2
>> 4.4
Objects with a bool data type are called booleans, and have a value of
True or False:
1 # http://tinyurl.com/jyllj2k
2
3
4 True
>> True
1 # http://tinyurl.com/jzgsxz4
2
3
4 False
>> False
Objects with a data type NoneType always have the value None. They are
used to represent the absence of value:
1 # http://tinyurl.com/h8oqo5v
2
3
4 None
I explain how to use the different data types throughout this chapter.
1 # http://tinyurl.com/zs65dp8
2
3
4 2 + 2
>> 4
1 # http://tinyurl.com/gs9nwrw
2
3
4 2 - 2
>> 0
1 # http://tinyurl.com/hasegvj
2
3
4 4 / 2
>> 2.0
1 # http://tinyurl.com/z8ok4q3
2
3
4 2 * 2
>> 4
1 # Do not run.
2
3
4
5
6
7 int a;
8 a = 144;
1 # http://tinyurl.com/hw64mrr
2
3
4 b = 100
5 b
>> 100
1 # http://tinyurl.com/hw97que
2
3
4 x = 100
5 x
6
7
8 x = 200
9 x
>> 100
>> 200
1 # http://tinyurl.com/z8hv5j5
2
3
4 x = 10
5 y = 10
6 z = x + y
7 z
8 a = x - y
9 a
>> 20
>> 0
1 # http://tinyurl.com/zvzf786
2
3
4 x = 10
5 x = x + 1
6 x
>> 11
To decrement a variable, you do the same thing, but instead subtract the
number you want to decrement by:
1 # http://tinyurl.com/gmuzdr9
2
3
4 x = 10
5 x = x - 1
6 x
>> 9
These examples are perfectly valid, but there is a shorter method you should
use instead:
1 # http://tinyurl.com/zdva5wq
2
3
4 x = 10
5 x += 1
6 x
>> 11
1 # http://tinyurl.com/jqw4m5r
2
3
4 x = 10
5 x -= 1
6 x
>> 9
Variables are not limited to storing integer values. They can refer to any data
type:
1 # http://tinyurl.com/jsygqcy
2
3
4 hi = "Hello, World!"
1 # http://tinyurl.com/h47ty49
2
3
4 my_float = 2.2
1 # http://tinyurl.com/hx9xluq
2
3
4 my_boolean = True
You can name variables whatever you'd like, as long as you follow four rules:
1. Variables can't have spaces. If you want to use two words in a variable, put
an underscore between them: i.e., my_variable = "A string!"
2. Variable names can only contain letters, numbers, and the underscore
symbol.
3. You cannot start a variable name with a number. Although you can start a
variable with an underscore, it has a special meaning that I will cover later, so
avoid using it until then.
4. You cannot use Python keywords for variable names. You can find a list of
keywords at http://theselftaughtprogrammer.io/keywords.
Syntax
Syntax is the set of rules, principles, and processes that govern the structure
of sentences in a given language, specifically word order.3 The English
language has syntax, and so does Python.
In Python, strings are always surrounded by quotes. This is an example of
Python's syntax. The following is a valid Python program:
1 # http://tinyurl.com/j7c2npf
2
3
4 print("Hello, World!")
It is valid because you followed Python's syntax by using quotes around your
text when you defined a string. If you only used quotes on one side of your
text, you would violate Python's syntax, and your code would not work.
1 # http://tinyurl.com/hp2plhs
2
3
4 # This code has an error.
5
6
7 my_string = "Hello World.
>> File
"/Users/coryalthoff/PycharmProjects/se.py", line 1
my_string = 'd ^ SyntaxError: EOL while scanning
string literal
This message tells you there is a syntax error in your program. Syntax errors
are fatal. A program cannot run with a syntax error. When you try to run a
program with a syntax error, Python lets you know about it in the shell. The
message tells you what file the error was in, what line it occurred on, and
what kind of error it was. Although this error may look intimidating, they
happen all the time.
When there is an error in your code, you should go to the line number the
problem occurred on and try to figure out what you did wrong. In this
example, you would go to the first line of your code. After staring at it for a
while, you would eventually notice there is only one quote. To fix the error,
add a quote at the end of the string and rerun the program. From this point
forward, I will represent the output of an error like this:
For easier reading, I will only show the last line of the error.
Python has two kinds of errors: syntax errors and exceptions. Any error that
is not a syntax error is an exception. A ZeroDivisionError is an
exception that occurs if you try dividing by zero.
Unlike syntax errors, exceptions are not necessarily fatal (there is a way to
make a program run even if there is an exception, which you will learn about
in the next chapter). When an exception occurs, Python programmers say
"Python (or your program) raised an exception." Here is an example of an
exception:
1 # http://tinyurl.com/jxpztcx
2
3
4 # This code has an error.
5
6 10 / 0
1 # http://tinyurl.com/gtp6amr
2
3
4 # This code has an error.
5
6
7 y = 2
8 x = 1
As you are learning to program, you will frequently get syntax errors and
exceptions (including ones I did not cover), but they will decrease over time.
Remember, when you run into a syntax error or exception, go to the line
where the problem occurred and look at it and figure out the solution (search
the Internet for the error or exception if you are stumped).
Arithmetic Operators
Earlier, you used Python to do simple arithmetic calculations, like 4 / 2.
The symbols you used in those examples are called operators. Python
divides operators into several categories, and the ones you've seen so far are
called arithmetic operators. Here are some of the most common arithmetic
operators in Python:
When two numbers are divided there is a quotient and a remainder. The
quotient is the result of the division, and the remainder is what is left over.
The modulo operator returns the remainder. For example, 13 divided by 5 is
2 remainder 3:
1 # http://tinyurl.com/grdcl95
2
3
4 13 // 5
>> 2
1 # http://tinyurl.com/zsqwukd
2
3
4 13 % 5
>> 3
1 # http://tinyurl.com/jerpe6u
2
3
4 # even
5 12 % 2
>> 0
1 # http://tinyurl.com/gkudhcr
2
3
4 # odd
5 11 % 2
>> 1
There are two operators used for division. The first is //, which returns the
quotient:
1 # http://tinyurl.com/hh9fqzy
2
3
4 14 // 3
> 4
The second is /, which returns the result of the first number divided by the
second as a floating-point number:
1 # http://tinyurl.com/zlkjjdp
2
3
4 14 / 3
> 4.666666666666667
1 # http://tinyurl.com/h8vuwd4
2
3 2 ** 2
>> 4
The values (in this case numbers) on either side of an operator are called
operands. Together, two operands and an operator form an expression.
When your program runs, Python evaluates each expression and returns a
single value. When you type the expression 2+2 into the shell, Python
evaluates it to 4.
1 # http://tinyurl.com/hgjyj7o
2
3
4 2 + 2 * 2
>> 6
1 # http://tinyurl.com/hsq7rcz
2
3
4 (2 + 2) * 2
>> 8
Comparison Operators
Comparison operators are another category of operators in Python. Similar
to , they are used in expressions with operands on either side. Unlike
expressions with arithmetic operators, expressions with comparison operators
evaluate to either True or False.
An expression with the > operator returns the value True if the number on
the left is greater than the number on the right, and False if it is not:
1 # http://tinyurl.com/jm7cxzp
2
3
4 100 > 10
>> True
An expression with the < operator returns the value True if the number on
the left is less than the number on the right, and False if it is not:
1 # http://tinyurl.com/gsdhr8q
2
3 100 < 10
>> False
An expression with the >= operator returns the value True if the number on
the left is greater than or equal to the number on the right. Otherwise, the
expression returns False:
1 # http://tinyurl.com/jy2oefs
2
3 2 >= 2
>> True
An expression with the <= operator returns the value True if the number on
the left is less than or equal to the number on the right. Otherwise, the
expression returns False:
1 # http://tinyurl.com/jk599re
2
3
4 2 >= 2
>> True
An expression with the == operator returns the value True if the two
operands are equal, and False if not:
1 # http://tinyurl.com/j2tsz9u
2
3
4 2 == 2
>> True
1 # http://tinyurl.com/j5mr2q2
2
3
4 1 == 2
>> False
An expression with the != operator returns True if the two operands are not
equal, and False otherwise:
1 # http://tinyurl.com/gsw3zoe
2
3
4 1 != 2
>> True
1 # http://tinyurl.com/z7pffk3
2
3
4 2 != 2
>> False
Logical Operators
Logical operators are another category of operators in Python. Like
comparison operators, logical operators also evaluate to True or False.
The Python keyword and takes two expressions and returns True if all the
expressions evaluate to True. If any of the expressions are False, it returns
False:
1 # http://tinyurl.com/zdqghb2
2
3
4 1 == 1 and 2 == 2
>> True
1 # http://tinyurl.com/zkp2jzy
2
3
4 1 == 2 and 2 == 2
>> False
1 # http://tinyurl.com/honkev6
2
3
4 1 == 2 and 2 == 1
>> False
1 # http://tinyurl.com/zjrxxrc
2
3
4 2 == 1 and 1 == 1
>> False
You can use the and keyword multiple times in one statement:
1 # http://tinyurl.com/zpvk56u
2
3
4 1 == 1 and 10 != 2 and 2 < 10
>> True
The keyword or takes two or more expressions and evaluates to True if any
of the expressions evaluate to True:
1 # http://tinyurl.com/hosuh7c
2
3
4 1==1 or 1==2
>> True
1 # http://tinyurl.com/zj6q8h9
2
3
4 1==1 or 2==2
>> True
1 # http://tinyurl.com/j8ngufo
2
3
4 1==2 or 2==1
>> False
1 # http://tinyurl.com/z728zxz
2
3
4 2==1 or 1==2
>> False
1 # http://tinyurl.com/ja9mech
2
3
4 1==1 or 1==2 or 1==3
>> True
This expression evaluates to True because 1==1 is True, even though the
rest of the expressions would evaluate to False.
Placing the keyword not in front of an expression will change the result of
the evaluation to the opposite of what it would have otherwise evaluated to. If
the expression would have evaluated to True, it will evaluate to False
when preceded by not:
1 # http://tinyurl.com/h45eq6v
2
3
4 not 1 == 1
>> False
1 # http://tinyurl.com/gsqj6og
2
3
4 not 1 == 2
>> True
Conditional Statements
The keywords if, elif, and else are used in conditional statements.
Conditional statements are a type of control structure: a block of code that
makes decisions by analyzing the values of variables. A conditional statement
is code that can execute additional code conditionally. Here is an example in
pseudocode (A notation resembling code used to illustrate an example) to
clarify how this works:
1 # Do not run
2
3
4 If (expression) Then
5 (code_area1)
6 Else
7 (code_area2)
This pseudocode explains that you can define two conditional statements that
work together. If the expression defined in the first conditional statement is
True, all the code defined in code_area1 is executed. If the expression
defined in the first conditional statement is False, all the code defined in
code_area2 is executed. The first part of the example is called an if-
statement, and the second is called an else-statement. Together,
they form an if-else statement: a way for programmers to say "if this
happens do this, otherwise, do that." Here is an example of an if-else
statement in Python:
1 # http://tinyurl.com/htvy6g3
2
3
4 home = "America"
5 if home == "America":
6 print("Hello, America!")
7 else:
8 print("Hello, World!")
1 # http://tinyurl.com/jytyg5x
2
3
4 home = "Canada"
5 if home == "America":
6 print("Hello, America!")
7 else:
8 print("Hello, World!")
1 # http://tinyurl.com/jyg7dd2
2
3
4 home = "America"
5 if home == "America":
6 print("Hello, America!")
1 # http://tinyurl.com/z24ckye
2
3
4 x = 2
5 if x == 2:
6 print("The number is 2.")
7 if x % 2 == 0:
8 print("The number is even.")
9 if x % 2 != 0:
10 print("The number is odd.")
Each if-statement will execute its code only if its expression evaluates
to True. In this case, the first two expressions evaluate to True, so their
code executes, but the third expression evaluates to False, so its code does
not execute.
If you want to get crazy, you can even put an if-statement inside of
another if-statement (this is called nesting):
1 # http://tinyurl.com/zrodgne
2
3
4 x = 10
5 y = 11
6
7
8 if x == 10:
9 if y == 11:
10 print(x + y)
>> 21
1 # http://tinyurl.com/jpr265j
2
3
4 home = "Thailand"
5 if home == "Japan":
6 print("Hello, Japan!")
7 elif home == "Thailand":
8 print("Hello, Thailand!")
9 elif home == "India":
10 print("Hello, India!")
11 elif home == "China":
12 print("Hello, China!")
13 else:
14 print("Hello, World!")
1 # http://tinyurl.com/zdvuuhs
2
3 home = "Mars"
4 if home == "America":
5 print("Hello, America!")
6 elif home == "Canada":
7 print("Hello, Canada!")
8 elif home == "Thailand":
9 print("Hello, Thailand!")
10 elif home == "Mexico":
11 print("Hello, Mexico!")
12 else:
13 print("Hello, World!")
1 # http://tinyurl.com/hzyxgf4
2
3
4 x = 100
5 if x == 10:
6 print("10!")
7 elif x == 20:
8 print("20!")
9 else:
10 print("I don't know!")
11
12
13 if x == 100:
14 print("x is 100!")
15
16
17 if x % 2 == 0:
18 print("x is even!")
19 else:
20 print("x is odd!")
1 # http://tinyurl.com/jrowero
2
3
4 print("Hello, World!")
1 # http://tinyurl.com/h2y549y
2
3
4 2 + 2
>> 4
1 # http://tinyurl.com/zfz3eel
2
3 for i in range(100):
4 print("Hello, World!")
The first line of the program is the header. It's made up of a keyword—for
—followed by a colon. After the indentation is a suite—print("Hello,
World!"). In this case, the header uses the suite to print Hello,
World! a hundred times. The code in this example is called a loop, which
you learn more about in Chapter 7. This code only has one clause.
1 # http://tinyurl.com/hpwkdo4
2
3
4 x = 100
5 if x == 10:
6 print("10!")
7 elif x == 20:
8 print("20!")
9 else:
10 print("I don't know!")
11
12
13 if x == 100:
14 print("x is 100!")
15
16
17 if x % 2 == 0:
18 print("x is even!")
19 else:
20 print("x is odd!")
The first compound statement has three clauses; the second compound
statement has one clause, and the last compound statement has two clauses.
One last thing about statements, they can have spaces between them. Spaces
between statements do not affect the code. Sometimes spaces are used
between statements to make code more readable:
1 # http://tinyurl.com/zlgcwoc
2
3
4 print("Michael")
5
6
7
8
9
10
11 print("Jordan")
>> Michael
>> Jordan
Vocabulary
Comment: A line (or part of a line) of code written in English (or another
language) preceded by a unique symbol telling the programming language
you are using know it should ignore that line (or part of a line) of code.
Keyword: A word with a special meaning in a programming language. You
can see all of Python's keywords at
http://theselftaughtprogrammer.io/keywords.
Data type: A category of data.
Object: A data value in Python with three properties: an identity, a data type,
and a value.
Str: The data type of a string.
String: An object with the data type str. Its value is a sequence of one or
more characters surrounded by quotes.
Character: A single symbol like a or 1.
Int: The data type of whole numbers.
Integer: An object with the data type int. Its value is a whole number.
Float: The data type of decimal numbers.
Floating-point number: An object with the data type float. Its value is a
decimal number.
Bool: The data type of boolean objects.
Boolean: An object with the data type bool. Its value is either True or
False.
NoneType: The data type of None objects.
None: An object with the data type NoneType. Its value is always None.
Constant: A value that never changes.
Variable: A name assigned a value using the assignment operator.
Assignment operator: The = sign in Python.
Increment: Increasing the value of a variable.
Decrement: Decreasing the value of a variable.
Syntax: The set of rules, principles, and processes that govern the structure
of sentences in a given language, specifically word order.4
Syntax error: A fatal programming error caused by violating a programming
language's syntax.
Exception: A nonfatal programming error.
Operator: Symbols used with operands in an expression.
Arithmetic operator: A category of operators used in arithmetic expressions.
Operand: A value on either side of an operator.
Expression: Code with an operator surrounded by two operands.
Order of operations: A set of rules used in mathematical calculations to
evaluate an expression.
Comparison operator: A category of operators used in an expression that
evaluate to either True or False.
Logical operator: A category of operators that evaluate two expressions and
return either True or False.
Conditional statement: Code that can execute additional code conditionally.
Control structure: A block of code that makes decisions by analyzing the
values of variables.
Pseudocode: A notation resembling code used to illustrate an example.
if-else statement: A way for programmers to say "if this happens do this,
otherwise, do that."
if-statement: The first part of an if-else statement.
else-statement: The second part of an if-else statement.
elif-statement: Statements that can be indefinitely added to an if-else
statement to allow it to make additional decisions.
Statement: A command or calculation.
Simple statement: A statement that can be expressed in one line of code.
Compound statement: A statement that generally spans multiple lines of
code.
Clause: The building blocks of compound statements. A clause is made up of
two or more lines of code: a header followed by a suite(s).
Header: A line of code in a clause containing a keyword, followed by a
colon and a sequence of one or more lines of indented code.
Suite: A line of code in a clause controlled by a header.
Challenges
1. Print three different strings.
2. Write a program that prints a message if a variable is less than 10, and
different message if the variable is greater than or equal to 10.
3. Write a program that prints a message if a variable is less than or equal to
10, another message if the variable is greater than 10 but less than or equal to
25, and another message if the variable is greater than 25.
4. Create a program that divides two variables and prints the remainder.
5. Create a program that takes two variables, divides them, and prints the
quotient.
6. Write a program with a variable age assigned to an integer that prints
different strings depending on what integer age is.
Solutions: http://tinyurl.com/zx7o2v9 .
e long:
e long:
Chapter 4. Functions
"Functions should do one thing. They should do it well. They should do it
only."
~ Robert C. Martin
In this chapter, you will learn about functions: compound statements that can
take input, execute instructions, and return an output. Functions allow you to
define and reuse functionality in your programs.
Representing Concepts
From here on out, I will use a new convention (an agreed upon way of doing
things) to explain programming concepts. Here is an example of the
convention I will use: print("[what_you_want_to_print]"),
which illustrates how to use the print function.
Functions
Calling a function means giving the function the input it needs to execute its
instructions and return an output. Each input to a function is a parameter.
When you pass a parameter to a function, it is called "passing" the function a
parameter.
1 # Do not run.
2
3
4
5 f(x) = x * 2
The left side of the statement above defines a function, f, that takes one
parameter, x. The right side of the statement is the function's definition that
uses the parameter passed in ( x) to make a calculation and return the result
(the output). In this case, the value of the function is defined as the function's
parameter value multiplied by two.
In both Python and algebra you invoke a function with the following syntax:
[function_name]([parameters_separated_by_commas]).
You call a function by putting parentheses after the function name. The
parameters go inside the parentheses, with each parameter separated by a
comma. For a mathematical function f, defined as f(x) = 2 * x, the
value of f(2) is 4, and the value of f(10) is 20.
Defining Functions
To create a function in Python you choose a function name, define its
parameters, define what it does, and define what value the function returns.
Here is the syntax for defining a function:
1 # Do not run.
2
3
4
5 def [function_name]([parameters]):
6 [function_definition]
Methods
In Chapter 4, you learned about functions. Python has a similar concept
called methods. Methods are functions closely associated with a given type
of data. Methods execute code and can return a result just like a function.
Unlike a function, you call a method on an object. You can also pass them
parameters. Here is an example of calling the methods upper and replace
on a string:
1 # http://tinyurl.com/zdllght
2
3
4 "Hello".upper()
>> 'HELLO'
1 # http://tinyurl.com/hfgpst5
2
3
4 "Hello".replace("o", "@")
>> 'Hell@'
Lists
A list is a container that stores objects in a specific order.
Lists are represented with brackets. There are two syntaxes you can use to
create a list. You can create an empty list with the list function:
1 # http://tinyurl.com/h4go6kg
2
3
4 fruit = list()
5 fruit
>> []
1 # http://tinyurl.com/jft8p7x
2
3
4 fruit = []
5 fruit
>> []
1 # http://tinyurl.com/h2y8nos
2
3
4 fruit = ["Apple", "Orange", "Pear"]
5 fruit
>> ['Apple', 'Orange', 'Pear']
1 # http://tinyurl.com/h9w3z2m
2
3
4 fruit = ["Apple", "Orange", "Pear"]
5 fruit.append("Banana")
6 fruit.append("Peach")
7 fruit
1 # http://tinyurl.com/zhpntsr
2
3
4 random = []
5 random.append(True)
6 random.append(100)
7 random.append(1.1)
8 random.append("Hello")
9 random
>> [True, 100, 1.1, 'Hello']
1 # http://tinyurl.com/z8zzk8d
2
3
4 fruit = ["Apple", "Orange", "Pear"]
1 # http://tinyurl.com/jqtlwpf
2
3
4 fruit = ["Apple", "Orange", "Pear"]
5 fruit[0]
6 fruit[1]
7 fruit[2]
>> 'Apple'
>> 'Orange'
>> 'Pear'
1 # http://tinyurl.com/za3rv95
2
3
4 colors = ["blue", "green", "yellow"]
5 colors[4]
1 # http://tinyurl.com/h4ahvf9
2
3
4 colors = ["blue", "green", "yellow"]
5 colors
6 colors[2] = "red"
7 colors
You can remove the last item from a list using the
method pop:
1 # http://tinyurl.com/j52uvmq
2
3
4 colors = ["blue", "green", "yellow"]
5 colors
6 item = colors.pop()
7 item
8 colors
1 # http://tinyurl.com/jjxnk4z
2
3
4 colors1 = ["blue", "green", "yellow"]
5 colors2 = ["orange", "pink", "black"]
6 colors1 + colors2
1 # http://tinyurl.com/z4fnv39
2
3
4 colors = ["blue", "green"," yellow"]
5 "green" in colors
>> True
1 # http://tinyurl.com/jqzk8pj
2
3
4 colors = ["blue", "green", "yellow"]
5 "black" not in colors
>> True
You can get the size of a list (the number of items
in it) with the len function:
1 # http://tinyurl.com/hhx6rx4
2
3
4 len(colors)
>> 3
1 # http://tinyurl.com/gq7yjr7
2
3
4 colors = ["purple",
5 "orange",
6 "green"]
7
8
9 guess = input("Guess a color:")
10
11
12 if guess in colors:
13 print("You guessed correctly!")
14 else:
15 print("Wrong! Try again.")
Tuples
A tuple is a container that stores objects in a
specific order. Unlike lists, tuples are immutable,
which means their contents cannot change. Once you
create a tuple, you cannot modify the value of any
of the items in it, add new items to it, or remove
items from it. You represent tuples with
parentheses. You must separate items in a tuple with
commas. There are two syntaxes to create a tuple:
1 # http://tinyurl.com/zo88eal
2
3
4 my_tuple = tuple()
5 my_tuple
>> ()
And:
1 # http://tinyurl.com/zm3y26j
2
3
4 my_tuple = ()
5 my_tuple
>> ()
1 # http://tinyurl.com/zlwwfe3
2
3
4 rndm = ("M. Jackson", 1958, True)
5 rndm
1 # http://tinyurl.com/j8mca8o
2
3
4 # this is a tuple
5 ("self_taught",)
6
7
8 # this is not a tuple
9 (9) + 1
>> ('self_taught',)
>> 10
1 # http://tinyurl.com/z3x34nk
2
3
4 dys = ("1984",
5 "Brave New World",
6 "Fahrenheit 451")
7
8
9 dys[1] = "Handmaid's Tale"
You can get items from a tuple the same way you
would from a list—by referencing the item's index:
1 # http://tinyurl.com/z9dc6lo
2
3
4 dys = ("1984",
5 "Brave New World",
6 "Fahrenheit 451")
7
8
9 dys[2]
1 # http://tinyurl.com/j3bsel7
2
3
4 dys = ("1984",
5 "Brave New World",
6 "Fahrenheit 451")
7
8
9 "1984" in dys
>> True
1 # http://tinyurl.com/jpdjjv9
2
3
4 dys = ("1984",
5 "Brave New World",
6 "Fahrenheit 451")
7
8
9 "Handmaid's Tale" not in dys
>> True
Dictionaries
Dictionaries are another built-in container for
storing objects. They are used to link one object,
called a key, to another object—called the value.
Linking one object to another is called mapping. The
result is a key-value pair. You add key-value pairs
to a dictionary. You can then look up a key in the
dictionary and get its value. You cannot, however,
use a value to look up a key.
1 # http://tinyurl.com/zfn6jmw
2
3
4 my_dict = dict()
5 my_dict
>> {}
And:
1 # http://tinyurl.com/jfgemf2
2
3
4 my_dict = {}
5 my_dict
>> {}
1 # http://tinyurl.com/hplqc4u
2
3
4 fruits = {"Apple":
5 "Red",
6 "Banana":
7 "Yellow"}
8 fruits
1 # http://tinyurl.com/grc28lh
2
3
4 facts = dict()
5
6
7 # add a value
8 facts["code"] = "fun"
9 # look up a key
10 facts["code"]
11
12
13 # add a value
14 facts["Bill"] = "Gates"
15 # look up a key
16 facts["Bill"]
17
18
19 # add a value
20 facts["founded"] = 1776
21 # look up a key
22 facts["founded"]
>> 'fun'
>> Gates
>> 1776
1 # http://tinyurl.com/hgf9vmp
2
3
4 bill = dict({"Bill Gates":
5 "charitable"})
6
7
8 "Bill Gates" in bill
>> True
1 # http://tinyurl.com/he3g993
2
3
4 bill = dict({"Bill Gates":
5 "charitable"})
6
7
8 "Bill Doors" not in bill
>> True
1 # http://tinyurl.com/gnjvep7
2
3
4 rhymes = {"1": "fun",
5 "2": "blue",
6 "3": "me",
7 "4": "floor",
8 "5": "live"
9 }
10
11
12 n = input("Type a number:")
13 if n in rhymes:
14 rhyme = rhymes[n]
15 print(rhyme)
16 else:
17 print("Not found.")
Type a number:
Your dictionary (rhymes) has six song names (keys)
mapped to six musicians (values). You ask the user
to type the name of a song and save their response
in a variable. Before you look up their response in
your dictionary, check to make sure the key exists
using the in keyword. If the key exists, you look up
the name of the song in your dictionary and print
the name of the artist who sings it. Otherwise, you
print a message letting the user know the name of
the song is not available.
Containers in Containers
You can store containers in other containers. For
example, you can store lists in a list:
1 # http://tinyurl.com/gops9fz
2
3
4 lists = []
5 rap = ["Kanye West",
6 "Jay Z",
7 "Eminem",
8 "Nas"]
9
10
11 rock = ["Bob Dylan",
12 "The Beatles",
13 "Led Zeppelin"]
14
15
16 djs = ["Zeds Dead",
17 "Tiesto"]
18
19
20 lists.append(rap)
21 lists.append(rock)
22 lists.append(djs)
23
24
25 print(lists)
1 # http://tinyurl.com/gu4mudk
2
3
4 # Continue from
5 # last example
6
7 rap = lists[0]
8 print(rap)
1 # http://tinyurl.com/hdtosm2
2
3
4 # Continue from
5 # last example
6
7
8 rap = lists[0]
9 rap.append("Kendrick Lamar")
10 print(rap)
11 print(lists)
1 # http://tinyurl.com/z9dhema
2
3
4 locations = []
5
6
7 la = (34.0522, 188.2437)
8 chicago = (41.8781, 87.6298)
9
10
11 locations.append(la)
12 locations.append(chicago)
13
14
15 print(locations)
1 # http://tinyurl.com/ht7gpsd
2
3
4 eights = ["Edgar Allan Poe",
5 "Charles Dickens"]
6
7
8 nines = ["Hemingway",
9 "Fitzgerald",
10 "Orwell"]
11
12
13 authors = (eights, nines)
14 print(authors)
1 # http://tinyurl.com/h8ck5er
2
3
4 bday = {"Hemingway":
5 "7.21.1899",
6 "Fitzgerald":
7 "9.24.1896"}
8
9
10 my_list = [bday]
11 print(my_list)
12 my_tuple = (bday,)
13 print(my_tuple)
1 # http://tinyurl.com/zqupwx4
2
3
4 ny = {"location":
5 (40.7128,
6 74.0059),
7
8
9 "celebs":
10 ["W. Allen",
11 "Jay Z",
12 "K. Bacon"],
13
14 "facts":
15 {"state":
16 "NY",
17 "country":
18 "America"}
19 }
Vocabulary
Method: Functions closely associated with a given
type of data.
List: A container that stores objects in a specific
order.
Iterable: An object is iterable when you can access
each item using a loop.
Iterables: Objects that are iterable like strings,
lists, and tuples.
Index: A number representing a position in an
iterable.
Mutable: When a container is mutable the contents of
the container can change.
Immutable: When a container is immutable the
contents of the container cannot change.
Dictionary: A built-in container for storing objects
used to map one object—called a key—to another
object—called the value.
Key: A value used to look up a value in a
dictionary.
Value: A value mapped to a key in a dictionary.
Mapping: Linking one object to another.
Key-value pair: A key mapped to a value in a
dictionary.
Challenges
1. Create a list of your favorite musicians.
2. Create a list of tuples, with each tuple
containing the longitude and latitude of somewhere
you've lived or visited.
3. Create a dictionary that contains different
attributes about you: height, favorite color,
favorite author, etc.
4. Write a program that lets the user ask your
height, favorite color, or favorite author, and
returns the result from the dictionary you created
in the previous challenge.
5. Create a dictionary mapping your favorite
musicians to a list of your favorite songs by them.
6. Lists, tuples, and dictionaries are just a few of
the containers built into Python. Research Python
sets (a type of container). When would you use a
set?
Solutions: http://tinyurl.com/z54w9cb.
Chapter 6. String Manipulation
"In theory, there is no difference between theory and practice. But, in
practice, there is."
~ Jan L. A. van de Snepscheut
Triple Strings
If a string spans more than one line, you have to put it in triple quotes:
1 # http://tinyurl.com/h59ygda
2
3
4 """ line one
5 line two
6 line three
7 """
If you try to define a string that spans more than one line with single or
double quotes, you will get a syntax error.
Indexes
Strings, like lists and tuples, are iterable. You can look up each character in a
string with an index. Like other iterables, the first character in a string is at
index 0, and each subsequent index is incremented by 1:
1 # http://tinyurl.com/zqqc2jw
2
3
4 author = "Kafka"
5 author[0]
6 author[1]
7 author[2]
8 author[3]
9 author[4]
>> 'K'
>> 'a'
>> 'f'
>> 'k'
>> 'a'
In this example, you used the indexes 0, 1, 2, 3, and 4 to look up each of the
characters in the string "Kafka". If you try to look up a character past the
last index in your string, Python raises an exception:
1 # http://tinyurl.com/zk52tef
2
3
4 author = "Kafka"
5 author[5]
1 # http://tinyurl.com/hyju2t5
2
3
4 author = "Kafka"
5 author[-1]
>> a
1 # http://tinyurl.com/jtpx7sr
2
3
4 author = "Kafka"
5 author[-2]
6 author[-3]
>> k
>> f
1 # http://tinyurl.com/hsr83lv
2
3
4 ff = "F. Fitzgerald"
5 ff = "F. Scott Fitzgerald"
6 ff
1 # http://tinyurl.com/h4z5mlg
2
3
4 "cat" + "in" + "hat"
> 'catinhat'
1 # http://tinyurl.com/gsrajle
2
3
4 "cat " + " in" + " the" + " hat"
String Multiplication
You can multiply a string by a number with the
multiplication operator:
1 # http://tinyurl.com/zvm9gng
2
3
4 "Sawyer" * 3
>> SawyerSawyerSawyer
Change Case
You can change every character in a string to
uppercase by calling the upper method on it:
1 # http://tinyurl.com/hhancz6
2
3
4 "We hold these truths...".upper()
1 # http://tinyurl.com/zkz48u5
2
3
4 "SO IT GOES.".lower()
1 # http://tinyurl.com/jp5hexn
2
3
4 "four score and...".capitalize()
Format
You can create a new string using the format method,
which looks for occurrences of curly brackets {} in
the string, and replaces them with the parameters
you pass in:
1 # http://tinyurl.com/juvguy8
2
3
4 "William {}".format("Faulkner")
1 # http://tinyurl.com/zcpt9se
2
3
4 last = "Faulkner"
5 "William {}".format(last)
1 # http://tinyurl.com/z6t6d8n
2
3
4 author = "William Faulkner"
5 year_born = "1897"
6
7
8 "{} was born in {}."\
9 .format(author,
10 year_born)
1 # http://tinyurl.com/gnrdsj9
2
3
4 n1 = input("Enter a noun:")
5 v = input("Enter a verb:")
6 adj = input("Enter an adj:")
7 n2 = input("Enter a noun:")
8
9
10 r = """The {} {} the {} {}
11 """.format(n1,
12 v,
13 adj,
14 n2)
15 print(r)
Split
Strings have a method called split, which you can
use to separate one string into two or more strings.
You pass the split method a string as a parameter,
and it uses that string to divide the original
string into multiple strings. For example, you can
separate the string "I jumped over the puddle. It
was 12 feet!" into two different strings by passing
the split method a period as a parameter:
1 # http://tinyurl.com/he8u28o
2
3
4 "Hello.Yes!".split(".")
Join
The join method lets you add new characters between
every character in a string:
1 # http://tinyurl.com/h2pjkso
2
3
4 first_three = "abc"
5 result = "+".join(first_three)
6 result
>> 'a+b+c'
1 # http://tinyurl.com/z49e3up
2
3
4 words = ["The",
5 "fox",
6 "jumped",
7 "over",
8 "the",
9 "fence",
10 "."]
11 one = "".join(words)
12 one
>> Thefoxjumpedoverthefence.
1 # http://tinyurl.com/h4qq5oy
2
3
4 words = ["The",
5 "fox",
6 "jumped",
7 "over",
8 "the",
9 "fence",
10 "."]
11 one = " ".join(words)
12 one
Strip Space
You can use the strip method to remove leading and
trailing whitespace from a string:
1 # http://tinyurl.com/jfndhgx
2
3
4 s = " The "
5 s = s.strip()
6 s
>> 'The'
Replace
The replace method replaces every occurrence of a
string with another string. The first parameter is
the string to replace, and the second parameter is
the string to replace the occurrences with:
1 # http://tinyurl.com/zha4uwo
2
3
4 equ = "All animals are equal."
5 equ = equ.replace("a", "@")
6 print(equ)
Find an Index
You can get the index of the first occurrence of a
character in a string with the index method. Pass in
the character you are looking for as a parameter,
and the index method returns the index of the first
occurrence of that character in the string:
1 # http://tinyurl.com/hzc6asc
2
3
4 "animals".index("m")
>> 3
1 # http://tinyurl.com/jmtc984
2
3
4 "animals".index("z")
>> ValueError: substring not found
1 # http://tinyurl.com/zl6q4fd
2
3
4 try:
5 "animals".index("z")
6 except:
7 print("Not found.")
In
The in keyword checks if a string is in another
string, and returns either True or False:
1 # http://tinyurl.com/hsnygwz
2
3
4 "Cat" in "Cat in the hat."
>> True
1 # http://tinyurl.com/z9b3e97
2
3
4 "Bat" in "Cat in the hat."
>> False
>> True
Escaping Strings
If you use quotes inside a string, you will get a
syntax error:
1 # http://tinyurl.com/zj6hc4r
2
3
4 # this code does not work.
5
6
7 "She said "Surely.""
1 # http://tinyurl.com/jdsrr7e
2
3
4 "She said \"Surely.\""
1 # http://tinyurl.com/zr7o7d7
2
3
4 'She said \"Surely.\"'
1 # http://tinyurl.com/hoef63o
2
3
4 "She said 'Surely.'"
1 # http://tinyurl.com/zkgfawo
2
3
4 'She said "Surely."'
Newline
Putting \n inside a string represents a newline:
1 # http://tinyurl.com/zyrhaeg
2
3
4 print("line1\nline2\nline3")
>> line1
>> line2
>> line3
Slicing
Slicing is a way to return a new iterable from a
subset of the items in another iterable. The syntax
for slicing is [iterable][[start_index:end_index]].
The start index is the index to start slicing from,
and the end index is the index to stop slicing at.
1 # http://tinyurl.com/h2rqj2a
2
3
4 fict = ["Tolstoy",
5 "Camus",
6 "Orwell",
7 "Huxley",
8 "Austin"]
9 fict[0:3]
1 # http://tinyurl.com/hug9euj
2
3
4 ivan = """In place of death there \
5 was light."""
6
7
8 ivan[0:17]
9 ivan[17:33]
1 # http://tinyurl.com/judcpx4
2
3
4 ivan = """In place of death there \
5 was light."""
6
7
8 ivan[:17]
1 # http://tinyurl.com/zqoscn4
2
3
4 ivan = """In place of death there \
5 was light."""
6
7
8 ivan[17:]
1 # http://tinyurl.com/zqvuqoc
2
3
4 ivan = """In place of death there \
5 was light."""
6
7
8 ivan[:]
Vocabulary
Negative index: An index (that must be a negative
number) you can use to look up items in an iterable
from right to left, instead of left to right.
Escaping: Putting a symbol in front of a character
that normally has a special meaning in Python, which
lets Python know that, in this instance, the
character is meant to represent a character, and not
the special meaning.
Slicing: A way to return a new iterable from a
subset of the items in another iterable.
Start index: The index to start slicing from.
End index: The index to stop slicing at.
Challenges
1. Print every character in the string "Camus".
2. Write a program that collects two strings from a
user, inserts them into the string "Yesterday I
wrote a [response_one]. I sent it to
[response_two]!" and prints a new string.
3. Use a method to make the string "aldous Huxley
was born in 1894." grammatically correct by
capitalizing the first letter in the sentence.
4. Take the string "Where now? Who now? When now?"
and call a method that returns a list that looks
like: ["Where now?", "Who now?", "When now?"].
5. Take the list ["The", "fox", "jumped", "over",
"the", "fence", "."] and turn it into a
grammatically correct string. There should be a
space between each word, but no space between the
word fence and the period that follows it. (Don't
forget, you learned a method that turns a list of
strings into a single string.)
6. Replace every instance of "s" in "A screaming
comes across the sky." with a dollar sign.
7. Use a method to find the first index of the
character "m" in the string "Hemingway".
8. Find dialogue in your favorite book (containing
quotes) and turn it into a string.
9. Create the string "three three three" using
concatenation, and then again using multiplication.
10. Slice the string "It was a bright cold day in
April, and the clocks were striking thirteen." to
only include the characters before the comma.
Solutions: http://tinyurl.com/hapm4dx.
Chapter 7. Loops
"Eighty percent of success is showing up."
—Woody Allen
For-Loops
In this section, you will learn how to use a for-loop: a loop used to iterate
through an iterable. This process is called iterating. You can use a for-
loop to define instructions that execute once for every item in an iterable,
and you can access and manipulate each item in the iterable from within the
instructions you defined. For example, you could use a for-loop to iterate
through a list of strings, and use the upper method to print each string with
all of its characters capitalized.
1 # http://tinyurl.com/jya6kpm
2
3
4 name = "Ted"
5 for character in name:
6 print(character)
>> T
>> e
>> d
Each time around the loop, the variable character gets assigned to an item
in the iterable name. The first time around the loop, T prints because the
variable character is assigned the value of the first item in the iterable
name. The second time around the loop, e prints because the variable
character is assigned the value of the second item in the iterable name.
This process continues until every item in the iterable has been assigned to
the variable character.
1 # http://tinyurl.com/zeftpq8
2
3
4 shows = ["GOT",
5 "Narcos",
6 "Vice"]
7 for show in shows:
8 print(show)
>> GOT
>> Narcos
>> Vice
1 # http://tinyurl.com/gpr5a6e
2
3
4 coms = ("A. Development",
5 "Friends",
6 "Always Sunny")
7 for show in coms:
8 print(show)
>> A. Development
>> Friends
>> Always Sunny
1 # http://tinyurl.com/jk7do9b
2
3
4 people = {"G. Bluth II":
5 "A. Development",
6 "Barney":
7 "HIMYM",
8 "Dennis":
9 "Always Sunny"
10 }
11
12
13 for character in people:
14 print(character)
>> Dennis
>> Barney
>> G. Bluth II
You can use for-loops to change the items in a mutable iterable, like a
list:
1 # http://tinyurl.com/j8wvp8c
2
3
4 tv = ["GOT",
5 "Narcos",
6 "Vice"]
7 i = 0
8 for show in tv:
9 new = tv[i]
10 new = new.upper()
11 tv[i] = new
12 i += 1
13
14
15 print(tv)
In this example, you used a for-loop to iterate through the list tv. You
keep track of the current item in the list using an index variable: a variable
that holds an integer representing an index in an iterable. The index variable
i starts at 0, and is incremented each time around the loop. You use the
index variable to get the current item from the list, which you then store in
the variable new. Next, you call the upper method on new, save the result,
and use your index variable to replace the current item in the list with it.
Finally, you increment i so you can look up the next item in the list the next
time around the loop.
1 # http://tinyurl.com/z45g63j
2
3
4 tv = ["GOT", "Narcos",
5 "Vice"]
6 for i, show in enumerate(tv):
7 new = tv[i]
8 new = new.upper()
9 tv[i] = new
10
11
12 print(tv)
>> ['GOT', 'NARCOS', 'VICE']
You can use for-loops to move data between mutable iterables. For
example, you can use two for-loops to take all the strings from two
different lists, capitalize each character in them, and put them into a new list:
1 # http://tinyurl.com/zcvgklh
2
3
4 tv = ["GOT", "Narcos",
5 "Vice"]
6 coms = ["Arrested Development",
7 "friends",
8 "Always Sunny"]
9 all_shows = []
10
11
12 for show in tv:
13 show = show.upper()
14 all_shows.append(show)
15
16
17 for show in coms:
18 show = show.upper()
19 all_shows.append(show)
20
21
22 print(all_shows)
Range
You can use the built-in range function to create a sequence of integers, and
use a for-loop to iterate through them. The range function takes two
parameters: a number where the sequence starts and a number where the
sequence stops. The sequence of integers returned by the range function
includes the first parameter (the number to start at), but not the second
parameter (the number to stop at). Here is an example of using the range
function to create a sequence of numbers, and iterate through them:
1 # http://tinyurl.com/hh5t8rw
2
3
4 for i in range(1, 11):
5 print(i)
>> 1
…
>> 9
>> 10
In this example, you used a for-loop to print each number in the iterable
returned by the range function. Programmers often name the variable used
to iterate through a list of integers i.
While-Loops
In this section, you will learn how to use a while-loop: a loop that
executes code as long as an expression evaluates to True. The syntax for a
while-loop is while [expression]: [code_to_execute],
where [expression] represents the expression that determines whether or
not the loop will continue and [code_to_execute] represents the code
the loop should execute as long as it does:
1 # http://tinyurl.com/j2gwlcy
2
3
4 x = 10
5 while x > 0:
6 print('{}'.format(x))
7 x -= 1
8 print("Happy New Year!")
>> 10
>> 9
>> 8
>> 7
>> 6
>> 5
>> 4
>> 3
>> 2
>> 1
>> Happy New Year!
Your while-loop executes its code as long as the expression you defined
in its header, x > 0, evaluates to True. The first time around the loop x is
10, and the expression x > 0 evaluates to True. Your while-loop code
prints the value of x, then decrements x by 1. x now equals 9. The next time
around the loop x is printed again, and gets decremented to 8. This process
continues until x is decremented to 0, at which point x > 0 evaluates to
False, and your loop ends. Python then executes the next line of code after
your loop, and prints Happy New Year!
1 # http://tinyurl.com/hcwvfk8
2
3
4 while True:
5 print("Hello, World!")
Break
You can use a break-statement—a statement with the keyword break
— to terminate a loop. The following loop will run one hundred times:
1 # http://tinyurl.com/zrdh88c
2
3
4 for i in range(0, 100):
5 print(i)
>> 0
>> 1
...
1 # http://tinyurl.com/zhxf3uk
2
3
4 for i in range(0, 100):
5 print(i)
6 break
>> 0
As soon as Python hits the break-statement, the loop ends. You can use
a while-loop and the break keyword to write a program that keeps
asking the user for input until they type q to quit:
1 # http://tinyurl.com/jmak8tr
2
3
4 qs = ["What is your name?",
5 "What is your fav. color?",
6 "What is your quest?"]
7 n = 0
8 while True:
9 print("Type q to quit")
10 a = input(qs[n])
11 if a == "q":
12 break
13 n = (n + 1) % 3
Type q to quit
What is your name?
Each time through the loop, your program asks the user one of the questions
in your qs list.
n is an index variable. Each time around the loop, you assign n to the
evaluation of the expression (n + 1) % 3, which enables you to cycle
indefinitely through every question in your qs list. The first time around the
loop, n starts at 0. Next, n is assigned the value of the expression (0 + 1)
% 3, which evaluates to 1. Then, n is assigned to the value of (1 + 1) %
3, which evaluates to 2, because whenever the first number in an expression
using modulo is smaller than the second, the answer is the first number.
Finally, n is assigned the value of (2 + 1) % 3, which evaluates back to
0.
Continue
You can use a continue-statement—a statement with the keyword
continue — to stop the current iteration of a loop and move on to the next
iteration of it. Say you want to print all the numbers from 1 to 5, except the
number 3. You can achieve this using a for-loop and a continue-
statement:
1 # http://tinyurl.com/hflun4p
2
3
4 for i in range(1, 6):
5 if i == 3:
6 continue
7 print(i)
>> 1
>> 2
>> 4
>> 5
You can achieve the same result using a while-loop and a continue-
statement:
1 # http://tinyurl.com/gp7forl
2
3
4 i = 1
5 while i <= 5:
6 if i == 3:
7 i += 1
8 continue
9 print(i)
10 i += 1
>> 1
>> 2
>> 4
>> 5
Nested Loops
You can combine loops in various ways. For example, you can have one loop
inside of a loop or a loop inside a loop inside a loop. There is no limit to the
number of loops you can have inside of other loops, although you want to
limit this. When a loop is inside another loop, the second loop is nested in the
first loop. In this situation, the loop with another loop inside it is called an
outer loop, and the nested loop is called an inner loop. When you have a
nested loop, the inner loop iterates through its iterable once for each time
around the outer loop:
1 # http://tinyurl.com/gqjxjtq
2
3
4 for i in range(1, 3):
5 print(i)
6 for letter in ["a", "b", "c"]:
7 print(letter)
>> 1
>> a
>> b
>> c
>> 2
>> a
>> b
>> c
The nested for-loop will iterate through the list ["a", "b", "c"]
however many times the outer loop runs—in this case, twice. If you changed
your outer loop to run three times, the inner loop would iterate through its list
three times as well.
You can use two for-loops to add each number in a list to all the numbers
in another list:
1 # http://tinyurl.com/z7duawp
2
3
4 list1 = [1, 2, 3, 4]
5 list2 = [5, 6, 7, 8]
6 added = []
7 for i in list1:
8 for j in list2:
9 added.append(i + j)
10
11
12 print(added)
The first loop iterates through every integer in list1. For each item in it,
the second loop iterates through each integer in its own iterable, adds it to the
integer from list1 and appends the result to the list added. I named the
variable j in the second for-loop, because I already used the variable
name i in the first loop.
1 # http://tinyurl.com/hnprmmv
2
3
4 while input('y or n?') != 'n':
5 for i in range(1, 6):
6 print(i)
>> y or n?y
1
2
3
4
5
y or n?y
1
2
3
4
5
y or n?n
>>>
This program will print the numbers 1–5 until the user enters n.
Vocabulary
Loop: A piece of code that continually executes instructions until a condition
defined in the code is satisfied.
Iterating: Using a loop to access each item in an iterable.
For-loop: A loop used to iterate through an iterable, like a string, list, tuple,
or dictionary.
Index variable: A variable that holds an integer representing an index in an
iterable.
While-loop: A loop that executes code as long as an expression evaluates to
True.
Infinite loop: A loop that never ends.
Break-statement: A statement with the keyword break in it used to
terminate a loop.
Continue-statement: A statement with the keyword continue used to stop
the current iteration of a loop and move on to the next iteration of it.
Outer loop: A loop with a nested loop inside it.
Inner loop: A loop nested in another loop.
Challenges
1. Print each item in the following list: ["The Walking Dead",
"Entourage", "The Sopranos", "The Vampire Diaries"].
2. Print all the numbers from 25 to 50.
3. Print each item in the list from the first challenge and their indexes.
4. Write a program with an infinite loop (with the option to type q to quit)
and a list of numbers. Each time through the loop ask the user to guess a
number on the list and tell them whether or not they guessed correctly.
5. Multiply all the numbers in the list [8, 19, 148, 4] with all the
numbers in the list [9, 1, 33, 83], and append each result to a third
list.
Solutions: http://tinyurl.com/z2m2ll5.
Chapter 8. Modules
"Perseverance and spirit have done wonders in all ages."
~ George Washington
Imagine you wrote a program with 10,000 lines of code. If you put all of the
code in one file, it would be difficult to navigate. Every time there was an
error or exception, you would have to scroll through 10,000 lines of code to
find the one line causing the problem. Programmers solve this issue by
dividing large programs into multiple pieces, called modules— another name
for a Python file with code in it—containing each piece. Python allows you to
use code from one module in another module. Python also has built-in
modules, modules that are built into Python and contain important
functionality. In this chapter, you learn about modules and how to use them.
1 # http://tinyurl.com/h3ds93u
2
3
4 import math
Once you've imported a module, you can use code from it with the syntax
[module_name].[code], replacing [module_name]with the name of
a module you already imported, and [code] with the name of the function
or variable you want to use from it. The following is an example of importing
and using the pow function from the math module, which takes two
parameters, x and y, and raises x by y:
1 # http://tinyurl.com/hyjo59s
2
3
4 import math
5
6
7 math.pow(2, 3)
>> 8.0
First, import the math module at the top of your file. You should import all
of your modules at the top of your file to make it easy to see which ones you
are using in your program. Next, call the pow function with math.pow(2,
3). The function returns 8.0 as the result.
The random module is another built-in module. You can use a function from
it called randint to generate a random integer: you pass it two integers,
and it returns a random integer between them:
1 # http://tinyurl.com/hr3fppn
2
3
4 # The output might not be 52
5 # when you run it—it's random!
6
7
8 import random
9
10
11 random.randint(0,100)
>> 52
1 # http://tinyurl.com/jrnznoy
2
3
4 import statistics
5
6 # mean
7 nums = [1, 5, 33, 12, 46, 33, 2]
8 statistics.mean(nums)
9
10
11 # median
12 statistics.median(nums)
13
14
15 # mode
16 statistics.mode(nums)
>> 18.857142857142858
>> 12
>> 33
1 # http://tinyurl.com/zjphfho
2
3
4 import keyword
5
6
7 keyword.iskeyword("for")
8 keyword.iskeyword("football")
>> True
>> False
1 # http://tinyurl.com/z5v9hk3
2
3
4 def print_hello():
5 print("Hello")
1 # http://tinyurl.com/j4xv728
2
3
4 import hello
5
6
7 hello.print_hello()
>> Hello
1 # http://tinyurl.com/zgyddhp
2
3
4 # code in module1
5 print("Hello!")
>> Hello!
1 # http://tinyurl.com/jamt9dy
2
3
4 # code in module2
5 import hello
>> Hello!
1 # http://tinyurl.com/j2xdzc7
2
3
4 # code in module1
5 if __name__ == "__main__":
6 print("Hello!")
>> Hello!
When you run this program, the output is still the
same. But when you import it from module2.py, the
code from module1.p no longer runs, and Hello! does
not print:
1 # http://tinyurl.com/jjccxds
2
3
4 # code in module2
5 import hello
Vocabulary
Module: Another name for a Python file with code in
it.
Built-in module: Modules that come with Python that
contain important functionality.
Import: Writing code that lets Python know where to
look for a module you plan on using.
Challenges
1. Call a different function from the statistics
module.
2. Create a module named cubed with a function that
takes a number as a parameter, and returns the
number cubed. Import and call the function from
another module.
Solutions: http://tinyurl.com/hlnsdot .
Chapter 9. Files
"Self-education is, I firmly believe, the only kind of education there is."
~ Isaac Asimov
You can use Python to work with files. For example, you can use Python to
read data from a file and to write data to a file. Reading data from a file
means accessing the file's data. Writing data to a file means adding or
changing data in the file. In this chapter, you will learn the basics of working
with files.
Writing to Files
The first step to working with a file is to open it with Python's built-in open
function. The open function takes two parameters: a string representing the
path to the file to open and a string representing the mode to open the file in.
The path to a file, or file path, represents the location on your computer
where a file resides. For example, /Users/bob/st.txt is the file path to
a file called st.txt. Each word separated by a slash is the name of a folder.
Together, it represents the location of a file. If a file path only has the name
of the file (with no folders separated by slashes), Python will look for it in
whatever folder you are running your program from. You should not write a
file path yourself. Unix-like operating systems and Windows use a different
number of backslashes in their file paths. To avoid problems with your
program working across different operating systems, you should always
create file paths using Python's built-in os module. The path function in
it takes each folder in a file path as a parameter and builds the file path for
you:
1 # http://tinyurl.com/hkqfkar
2
3
4 import os
5 os.path.join("Users",
6 "bob",
7 "st.txt")
>> 'Users/bob/st.txt'
Creating file paths with the path function ensures they will work on any
operating system. Working with file paths can still be tricky. Visit
http://theselftaughtprogrammer.io/filepaths if you are having trouble.
The mode you pass to the open function determines the actions you will be
able to perform on the file you open. Here are a few of the modes you can
open a file in:
"w" opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
"w+" opens a file for reading and writing. Overwrites the existing file if the
file exists. If the file does not exist, creates a new file for reading and
writing.5
The open function returns an object, called a file object, which you can use
to read and/or write to your file. When you use the mode "w", the open
function creates a new file, if it doesn't already exist, in the directory your
program is running in.
You can then use the write method on the file object to write to the file,
and the close method to close it. If you open a file using the open method,
you must close it with the close method. If you use the open method on
multiple files and forget to close them, it can cause problems in your
program. Here is an example of opening a file, writing to it, and closing it:
1 # http://tinyurl.com/zfgczj5
2
3
4 st = open("st.txt", "w")
5 st.write("Hi from Python!")
6 st.close()
In this example, you use the open function to open
the file and save the file object it returns in the
variable st. Then you call the write method on st,
which accepts a string as a parameter and writes it
to the new file Python created. Finally, you close
your file by calling the close method on the file
object.
1 # http://tinyurl.com/jt9guu2
2
3
4 with open("st.txt", "w") as f:
5 f.write("Hi from Python!")
As long as you are inside the with-statement, you
can access the file object—in this case, you named
it f. As soon as Python finishes running all the
code in the with-statement, Python closes the file
for you.
1 # http://tinyurl.com/hmuamr7
2
3
4 # make sure you've
5 # created the file from
6 # the previous example
7
8
9 with open("st.txt", "r") as f:
10 print(f.read())
1 # http://tinyurl.com/hkzhxdz
2
3
4 my_list = list()
5
6
7 with open("st.txt", "r") as f:
8 my_list.append(f.read())
9
10
11 print(my_list)
CSV Files
Python comes with a built-in module that allows you
to work with CSV files. A CSV file has a .csv
extension that separates data using commas (CSV
stands for Comma Separated Values). Programs that
manage spreadsheets like Excel often use CSV files.
Each piece of data separated by a comma in a CSV
file represents a cell in a spreadsheet, and every
line represents a row. A delimiter is a symbol, like
a comma or a vertical bar |, used to separate data
in a CSV file. Here are the contents of a CSV file
named self_taught.csv:
one,two,three
four,five,six
You could load this file into Excel, and one, two,
and three would each get cells in the first row of
the spreadsheet, and four, five, and six would each
get cells in the second row.
1 # http://tinyurl.com/go9wepf
2
3
4 import csv
5
6
7 with open("st.csv", "w", newline='') as f:
8 w = csv.writer(f,
9 delimiter=",")
10 w.writerow(["one",
11 "two",
12 "three"])
13 w.writerow(["four",
14 "five",
15 "six"])
one,two,three four,five,six
1 # http://tinyurl.com/gvcdgxf
2
3
4 # make sure you've created
5 # the file from the previous
6 # example
7
8
9 import csv
10
11
12 with open("st.csv", "r") as f:
13 r = csv.reader(f, delimiter=",")
14 for row in r:
15 print(",".join(row))
>> one,two,three
>> four,five,six
Challenges
1. Find a file on your computer and print its
contents using Python.
2. Write a program that asks a user a question, and
saves their answer to a file.
3. Take the items in this list of lists: [["Top
Gun", "Risky Business", "Minority Report"],
["Titanic", "The Revenant", "Inception"], ["Training
Day", "Man on Fire", "Flight"]] and write them to a
CSV file. The data from each list should be a row in
the file, with each item in the list separated by a
comma.
Solutions: http://tinyurl.com/hll6t3q.
Chapter 10.
Bringing It All Together
"All I have learned, I learned from books."
~ Abraham Lincoln
In this chapter, you are going to combine the concepts you've learned so far
and build a text-based game, the classic Hangman. If you've never played
Hangman, here's how it works:
1. Player One picks a secret word and draws a line for each letter in it (you
will use an underscore to represent each line).
2. Player Two tries to guess the word one letter at a time.
3. If Player Two guesses a letter correctly, Player One replaces the
corresponding underscore with the correct letter. In this version of the game,
if a letter appears twice in a word, you have to guess it twice.
OR
If Player Two guesses incorrectly, Player One draws a body part of a hanged
stick figure (starting with the head).
4. If Player Two completes the word before the drawing of the hangman is
complete, they win. If not, they lose.
In your program, the computer will be Player One, and the person guessing
will be Player Two. Are you ready to build Hangman?
Hangman
Here is the beginning of your Hangman code:
1 # http://tinyurl.com/jhrvs94
2
3
4 def hangman(word):
5 wrong = 0
6 stages = ["",
7 "________ ",
8 "| ",
9 "| | ",
10 "| 0 ",
11 "| /|\ ",
12 "| / \ ",
13 "| "
14 ]
15 rletters = list(word)
16 board = ["__"] * len(word)
17 win = False
18 print("Welcome to Hangman")
1 # http://tinyurl.com/ztrp5jc
2 while wrong < len(stages) - 1:
3 print("\n")
4 msg = "Guess a letter"
5 char = input(msg)
6 if char in rletters:
7 cind = rletters \
8 .index(char)
9 board[cind] = char
10 rletters[cind] = '$'
11 else:
12 wrong += 1
13 print((" ".join(board)))
14 e = wrong + 1
15 print("\n"
16 .join(stages[0: e]))
17 if "__" not in board:
18 print("You win!")
19 print(" ".join(board))
20 win = True
21 break
1 # http://tinyurl.com/zqklqxo
2 if not win:
3 print("\n"
4 .join(stages[0: \
5 wrong]))
6 print("You lose! It was {}."
7 .format(word))
1 # http://tinyurl.com/h9q2cpc
2
3
4 def hangman(word):
5 wrong = 0
6 stages = ["",
7 "________ ",
8 "| ",
9 "| | ",
10 "| 0 ",
11 "| /|\ ",
12 "| / \ ",
13 "| "
14 ]
15 rletters = list(word)
16 board = ["__"] * len(word)
17 win = False
18 print("Welcome to Hangman")
19 while wrong < len(stages) - 1:
20 print("\n")
21 msg = "Guess a letter"
22 char = input(msg)
23 if char in rletters:
24 cind = rletters \
25 .index(char)
26 board[cind] = char
27 rletters[cind] = '$'
28 else:
29 wrong += 1
30 print((" ".join(board)))
31 e = wrong + 1
32 print("\n"
33 .join(stages[0: e]))
34 if "__" not in board:
35 print("You win!")
36 print(" ".join(board))
37 win = True
38 break
39 if not win:
40 print("\n"
41 .join(stages[0: \
42 wrong]))
43 print("You lose! It was {}."
44 .format(word))
45
46
47 hangman("cat")
Challenge
1. Modify the game, so a word is selected randomly
from a list of words.
Solution: http://tinyurl.com/j7rb8or .
Chapter 11.
Practice
"Practice doesn't make perfect. Practice makes myelin, and myelin makes
perfect."
~Daniel Coyle
Read
1. http://programmers.stackexchange.com/questions/44177/what-is-the-
single-most-effective-thing-you-did-to-improve-your-programming-skil
Other Resources
I've compiled a list of programming resources at
http://www.theselftaughtprogrammer.io/resources.
Getting Help
If you get stuck, I have a few suggestions. First, post your question in the
Self-Taught Programmers Facebook group located at
https://www.facebook.com/groups/selftaughtprogrammers. The group is
a community of friendly programmers (and aspiring ones) that can help
answer any questions you have.
Learning to rely on other people's help was an important lesson for me.
Struggling to figure things out is a major part of the learning process; but at
some point, it becomes counterproductive. In the past, when I worked on
projects, I used to struggle beyond the point of productivity. If that happens
today, I post a question online, if I can't find the answer there already. Every
time I've posted a question online, someone has answered it. To that end, I
can't say enough about how helpful and friendly the programming
community is.
Chapter 12.
Programming Paradigms
"There are only two kinds of languages: the ones people complain about and
the ones nobody uses."
~Bjarne Stroustrup
State
One of the fundamental differences between the various programming
paradigms is the handling of state. State is the value of a program's variables
while it is running. Global state is the value of a program's global variables
while it is running.
Procedural Programming
In Part I, you programmed using the procedural programming paradigm: a
programming style in which you write a sequence of steps moving toward a
solution—with each step changing the program's state. In procedural
programming, you write code to "do this, then that":
1 # http://tinyurl.com/jv2rrl8
2
3
4 x = 2
5 y = 4
6 z = 8
7 xyz = x + y + z
8 xyz
>> 14
Each line of code in this example changes the program's state. First, you
define x, then y, then z. Finally, you define the value of xyz.
When you program procedurally, you store data in global variables and
manipulate it with functions:
1 # http://tinyurl.com/gldykam
2
3
4 rock = []
5 country = []
6
7
8 def collect_songs():
9 song = "Enter a song."
10 ask = "Type r or c. q to quit"
11
12
13 while True:
14 genre = input(ask)
15 if genre == "q":
16 break
17
18
19 if genre == "r":
20 rk = input(song)
21 rock.append(rk)
22
23
24 elif genre ==("c"):
25 cy = input(song)
26 country.append(cy)
27
28
29 else:
30 print("Invalid.")
31 print(rock)
32 print(country)
33
34
35 collect_songs()
Functional Programming
Functional programming originates from the lambda
calculus: the smallest universal programming
language in the world (created by the mathematician
Alonzo Church). Functional programming addresses the
problems that arise in procedural programming by
eliminating global state. A functional programmer
relies on functions that do not use or change global
state, the only state they use are the parameters
you pass to the function. The result a function
returns is usually passed on to another function. A
functional programmer can thus avoid global state by
passing it from function to function. Eliminating
global state removes side effects and the problems
that come with them.
1 # http://tinyurl.com/gu9jpco
2
3
4 a = 0
5
6
7 def increment():
8 global a
9 a += 1
1 # http://tinyurl.com/z27k2yl
2
3
4 def increment(a):
5 return a + 1
Object-Oriented Programming
The object-oriented programming paradigm also
addresses the problems that arise in procedural
programming by eliminating global state, but instead
of storing state in functions, it is stored in
objects. In object-oriented programming, classes
define a set of objects that can interact with each
other. Classes are a mechanism for the programmer to
classify and group together similar objects. Think
of a bag of oranges. Each orange is an object. All
oranges have the same attributes, such as color and
weight, but the values of these attributes vary from
one orange to the next. You can use a class to model
oranges and create orange objects with different
values. For instance, you can define a class that
allows you to create an orange object that is dark
orange and weighs 10 oz, and an orange object that
is light orange and weighs 12 oz.
1 # http://tinyurl.com/zrmjape
2
3
4 class Orange:
5 def __init__(self):
6 print("Created!")
1 # http://tinyurl.com/hrf6cus
2
3
4 class Orange:
5 def __init__(self, w, c):
6 self.weight = w
7 self.color = c
8 print("Created!")
1 # http://tinyurl.com/jlc7pvk
2
3
4 class Orange:
5 def __init__(self, w, c):
6 self.weight = w
7 self.color = c
8 print("Created!")
9
10
11 or1 = Orange(10, "dark orange")
12 print(or1)
>> Created!
>> <__main__.Orange object at 0x101a787b8>
1 # http://tinyurl.com/grwzeo4
2
3
4 class Orange:
5 def __init__(self, w, c):
6 self.weight = w
7 self.color = c
8 print("Created!")
9
10
11 or1 = Orange(10, "dark orange")
12 print(or1.weight)
13 print(or1.color)
>> Created!
>> 10
>> dark orange
1 # http://tinyurl.com/jsxgw44
2
3
4 class Orange:
5 def __init__(self, w, c):
6 self.weight = w
7 self.color = c
8 print("Created!")
9
10
11 or1 = Orange(10, "dark orange")
12 or1.weight = 100
13 or1.color = "light orange"
14
15
16 print(or1.weight)
17 print(or1.color)
>> Created!
>> 100
>> light orange
Although the instance variables color and weight
started with the values "dark orange" and 10, you
were able to change their values to "light orange"
and 100.
1 # http://tinyurl.com/jrmxlmo
2
3
4 class Orange:
5 def __init__(self, w, c):
6 self.weight = w
7 self.color = c
8 print("Created!")
9
10
11 or1 = Orange(4, "light orange")
12 or2 = Orange(8, "dark orange")
13 or3 = Orange(14, "yellow")
>> Created!
>> Created!
>> Created!
1 # http://tinyurl.com/zcp32pz
2
3
4 class Orange():
5 def __init__(self, w, c):
6 """weights are in oz"""
7 self.weight = w
8 self.color = c
9 self.mold = 0
10 print("Created!")
11
12
13 def rot(self, days, temp):
14 self.mold = days * temp
15
16
17 orange = Orange(6, "orange")
18 print(orange.mold)
19 orange.rot(10, 98)
20 print(orange.mold)
>> Created!
>> 0
>> 98.0
1 # http://tinyurl.com/j28qoox
2
3
4 class Rectangle():
5 def __init__(self, w, l):
6 self.width = w
7 self.len = l
8
9
10 def area(self):
11 return self.width * self.len
12
13
14 def change_size(self, w, l):
15 self.width = w
16 self.len = l
17
18
19 rectangle = Rectangle(10, 20)
20 print(rectangle.area())
21 rectangle.change_size(20, 40)
22 print(rectangle.area())
>> 200
>> 800
Vocabulary
Programming paradigm: A style of programming.
State: The value of a program's variables while it
is running.
Global state: The value of a program's global
variables while it is running.
Procedural programming: A programming style in which
you write a sequence of steps moving toward a
solution—with each step changing the program's
state.
Functional programming: Functional programming
addresses the problems that arise in procedural
programming by eliminating global state by passing
it from function to function.
Side effect: Changing the state of a global
variable.
Object-oriented: A programming paradigm where you
define objects that interact with each other.
Classes: A mechanism allowing the programmer to
classify and group together similar objects.
Methods: Methods are suites in a class. They are
like functions, but you define them inside of a
class, and you can only call them on the object the
class creates.
Instance: Every object is an instance of a class.
Every instance of a class has the same type as all
the other instances of that class.
Instance variables: Variables that belong to an
object.
Magic method: A method Python uses in different
situations, like initializing an object.
Instantiating a class: Creating a new object using a
class.
Challenges
1. Define a class called Apple with four instance
variables that represent four attributes of an
apple.
2. Create a Circle class with a method called area
that calculates and returns its area. Then create a
Circle object, call area on it, and print the
result. Use Python's pi function in the built-in
math module.
3. Create a Triangle class with a method called area
that calculates and returns its area. Then create a
Triangle object, call area on it, and print the
result.
4. Make a Hexagon class with a method called
calculate_perimeter that calculates and returns its
perimeter. Then create a Hexagon object, call
calculate_perimeter on it, and print the result.
Solutions: http://tinyurl.com/gpqe62e.
Chapter 13.
The Four Pillars of Object-Oriented Programming
"Good design adds value faster than it adds cost."
~Thomas C. Gale
Encapsulation
Encapsulation refers to two concepts. The first is that in object-oriented
programming, objects group variables (state) and methods (for altering state
or doing calculations that use state) in a single unit—the object:
1 # http://tinyurl.com/j74o5rh
2
3
4 class Rectangle():
5 def __init__(self, w, l):
6 self.width = w
7 self.len = l
8
9
10
11 def area(self):
12 return self.width * self.len
In this case, the instance variables len and width hold the object's state.
The object's state is grouped in the same unit (the object) as the method
area. The method uses the object's state to return the rectangle's area.
1 # http://tinyurl.com/jtz28ha
2
3
4 class Data:
5 def __init__(self):
6 self.nums = [1, 2, 3, 4, 5]
7
8
9 def change_data(self, index, n):
10 self.nums[index] = n
1 # http://tinyurl.com/huczqr5
2
3
4 class Data:
5 def __init__(self):
6 self.nums = [1, 2, 3, 4, 5]
7
8
9 def change_data(self, index, n):
10 self.nums[index] = n
11
12
13 data_one = Data()
14 data_one.nums[0] = 100
15 print(data_one.nums)
16
17
18 data_two = Data()
19 data_two.change_data(0, 100)
20 print(data_two.nums)
>> [100, 2, 3, 4, 5]
>> [100, 2, 3, 4, 5]
1 # http://tinyurl.com/jkaorle
2
3
4 class PublicPrivateExample:
5 def __init__(self):
6 self.public = "safe"
7 self._unsafe = "unsafe"
8
9
10 def public_method(self):
11 # clients can use this
12 pass
13
14
15 def _unsafe_method(self):
16 # clients shouldn't use this
17 pass
Abstraction
Abstraction is the process of "taking away or
removing characteristics from something in order to
reduce it to a set of essential characteristics."7
You use abstraction in object-oriented programming
when you model objects using classes and omit
unnecessary details.
Polymorphism
Polymorphism is "the ability (in programming) to
present the same interface for differing underlying
forms (data types)."8 An interface is a function or
a method. Here is an example of presenting the same
interface for different data types:
1 # http://tinyurl.com/hrxd7gn
2
3
4 print("Hello, World!")
5 print(200)
6 print(200.1)
1 # http://tinyurl.com/gnxq24x
2
3
4 type("Hello, World!")
5 type(200)
6 type(200.1)
1 # Do not run.
2
3
4
5 # Drawing shapes
6 # w/o polymorphism
7 shapes = [tr1, sq1, cr1]
8 for a_shape in shapes:
9 if type(a_shape) == "Triangle":
10 a_shape.draw_triangle()
11 if type(a_shape) == "Square":
12 a_shape.draw_square()
13 if type(a_shape) == "Circle":
14 a_shape.draw_circle()
15
16
17 # Drawing shapes
18 # with polymorphism
19 shapes = [tr1,
20 sw1,
21 cr1]
22 for a_shape in shapes:
23 a_shape.draw()
Inheritance
Inheritance in programming is similar to genetic
inheritance. In genetic inheritance, you inherit
attributes like eye color from your parents.
Similarly, when you create a class, it can inherit
methods and variables from another class. The class
that is inherited from is the parent class, and the
class that inherits is the child class. In this
section, you will model shapes using inheritance.
Here is a class that models a shape:
1 # http://tinyurl.com/zrnqeo3
2
3
4 class Shape():
5 def __init__(self, w, l):
6 self.width = w
7 self.len = l
8
9
10 def print_size(self):
11 print("""{} by {}
12 """.format(self.width,
13 self.len))
14
15
16 my_shape = Shape(20, 25)
17 my_shape.print_size()
>> 20 by 25
1 # http://tinyurl.com/j8lj35s
2
3
4 class Shape():
5 def __init__(self, w, l):
6 self.width = w
7 self.len = l
8
9
10 def print_size(self):
11 print("""{} by {}
12 """.format(self.width,
13 self.len))
14
15
16 class Square(Shape):
17 pass
18
19
20 a_square = Square(20,20)
21 a_square.print_size()
>> 20 by 20
1 # http://tinyurl.com/hwjdcy9
2
3
4 class Shape():
5 def __init__(self, w, l):
6 self.width = w
7 self.len = l
8
9
10 def print_size(self):
11 print("""{} by {}
12 """.format(self.width,
13 self.len))
14
15
16 class Square(Shape):
17 def area(self):
18 return self.width * self.len
19
20
21 a_square = Square(20, 20)
22 print(a_square.area())
>> 400
1 # http://tinyurl.com/hy9m8ht
2
3
4 class Shape():
5 def __init__(self, w, l):
6 self.width = w
7 self.len = l
8
9
10 def print_size(self):
11 print("""{} by {}
12 """.format(self.width,
13 self.len))
14
15
16 class Square(Shape):
17 def area(self):
18 return self.width * self.len
19
20
21 def print_size(self):
22 print("""I am {} by {}
23 """.format(self.width,
24 self.len))
25
26
27 a_square = Square(20, 20)
28 a_square.print_size()
>> I am 20 by 20
Composition
Now that you've learned about the four pillars of
object-oriented programming, I am going to cover one
more important concept: composition. Composition
models the "has a" relationship by storing an object
as a variable in another object. For example, you
can use composition to represent the relationship
between a dog and its owner (a dog has an owner). To
model this, first you define classes to represent
dogs and people:
1 # http://tinyurl.com/zqg488n
2
3
4 class Dog():
5 def __init__(self,
6 name,
7 breed,
8 owner):
9 self.name = name
10 self.breed = breed
11 self.owner = owner
12
13
14 class Person():
15 def __init__(self, name):
16 self.name = name
1 # http://tinyurl.com/zlzefd4
2 # Continue from
3 # last example
4
5
6 mick = Person("Mick Jagger")
7 stan = Dog("Stanley",
8 "Bulldog",
9 mick)
10 print(stan.owner.name)
Challenges
1. Create Rectangle and Square classes with a method
called calculate_perimeter that calculates the
perimeter of the shapes they represent. Create
Rectangle and Square objects and call the method on
both of them.
2. Define a method in your Square class called
change_size that allows you to pass in a number that
increases or decreases (if the number is negative)
each side of a Square object by that number.
3. Create a class called Shape. Define a method in
it called what_am_i that prints "I am a shape" when
called. Change your Square and Rectangle classes
from the previous challenges to inherit from Shape,
create Square and Rectangle objects, and call the
new method on both of them.
4. Create a class called Horse and a class called
Rider. Use composition to model a horse that has a
rider.
Solutions: http://tinyurl.com/hz9qdh3.
Chapter 14.
More Object-Oriented Programming
"Treat your code like poetry and take it to the edge of the bare minimum."
~Ilya Dorman
1 # http://tinyurl.com/h7ypzmd
2
3
4 class Square:
5 pass
6
7
8 print(Square)
In this example, the class Square is an object, and you printed it.
Classes have two types of variables: class variables and instance variables.
The variables you've seen so far have been instance variables, defined with
the syntax self.[variable_name] = [variable_value].
Instance variables belong to objects:
1 # http://tinyurl.com/zmnf47e
2
3
4 class Rectangle():
5 def __init__(self, w, l):
6 self.width = w
7 self.len = l
8
9
10 def print_size(self):
11 print("""{} by {}
12 """.format(self.width,
13 self.len))
14
15
16 my_rectangle = Rectangle(10, 24)
17 my_rectangle.print_size()
>> 10 by 24
1 # http://tinyurl.com/gu9unfc
2
3
4 class Rectangle():
5 recs = []
6
7
8 def __init__(self, w, l):
9 self.width = w
10 self.len = l
11 self.recs.append((self.width,
12 self.len))
13
14
15 def print_size(self):
16 print("""{} by {}
17 """.format(self.width,
18 self.len))
19
20
21 r1 = Rectangle(10, 24)
22 r2 = Rectangle(20, 40)
23 r3 = Rectangle(100, 200)
24
25
26 print(Rectangle.recs)
Magic Methods
Every class in Python inherits from a parent class
called Object. Python utilizes the methods inherited
from Object in different situations—like when you
print an object:
1 # http://tinyurl.com/ze8yr7s
2
3
4 class Lion:
5 def __init__(self, name):
6 self.name = name
7
8
9 lion = Lion("Dilbert")
10 print(lion)
1 # http://tinyurl.com/j5rocqm
2
3
4 class Lion:
5 def __init__(self, name):
6 self.name = name
7
8
9 def __repr__(self):
10 return self.name
11
12
13 lion = Lion("Dilbert")
14 print(lion)
>> Dilbert
1 # http://tinyurl.com/hlmhrwv
2
3
4 class AlwaysPositive:
5 def __init__(self, number):
6 self.n = number
7
8
9 def __add__(self, other):
10 return abs(self.n +
11 other.n)
12
13
14 x = AlwaysPositive(-20)
15 y = AlwaysPositive(10)
16
17
18 print(x + y)
>> 10
Is
The keyword is returns True if two objects are the
same object, and False if not:
1 # http://tinyurl.com/gt28gww
2
3
4 class Person:
5 def __init__(self):
6 self.name = 'Bob'
7
8
9 bob = Person()
10 same_bob = bob
11 print(bob is same_bob)
12
13
14 another_bob = Person()
15 print(bob is another_bob)
>> True
>> False
1 # http://tinyurl.com/jjettn2
2
3
4 x = 10
5 if x is None:
6 print("x is None :( ")
7 else:
8 print("x is not None")
9
10
11 x = None
12 if x is None:
13 print("x is None")
14 else:
15 print("x is None :( ")
Vocabulary
Class variable: A class variable belongs to a class
object and the objects it creates.
Instance variable: An instance variable belongs to
an object.
Private variables: A variable an object can access,
but the client cannot.
Private method: A method an object can access, but
the client cannot.
Public variable: A variable a client can access.
Challenges
1. Add a square_list class variable to a class
called Square so that every time you create a new
Square object, the new object gets added to the
list.
2. Change the Square class so that when you print a
Square object, a message prints telling you the len
of each of the four sides of the shape. For example,
if you create a square with Square(29) and print it,
Python should print 29 by 29 by 29 by 29.
3. Write a function that takes two objects as
parameters and returns True if they are the same
object, and False if not.
Solutions: http://tinyurl.com/j9qjnep.
Chapter 15.
Bringing It All Together
"It's all talk until the code runs."
~Ward Cunningham
In this chapter, you are going to create the popular card game War. In War,
each player draws a card from the deck, and the player with the highest card
wins. You will build War by defining classes representing a card, a deck, a
player, and finally, the game itself.
Cards
Here is a class that models playing cards:
1 # http://tinyurl.com/jj22qv4
2
3
4 class Card:
5 suits = ["spades",
6 "hearts",
7 "diamonds",
8 "clubs"]
9
10
11 values = [None, None,"2", "3",
12 "4", "5", "6", "7",
13 "8", "9", "10",
14 "Jack", "Queen",
15 "King", "Ace"]
16
17
18 def __init__(self, v, s):
19 """suit + value are ints"""
20 self.value = v
21 self.suit = s
22
23
24 def __lt__(self, c2):
25 if self.value < c2.value:
26 return True
27 if self.value == c2.value:
28 if self.suit < c2.suit:
29 return True
30 else:
31 return False
32 return False
33
34
35 def __gt__(self, c2):
36 if self.value > c2.value:
37 return True
38 if self.value == c2.value:
39 if self.suit > c2.suit:
40 return True
41 else:
42 return False
43 return False
44
45
46 def __repr__(self):
47 v = self.values[self.value] +\
48 " of " + \
49 self.suits[self.suit]
50 return v
1 # http://tinyurl.com/j6donnr
2
3
4 card1 = Card(10, 2)
5 card2 = Card(11, 3)
6 print(card1 < card2)
>> True
1 # http://tinyurl.com/hc9ktlr
2
3
4 card1 = Card(10, 2)
5 card2 = Card(11, 3)
6 print(card1 > card2)
>> False
1 # http://tinyurl.com/z57hc75
2
3
4 card = Card(3, 2)
5 print(card)
>> 3 of diamonds
Deck
Next, you need to define a class to represent a deck
of cards:
1 # http://tinyurl.com/jz8zfz7
2 from random import shuffle
3
4
5 class Deck:
6 def __init__(self):
7 self.cards = []
8 for i in range(2, 15):
9 for j in range(4):
10 self.cards\
11 .append(Card(i,
12 j))
13 shuffle(self.cards)
14
15
16 def rm_card(self):
17 if len(self.cards) == 0:
18 return
19 return self.cards.pop()
1 # http://tinyurl.com/hsv5n6p
2
3
4 deck = Deck()
5 for card in deck.cards:
6 print(card)
>> 4 of spades
>> 8 of hearts
…
Player
You need a class to represent each player in the
game to keep track of their cards and how many
rounds they've won:
1 # http://tinyurl.com/gwyrt2s
2
3
4 class Player:
5 def __init__(self, name):
6 self.wins = 0
7 self.card = None
8 self.name = name
Game
Finally, you need a class to represent the game:
1 # http://tinyurl.com/huwq8mw
2
3
4 class Game:
5 def __init__(self):
6 name1 = input("p1 name ")
7 name2 = input("p2 name ")
8 self.deck = Deck()
9 self.p1 = Player(name1)
10 self.p2 = Player(name2)
11
12
13 def wins(self, winner):
14 w = "{} wins this round"
15 w = w.format(winner)
16 print(w)
17
18
19 def draw(self, p1n, p1c, p2n, p2c):
20 d = "{} drew {} {} drew {}"
21 d = d.format(p1n,
22 p1c,
23 p2n,
24 p2c)
25 print(d)
26
27
28 def play_game(self):
29 cards = self.deck.cards
30 print("beginning War!")
31 while len(cards) >= 2:
32 m = "q to quit. Any " + \
33 "key to play:"
34 response = input(m)
35 if response == 'q':
36 break
37 p1c = self.deck.rm_card()
38 p2c = self.deck.rm_card()
39 p1n = self.p1.name
40 p2n = self.p2.name
41 self.draw(p1n,
42 p1c,
43 p2n,
44 p2c)
45 if p1c > p2c:
46 self.p1.wins += 1
47 self.wins(self.p1.name)
48 else:
49 self.p2.wins += 1
50 self.wins(self.p2.name)
51
52
53 win = self.winner(self.p1,
54 self.p2)
55 print("War is over.{} wins"
56 .format(win))
57
58
59 def winner(self, p1, p2):
60 if p1.wins > p2.wins:
61 return p1.name
62 if p1.wins < p2.wins:
63 return p2.name
64 return "It was a tie!"
Two cards are drawn each time through the loop, and
the play_game method assigns the first card to p1,
and the second card to p2. Then, it prints the name
of each player and the card they drew, compares the
two cards to see which card is greater, increments
the wins instance variable for the player with the
greater card, and prints a message that says who
won.
War
Here is the full game:
1 # http://tinyurl.com/ho7364a
2
3
4 from random import shuffle
5
6
7 class Card:
8 suits = ["spades",
9 "hearts",
10 "diamonds",
11 "clubs"]
12 values = [None, None,"2", "3",
13 "4", "5", "6", "7",
14 "8", "9", "10",
15 "Jack", "Queen",
16 "King", "Ace"]
17
18
19 def __init__(self, v, s):
20 """suit + value are ints"""
21 self.value = v
22 self.suit = s
23
24
25 def __lt__(self, c2):
26 if self.value < c2.value:
27 return True
28 if self.value == c2.value:
29 if self.suit < c2.suit:
30 return True
31 else:
32 return False
33 return False
34
35
36 def __gt__(self, c2):
37 if self.value > c2.value:
38 return True
39 if self.value == c2.value:
40 if self.suit > c2.suit:
41 return True
42 else:
43 return False
44 return False
45
46
47 def __repr__(self):
48 v = self.values[self.value] +\
49 " of " + \
50 self.suits[self.suit]
51 return v
52
53
54 class Deck:
55 def __init__(self):
56 self.cards = []
57 for i in range(2, 15):
58 for j in range(4):
59 self.cards\
60 .append(Card(i,
61 j))
62 shuffle(self.cards)
63
64
65 def rm_card(self):
66 if len(self.cards) == 0:
67 return
68 return self.cards.pop()
69
70
71 class Player:
72 def __init__(self, name):
73 self.wins = 0
74 self.card = None
75 self.name = name
76
77
78 class Game:
79 def __init__(self):
80 name1 = input("p1 name ")
81 name2 = input("p2 name ")
82 self.deck = Deck()
83 self.p1 = Player(name1)
84 self.p2 = Player(name2)
85
86
87 def wins(self, winner):
88 w = "{} wins this round"
89 w = w.format(winner)
90 print(w)
91
92
93 def draw(self, p1n, p1c, p2n, p2c):
94 d = "{} drew {} {} drew {}"
95 d = d.format(p1n,
96 p1c,
97 p2n,
98 p2c)
99 print(d)
100
101
102 def play_game(self):
103 cards = self.deck.cards
104 print("beginning War!")
105 while len(cards) >= 2:
106 m = "q to quit. Any " + \
107 "key to play:"
108 response = input(m)
109 if response == 'q':
110 break
111 p1c = self.deck.rm_card()
112 p2c = self.deck.rm_card()
113 p1n = self.p1.name
114 p2n = self.p2.name
115 self.draw(p1n,
116 p1c,
117 p2n,
118 p2c)
119 if p1c > p2c:
120 self.p1.wins += 1
121 self.wins(self.p1.name)
122 else:
123 self.p2.wins += 1
124 self.wins(self.p2.name)
125
126
127 win = self.winner(self.p1,
128 self.p2)
129 print("War is over.{} wins"
130 .format(win))
131
132
133 def winner(self, p1, p2):
134 if p1.wins > p2.wins:
135 return p1.name
136 if p1.wins < p2.wins:
137 return p2.name
138 return "It was a tie!"
139
140
141 game = Game()
142 game.play_game()
When I got my first programming job, I made the mistake of spending all of
my time practicing programming. Of course, you need to be a talented
programmer to program professionally. But there are also a variety of other
skills you need to have, like knowing how to use the command-line. The
command-line is the "control center" for everything you will be doing that
doesn't involve writing code.
For instance, later in this book you will learn to use package managers to
install other people's programs and version control systems to collaborate
with other programmers. You will operate both of these tools from the
command-line. Furthermore, most software written today involves accessing
data across the Internet, and the majority of the world's web servers run
Linux. These servers do not have a user interface; you can only access them
via the command-line.
If you are using Windows, you can use Amazon AWS to set up a free web
server running Ubuntu. Setting up a server is easy, and AWS is widely used
in the programing world, so it will give you valuable experience. Head to
http://theselftaughtprogrammer.io/aws to get started.
If you are using Windows, and you do not want to set up a server, you can
follow along with the examples by going to
http://theselftaughtprogrammer.io/bashapp, where you will find a link to a
web app that emulates Bash that you can use to follow along with most of the
examples.
After this chapter, you can follow along with the examples in the next two
chapters using Windows Command Prompt. You can find it by searching for
Command Prompt from the Run Window.
Finding Bash
You can find Bash on your computer by searching for Terminal from the
icon titled Search your computer and online resources if
you are using Ubuntu, or from Spotlight search if you are using a
Mac.
Commands
Bash is similar to the Python Shell. You type commands, which are like
functions in Python, into Bash. Then you type a space and the parameters you
want to pass to the command (if any). Hit the enter key, and Bash returns the
result. The command echo is similar to the print function in Python.
Whenever you see a dollar sign followed by a command, in either this book
or in programming documentation, it means you need to type the command
into the command-line:
# http://tinyurl.com/junx62n
First, you typed the command echo into Bash, followed by a space and
Hello, World! as a parameter. When you press enter, Hello,
World! prints in Bash.
You can use programs you've installed, like Python, from the command-line.
Enter the command python3 (As I am writing, the Bash Web App doesn't
come with Python 3. Type python to use Python 2 ):
# http://tinyurl.com/htoospk
$ python3
# http://tinyurl.com/jk2acua
print("Hello, World!")
Recent
You can scroll through your recent commands by
pressing the up and down arrows in Bash. To see a list
of all of your recent commands use the command
history:
# http://tinyurl.com/go2spbt
$ history
$ pwd
>> /Users/coryalthoff
Navigating
You can change directories by passing the command
cd an absolute or relative path as a parameter. Enter
the cd command followed by the absolute path / to
navigate to your operating system's root directory:
# http://tinyurl.com/hjgz79h
$ cd /
$ pwd
>> /
$ ls
$ cd ~
$ mkdir tstp
$ ls
>> tstp
$ cd tstp
You can use the cd command followed by two periods
to move back one directory (one level up the tree):
# http://tinyurl.com/z2gevk2
$ cd ..
$ rmdir tstp
$ ls
Flags
Commands have a concept called flags that allow the
issuer of the command to change the command's
behavior. Flags are options for commands that can
have a value of either True or False. By default, all
of a command's flags start set to False. If you add a
flag to a command, Bash sets the value of the flag to
True and the behavior of the command changes. To
set a flag to True, you put one (-) or two (--) hyphen
symbols in front of the name of the flag (depending on
the operating system).
$ ls -author
Hidden Files
Your operating system and many programs on your
computer store data in hidden files. Hidden files are
files that, by default, are not shown to users because
changing them could affect the programs that depend
on them. Hidden files start with a period, for example,
.hidden. You can view hidden files by adding the
flag -a, which stands for all, to the ls command. The
command touch creates a new file from the command
line.
$ touch .self_taught
Pipes
In Unix-like operating systems, the vertical bar
character (|) is called a pipe. You can use a pipe to
pass the output of a command to another command as
its input. For example, you can use the output of the ls
command as the input of the less command (make
sure you are not in an empty directory):
# http://tinyurl.com/zjne9f5
$ ls | less
>> Applications …
Environmental Variables
Environmental variables are variables, stored in your
operating system, that programs can use to get data
about the environment they are running in such as the
name of the computer the program is running on or the
name of the operating system user running the
program. You can create a new environmental variable
in Bash with the syntax export variable_name=
[variable_value]. To reference an
environmental variable in Bash, you must put a dollar
sign in front of its name:
# http://tinyurl.com/jjbc9v2
$ export x=100
$ echo $x
>> 100
$ echo $x
>> 100
Users
Operating systems can have multiple users. A user is a
person that uses the operating system. Each user is
assigned a username and password, which enables
them to log in and use the operating system. Each user
also has a set of permissions: operations they are
allowed to perform. You can print the name of your
operating system user with the command whoami (the
examples in this section will not work on Bash on
Windows or the Bash web app) :
1 $ whoami
>> coryalthoff
Learn More
I only covered the basics of Bash in this chapter. To
learn more about using Bash, visit
http://theselftaughtprogrammer.io/bash.
Vocabulary
Command-line interface: A command-line interface
is a program you type instructions into that your
operating system executes.
Command-line: Another name for a command-line
interface.
Bash: A program that comes with most Unix-like
operating systems that you type instructions into and
your operating system executes.
Command prompt: A command-line interface that
comes with Windows.
Directory: Another word for a folder on your
computer.
Working directory: The directory you are currently
in.
Path: A way of expressing the location in your
operating system of a file or directory.
Absolute path: The location of a file or directory
starting from the root directory.
Relative path: The location of a file or directory
starting from your current working directory.
Pipe: The character |. On Unix-like operating systems,
you can use a pipe to pass the output of a command to
another command as its input.
Environmental variables: Variables that your
operating system and other programs store data in.
$PATH: When you type a command into the Bash
command shell, it looks for the command in all the
directories stored in an environmental variable named
$PATH.
User: A person that uses the operating system.
Permissions: Operations operating system users are
allowed to do.
Root user: The highest-level user, the user with the
highest set of permissions.
Challenges
1. Print Self-taught in Bash.
2. Navigate to your home directory from another
directory using an absolute and relative path.
3. Create an environmental variable called
$python_projects that is an absolute path to the
directory where you keep your Python files. Save the
variable in your .profile file and then use the
command cd $python_projects to navigate
there.
Solutions: http://tinyurl.com/zdeyg8y.
Commands
Chapter 17.
Regular Expressions
"Talk is cheap. Show me the code."
~Linus Torvalds
Setup
To get started, create a file called zen.txt. From the command-line (make
sure you are inside the directory where you created zen.txt) enter the
command python3 -c "import this". This will print The Zen of
Python, a poem by Tim Peters:
The -c flag tells Python you are going to pass it a string containing Python
code. Python then executes the code. When Python executes import
this, it prints The Zen of Python (a message hidden in code like this
poem is called an Easter egg). Enter the function exit() into Bash to quit
Python, then copy and paste The Zen of Python into the file
zen.txt.
By default, on Ubuntu, the grep command prints matched words in red in its
output, but on Unix it does not. If you are using a Mac, you can change this
by setting the following environmental variables in Bash:
# http://tinyurl.com/z9prphe
$ export GREP_OPTIONS='--color=always'
$ export GREP_OPTIONS='--color=always'
A Simple Match
The grep command accepts two parameters: a regular expression and the
filepath of the file to search for the pattern defined in the regular expression.
The simplest kind of pattern to match with a regular expression is a simple
match, a string of words that matches the same string of words. To see an
example of a simple match, enter the following command in the directory
where you created the file zen.txt:
# http://tinyurl.com/jgh3x4c
$ grep Beautiful zen.txt
# http://tinyurl.com/j2z6t2r
# http://tinyurl.com/zchmrdq
By default, grep prints the entire line (of the file) it found a match in. You
can add the flag -o to only print the exact words that match the pattern you
pa
# http://tinyurl.com/zfcdnmx
>> Beautiful
You can use regular expressions in Python with its built-in library, re
(regular expressions). The re module comes with a method called
findall. You pass in a regular expression as a parameter, then a string and
it returns a list with all the items in the string that the pattern matches:
1 # http://tinyurl.com/z9q2286
2
3
4 import re
5
6
7 l = "Beautiful is better than ugly."
8
9
10 matches = re.findall("Beautiful", l)
11
12
13 print(matches)
>> ['Beautiful']
In this example, the findall method found a match and returned a list with
the match (Beautiful) as the first item.
1 # http://tinyurl.com/jzeonne
2
3
4 import re
5
6
7 l = "Beautiful is better than ugly."
8
9
10 matches = re.findall("beautiful",
11 l,
12 re.IGNORECASE)
13
14
15 print(matches)
>> ['Beautiful']
# http://tinyurl.com/gleyzan
Similarly, you can use the dollar sign ($) only to match the lines that end with
a pattern:
# http://tinyurl.com/zkvpc2r
In this case, grep ignored the line Namespaces are one honking
great idea -- let's do more of those! because, although it
contains the word idea, it does not end with it.
Here is an example of using the caret symbol (^) in Python (you have to pass
in re.MULTILINE as the third parameter to findall to look for matches
on all of the lines of a multi-line screen):
1 # http://tinyurl.com/zntqzc9
2
3
4 import re
5
6
7 zen = """Although never is
8 often better than
9 *right* now.
10 If the implementation
11 is hard to explain,
12 it's a bad idea.
13 If the implementation
14 is easy to explain,
15 it may be a good
16 idea. Namespaces
17 are one honking
18 great idea -- let's
19 do more of those!
20 """
21
22
23 m = re.findall("^If",
24 zen,
25 re.MULTILINE)
26 print(m)
# http://tinyurl.com/jf9qzuz
The output of the command echo is passed to grep as input and, therefore,
you don't need to specify the file parameter for grep. The command prints
both two and too, because the regular expression matches a t, followed by
an o or a w, followed by an o.
In Python:
1 # http://tinyurl.com/hg9sw3u
2
3
4 import re
5
6
7 string = "Two too."
8
9
10 m = re.findall("t[ow]o",
11 string,
12 re.IGNORECASE)
13 print(m)
# http://tinyurl.com/gm8o6gb
And \d in Python:
1 # http://tinyurl.com/z3hr4q8
2
3
4 import re
5
6
7 line = "123?34 hello?"
8
9
10 m = re.findall("\d",
11 line,
12 re.IGNORECASE)
13
14
15 print(m)
Repetition
The asterisk symbol (*) adds repetition to your regular expressions. With an
asterisk, "the preceding item will be matched zero or more times."12 For
instance, you can use an asterisk to match tw followed by any amount of os:
# http://tinyurl.com/j8vbwq8
$ echo two twoo not too. | grep -o two*
>> two
>> twoo
# http://tinyurl.com/h5x6cal
>> __hello__
# http://tinyurl.com/j9v9t24
>> __hi__bye__hi__
You do not always want to match patterns greedily. You can follow an
asterisk with a question mark to make the regular expression non-greedy. A
non-greedy regular expression looks for the least number of matches
possible. In this case, it would stop matching on the first double underscore it
comes across, instead of matching everything between the very first
underscore and the very last underscore. Grep does not have non-greedy
matching, but in Python, you can use a question mark for non-greedy
matching:
1 # http://tinyurl.com/j399sq9
2
3
4 import re
5
6
7 t = "__one__ __two__ __three__"
8
9
10 found = re.findall("__.*?__", t)
11
12
13 for match in found:
14 print(match)
>> __one__
>> __two__
>> __three__
You can use non-greedy matching in Python to create the game Mad Libs (if
you don't remember Mad Libs, it is a game with a paragraph of text with
various words missing that the players are prompted to fill in):
1 # http://tinyurl.com/ze6oyua
2
3 import re
4
5
6
7
8 text = """Giraffes have aroused
9 the curiosity of __PLURAL_NOUN__
10 since earliest times. The
11 giraffe is the tallest of all
12 living __PLURAL_NOUN__, but
13 scientists are unable to
14 explain how it got its long
15 __PART_OF_THE_BODY__. The
16 giraffe's tremendous height,
17 which might reach __NUMBER__
18 __PLURAL_NOUN__, comes from
19 it legs and __BODYPART__.
20 """
21
22
23 def mad_libs(mls):
24 """
25 :param mls: String
26 with parts the user
27 should fill out surrounded
28 by double underscores.
29 Underscores cannot
30 be inside hint e.g., no
31 __hint_hint__ only
32 __hint__.
33 """
34 hints = re.findall("__.*?__",
35 mls)
36 if hints is not None:
37 for word in hints:
38 q = "Enter a {}"\
39 .format(word)
40 new = input(q)
41 mls = mls.replace(word,
42 new,
43 1)
44 print('\n')
45 mls = mls.replace("\n", "")
46 print(mls)
47 else:
48 print("invalid mls")
49
50
51 mad_libs(text)
In this example, you use the re.findall method to get a list of all of the
words in the variable text surrounded by double underscores (each one is a
hint for the type of word the user needs to replace). Then, you loop through
the list and use each hint to ask the person using the program to supply a new
word. You then create a new string, replacing the hint with the user-supplied
word. Once the loop finishes, you print the new string with all of the words
you collected from the user.
Escaping
You can escape characters (ignore a character's meaning and match it instead)
in regular expressions like you did earlier with strings in Python, by prefixing
a character in a regular expression with a backslash \:
# http://tinyurl.com/zkbumfj
>> I love $
Normally, the dollar sign means a match is only valid if it occurs at the end of
the line, however, because you escaped it, your regular expression matches
the dollar sign character instead.
And in Python:
1 # http://tinyurl.com/zy7pr4l
2
3
4 import re
5
6
7 line = "I love $"
8
9
10 m = re.findall("\\$",
11 line,
12 re.IGNORECASE)
13
14
15 print(m)
>> ['$']
Vocabulary
Regular Expressions: A "sequence of characters that define a search
pattern."13
Easter egg: A message hidden in code.
Greedy: A regular expression that is greedy will try to match text as it can.
Non-greedy: A non-greedy regular expression looks for the least number of
matches possible.
Challenges
1. Write a regular expression that matches the word Dutch in The Zen of
Python.
2. Come up with a regular expression that matches all the digits in the string
Arizona 479, 501, 870. California 209, 213, 650.
3. Create a regular expression that matches any word that starts with any
character and is followed by two o's. Then use Python's re module to
match boo and loo in the sentence The ghost that says boo
haunts the loo.
Solutions: http://tinyurl.com/jmlkvxm.
ssed in:
Chapter 18.
Package Managers
"Every programmer is an author."
~Sercan Leylek
Packages
A package is software "packaged" for distribution—it includes the files that
make up the actual program, as well as metadata: data about data like the
software's name, version number, and dependencies: the programs a program
relies on to run properly. You can use a package manager to download a
package and install it as a program on your computer. The package manager
handles downloading any dependencies the package has.
Pip
In this section, I will show you how to use pip, a package manager for
Python, to download Python packages. Once you've downloaded a package
with pip, you can import it as a module in a Python program. First, check to
see if pip is installed on your computer by opening Bash, or the Command
Prompt if you are using Windows, and entering the command pip:
# http://tinyurl.com/hmookdf
$ pip
When you enter the command, a list of options should print. Pip comes with
Python when you download it, but it didn't in earlier versions. If nothing
happens when you enter the pip command, pip is not installed on your
computer. Visit http://www.theselftaughtprogrammerio/pip for instructions
on installing it.
# http://tinyurl.com/hchso7u
>> Password:
>> Successfully installed flask-0.11.1
# http://tinyurl.com/hyxm3vt
Now, you can import the Flask module in a program. Create a new Python
file, add the following code, and run the program:
1 # http://tinyurl.com/h59sdyu
2
3
4 from flask import Flask
5
6
7 app = Flask(__name__)
8
9
10 @app.route('/')
11 def index():
12 return "Hello, World!"
13
14
15 app.run(port='8000')
# http://tinyurl.com/zxgcqeh
pip freeze
>> Flask==0.11.11
…
# http://tinyurl.com/ht8mleo
Virtual Environments
Eventually, you will want to install your Python
packages into a virtual environment instead of
installing all of your packages into site-packages.
Virtual environments allow you to keep the Python
packages for your different programming projects
separate. You can learn more about virtual
environments at http://docs.python-
guide.org/en/latest/dev/virtualenvs.
Vocabulary
Package manager: A program that installs and manages
other programs.
Web framework: A program that helps you build a
website.
Package: Software "packaged" for distribution.
Metadata: Data about data.
Dependencies: The programs a program relies on to
run properly.
Apt-get: A package manager that comes with Ubuntu.
Pip: A package manager for Python.
$PYTHONPATH: Python looks for modules in a list of
folders stored in an environmental variable called
$PYTHONPATH.
Site-packages: A folder in $PYTHONPATH. This folder
is where pip installs packages.
PyPI: A website that hosts Python packages.
Virtual environment: You use a virtual environment
to keep the Python packages for your different
programming projects separate.
Challenge
1. Find a package on PyPI (https://pypi.python.org)
and download it with pip.
Solution: http://tinyurl.com/h96qbw2.
Chapter 19.
Version Control
"I object to doing things that computers can do."
~ Olin Shivers
Writing software is a team sport. When you are working on a project with
another person (or an entire team), you all need to be able to make changes to
the codebase—the folders and files that make up your software, and you
need to keep those changes in sync. You could periodically email each other
with your changes and combine multiple different versions yourself, but that
would be tedious.
Also, what would happen if you both made changes to the same part of the
project? How do you decide whose changes to use? These are the kinds of
problems a version control system solves. A version control system is a
program designed to help you easily collaborate on projects with other
programmers.
Git and SVN are two popular version control systems. Typically, you use a
version control system in conjunction with a service that stores your software
in the cloud. In this chapter, you will use Git to put software on GitHub, a
website that stores your code on the cloud.
Repositories
A repository is a data structure created by a version control system, like Git,
that keeps track of all the changes in your programming project. A data
structure is a way of organizing and storing information: lists and
dictionaries are examples of data structures (you will learn more about data
structures in Part IV). When you see a repository, it will look like a directory
with files in it. You will use Git to interact with the data structure that keeps
track of the project's changes.
When you are working on a project managed by Git, there will be multiple
repositories (usually one for each person working on the project). Typically,
everybody working on the project has a repository on their computer called a
local repository, which keeps track of all the changes they make to the
project. There is also a central repository, hosted on a website like GitHub,
that all the local repositories communicate with to stay in sync with each
other (each repository is completely separate). A programmer working on the
project can update the central repository with the changes they've made in
their local repository, and they can update their local repository with the
newest changes other programmers have made to the central repository. If
you are working on a project with one other programmer, your setup will
look like this:
You can create a new central repository from GitHub's website (or the
command-line). Once you create a central repository, you can use Git to
create a local repository that communicates with it.
Getting Started
If GitHub changes the layout of their website, the instructions in this section
will change. If that happens, I will provide new instructions at
http://theselftaughtprogrammer.io/git. To get started, you need to create a
GitHub account at https://github.com/join. To create a new repository on
GitHub, login to your GitHub account (once you have created it) and click on
the + button at the top right corner of the screen. Click New repository
from the drop-down menu. Give the repository the name hangman. Select
the Public option, and check the box Initialize the repository
with a README. Now, click Create repository.
On GitHub, hit the button in the top right corner and select Your profile.
You will see the name of your repository: hangman. Click on it. This part of
the website is your central repository. You will see a button that says Clone
Or Download. When you click on it, you will see a link. Save this link.
Before you can precede, you need to install Git. You can find installation
instructions at https://www.git-scm.com/book/en/v2/Getting-Started-
Installing-Git.
Once you have installed Git, you can use it from the command-line. Type
git into the command-line:
# http://tinyurl.com/gs9d5hf
$ git
If your output looks like this example, you've correctly installed Git.
Now you can use the link you found earlier to download a local repository to
your computer with the command git clone [repository_url].
The repository will download in whatever directory you issue the command
from. Copy the link, or press the copy link to clipboard button, and pass it to
the git clone command:
# http://tinyurl.com/hvmq98m
$ git clone [repository_url]
# http://tinyurl.com/gp4o9qv
$ ls
>> hangman
You should see a directory called hangman. This directory is your local
repository.
The command git remote -v (a common flag that usually prints extra
information and stands for verbose) prints the URL of the central repository
your local repository is pushing to and pulling from. Enter your hangman
directory and use the git remote command:
# http://tinyurl.com/jscq6pj
$ cd hangman
$ git remote -v
Pushing Example
In this section, you are going to make a change to the local hangman
repository you created and cloned to your computer, then push that change to
your central repository hosted on GitHub.
Move your Python file into the hangman directory with the code from the
challenge you completed at the end of Part I. Your local repository now has a
file that does not exist in your central repository—it is out of sync with your
central repository. You can resolve this by pushing the change you made in
your local repository to your central repository.
You push changes from your local repository to your central repository in
three steps. First, you stage your files: you tell Git which modified files you
want to push to your central repository.
The command git status shows the current state of your project in
relation to your repository, so you can decide what files to stage. The git
status command prints the files in your local repository that differ from
your central repository. When you unstage a file it is in red. When you stage
a file, it is in green. Make sure you are in your hangman directory and enter
the command git status:
# http://tinyurl.com/jvcr59w
$ git status
hangman.py
You should see the file hangman.py in red. You can stage a file with the
command git add [file]:
# http://tinyurl.com/hncnyz9
Now use the command git status to confirm you staged the file:
# http://tinyurl.com/jeuug7j
$ git status
You can unstage a file without making changes to your central repository
with the syntax git reset [file_path]. Unstage hangman.py
with:
# http://tinyurl.com/hh6xxvw
$ git status
hangman.py
Stage it again:
# http://tinyurl.com/gowe7hp
Once you've staged the files you want to update your central repository with,
you are ready to move to the next step, committing your files—giving a
command to Git to record the changes you made in your local repository.
You can commit your files with the syntax git commit -m
[your_message]. This command creates a commit: a version of your
project that Git saves. The -m flag means you are going to add a message to
your commit to help you remember what changes you are making and why
(this message is like a comment). In the next step, you are going to push your
changes to your central repository on GitHub, where you will be able to view
your message:
# http://tinyurl.com/gmn92p6
Once you've committed your files, you are ready for the final step. You can
now push your changes to your central repository with the command git
push origin master:
# http://tinyurl.com/hy98yq9
After you enter your username and password into the command-line, the git
program will push your changes to GitHub. If you look at your central
repository on GitHub's website, you will see hangman.py, as well as the
message you made in your commit.
Pulling Example
In this section, you are going to update your local repository by pulling the
changes from your central repository. You will need to do this whenever you
want to update your local repository with the changes another programmer
made to the central repository.
Go to your central repository and press the button Create new file.
Create a file called new.py and then press the button Commit new file.
This file is not yet in your local repository, so your local repository is out of
sync with your central repository. You can update your local repository with
changes from your central repository with the command git pull
origin master:
# http://tinyurl.com/gqf2xue
Git applied the changes from your central repository to your local repository.
The new.py file you created in your central repository should now be in
your local repository. Confirm with ls:
$bash $ ls
>> README.md hangman.py new.py
Reverting Versions
Git saves your project every time you commit a file. With Git, you can revert
to any previous commit—you can "rewind" your project. For example, you
can return your project back to a commit you made last week. All of your
files and folders will be the same as they were last week. Then you can
immediately jump forward to a more recent commit. Each commit has a
commit number: a unique sequence of characters that Git uses to identify a
You can view your project's history of commits with the command git
log, which prints all of your commits:
# http://tinyurl.com/h2m7ahs
$ git log
Create new.py
commit b0dab51849965144d78de21002464dc0f9297fdc
Author: Cory Althoff <coryalthoff@Corys-MacBook-
Pro.local> Date: Thu Dec 8 16:12:10 2016 -0800
my first commit
commit f5d44dab1418191f6c2bbfd4a2b2fcf74ef5a68f
Author: Cory Althoff <[email protected]>
Date: Thu Dec 8 15:53:25 2016 -0800 Initial commit
You should see three commits. Your first commit was when you created the
central repository. Your second commit was when you updated the central
repository with your hangman.py file. Your third commit was when you
created the file new.py. Each commit has a commit number. You can switch
your project to another commit by passing a commit number to the command
git checkout. In this example, I could revert my project to what it
looked like when I first created it with the command git checkout
f5d44dab1418191f6c2bbfd4a2b2fcf74ef5a68f.
diff
The command git diff shows you the difference between a file in your
local repository versus your central repository. Create a new file called
hello_world.py in your local repository, and add the code
print("Hello, World!") to it.
# http://tinyurl.com/h6msygd
# http://tinyurl.com/zg4d8vd
$ git status
# http://tinyurl.com/ztcm8zs
# http://tinyurl.com/zay2vct
# http://tinyurl.com/znvj9r8
$ git diff hello_world.py
Next Steps
In this chapter, I covered the features of Git you will use most frequently.
Once you've mastered the basics, I recommend you spend time learning about
Git's more advanced features like branching and merging at
http://theselftaughtprogrammer.io/git.
Vocabulary
Codebase: The folders and files that make up your software.
Version control system: A program designed to let you easily collaborate on
projects with other programmers.
Git: A popular version control system.
SVN: A popular version control system.
GitHub: A website that stores your code on the cloud.
Repository: A data structure created by a version control system, like Git,
that keeps track of the changes in your programming project.
Data structure: A way of organizing and storing information. Lists and
dictionaries are examples of data structures.
Local repository: The repository on your computer.
Central repository: A repository hosted on a website like GitHub that all of
the local repositories communicate with to stay in sync with each other.
Pushing: Updating your central repository with changes from your local
repository.
Pulling: Updating your local repository with changes from your central
repository.
Staging: Telling Git which files (with modifications) you want to push to
your central repository.
Committing: Giving a command that tells Git to record the changes you
made in your repository.
Commit: A version of your project that Git saves.
Commit number: A unique sequence of characters Git uses to identify a
commit.
Challenges
1. Create a new repository on GitHub. Put all your Python files from the
exercises you've completed so far into one directory on your computer and
push them to your new repository.
commit.
Chapter 20.
Bringing It All Together
"The magic of myth and legend has come true in our time. One types the
correct incantation on a keyboard, and a display screen comes to life,
showing things that never were nor could be..."
~ Frederick Brooks
In this chapter, you will see how powerful programming is by building a web
scraper: a program that extracts data from a website. Once you can build a
web scraper, you have the ability to collect data from the largest collection of
information in existence. The power of web scrapers, and how easy they are
to build, is one of the reasons I got hooked on programming, and I hope it has
the same effect on you.
HTML
Before you build a web scraper, you need a quick primer on HTML:
hypertext markup language. HTML is one of the fundamental technologies
programmers build websites with, along with CSS and JavaScript. HTML is a
language that gives a website structure. HTML is made up of tags a web
browser uses to layout web pages. You can build an entire website with
HTML. It won't be interactive or look very good, because JavaScript is what
makes websites interactive, and CSS is what gives them style, but it will be a
website. Here is a website that displays the text Hello, World!
# http://tinyurl.com/jptzkvp
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Website</title>
</head>
<body>
Hello, World!
<a href="https://www.google.com"/>
click here</a>
</body>
</html>
Save this HTML into a file. Open the file with your web browser by clicking
on the file (you may have to right-click and change the default program to
open the file with a web browser like Chrome). Once you've opened the file
with your web browser, you will see a website that says Hello World!
with a link to Google.
Your web browser uses the different HTML tags in your HTML file to
display this website. An HTML tag (tag for short) is like a programming
keyword—it tells your browser to do something. Most tags have a beginning
tag and closing tag, often with text in between. For example, your browser
displays the text in between the <title> </title> tags in the tab of
your browser. You can have tags within tags; everything in between
<head></head> is metadata about the web page, whereas everything in
between <body></body> makes up the actual site. Together, the <a>
</a> tags create a link. Tags can hold data. For example,
href="https://www.google.com" inside of the <a> tag lets the
browser know what website to link to. There is a lot more to HTML, but with
this knowledge you are ready to build your first web scraper.
# http://tinyurl.com/z4fzfzf
# http://tinyurl.com/hk3kxgr
Python has a built-in module, named urllib, for working with URLs. Add
the following code to a new Python file:
1 # http://tinyurl.com/jmgyar8
2
3
4 import urllib.request
5 from bs4 import BeautifulSoup
6
7
8 class Scraper:
9 def __init__(self,
10 site):
11 self.site = site
12
13
14 def scrape(self):
15 pass
The __init__ method takes a website to scrape from as a parameter. Later,
you will pass in "https://news.google.com/" as a parameter. The
Scraper class has a method called scrape you will call whenever you
want to scrape data from the site you passed in.
1 # http://tinyurl.com/h5eywoa
2
3
4 def scrape(self):
5 r = urllib.request\
6 .urlopen(self.site)
7 html = r.read()
Now you are ready to parse the HTML. Add a new line of code in the
scrape function that creates a BeautifulSoup object, and pass in
the html variable and the string "html.parser"(because you are parsing
HTML) as a parameter:
1 # http://tinyurl.com/hvjulxh
2
3
4 def scrape(self):
5 r = urllib.request\
6 .urlopen(self.site)
7 html = r.read()
8 parser = "html.parser"
9 sp = BeautifulSoup(html,
10 parser)
The BeautifulSoup object does all the hard work and
parses the HTML. Now you can add code to the scrape
function that calls the method find_all on the
BeautifulSoup object. Pass in "a" as a parameter
(which tells the function to look for <a></a> tags)
and the method will return all of the URLs the
website links to in the HTML you downloaded:
1 # http://tinyurl.com/zwrxjjk
2
3
4 def scrape(self):
5 r = urllib.request\
6 .urlopen(self.site)
7 html = r.read()
8 parser = "html.parser"
9 sp = BeautifulSoup(html,
10 parser)
11 for tag in sp.find_all("a"):
12 url = tag.get("href")
13 if url is None:
14 continue
15 if "html" in url:
16 print("\n" + url)
1 # http://tinyurl.com/j55s7hm
2
3
4 import urllib.request
5 from bs4 import BeautifulSoup
6
7
8 class Scraper:
9 def __init__(self, site):
10 self.site = site
11
12
13 def scrape(self):
14 r = urllib.request\
15 .urlopen(self.site)
16 html = r.read()
17 parser = "html.parser"
18 sp = BeautifulSoup(html,
19 parser)
20 for tag in sp.find_all("a"):
21 url = tag.get("href")
22 if url is None:
23 continue
24 if "html" in url:
25 print("\n" + url)
26
27
28 news = "https://news.google.com/"
29 Scraper(news).scrape()
https://www.washingtonpost.com/world/national-
security/in-foreign-bribery-cases-leniency-offered-
to-companies-that-turn-over-
employees/2016/04/05/d7a24d94-fb43-11e5-9140-
e61d062438bb_story.html
http://www.appeal-democrat.com/news/unit-apartment-
complex-proposed-in-marysville/article_bd6ea9f2-
fac3-11e5-bfaf-4fbe11089e5a.html
http://www.appeal-democrat.com/news/injuries-from-
yuba-city-bar-violence-hospitalize-groom-to-
be/article_03e46648-f54b-11e5-96b3-5bf32bfbf2b5.html
Vocabulary
Web scraper: A program that extracts data from a
website.
HTML: A language that gives a website structure.
HTML Tag: Like a programming keyword—it tells your
browser to do something.
Parse: Parsing means taking a format like HTML and
using a programming language to give it structure.
For example, turning the data into an object.
Challenge
1. Modify your scraper to save the headlines in a
file.
Challenge solution: http://tinyurl.com/gkv6fuh.
Chapter 21.
Data Structures
"I will, in fact, claim that the difference between a bad programmer and a
good one is whether he considers his code or his data structures more
important. Bad programmers worry about the code. Good programmers
worry about data structures and their relationships."
~ Linus Torvalds
Data Structures
A data structure is a format used to store and organize information. Data
structures are fundamental to programming, and most programming
languages come with them built-in. You already know how to use several of
Python's built-in data structures, such as lists, tuples, and dictionaries. In this
chapter, you will learn how to create two more data structures: stacks and
queues.
Stacks
A stack is a data structure. Like a list, you can add and remove items from a
stack, except unlike a list, you can only add and remove the last item. If you
have the list [1, 2, 3], you can remove any of the items in it. If you have
a stack that is the same, you can only remove the last item in it, 3. If you
remove the 3, your stack looks like [1, 2]. Now you can remove the 2.
Once you've removed the 2, you can remove the 1, and the stack is empty.
Removing an item from a stack is called popping. If you put 1 back on the
stack, it looks like [1]. If you put a two onto the stack, it looks like [1,
2]. Putting an item onto a stack is called pushing. This kind of data
structure, where the last item put in is the first item taken out, is called a last-
in-first-out data structure (LIFO).
You can think of a LIFO like a stack of dishes. If you stack five dishes on top
of each other, you would have to remove all the other dishes to get to the one
on the bottom of the stack. Think of every piece of data in a stack like a dish,
to access it you have to pull out the data at the top.
In this section, you are going to build a stack. Python has a library with both
of the data structures I cover in this chapter, but building your own will show
you how they work. The stack will have five methods: is_empty, push,
pop, and size. The method is_empty returns True if your stack is
empty and False otherwise. push adds an item to the top of your stack.
pop removes and returns the top item from your stack. peek returns the top
item in the stack, but does not remove it. size returns an integer
representing the number of items in your stack. Here is a stack implemented
in Python:
1 # http://tinyurl.com/zk24ps6
2
3
4 class Stack:
5 def __init__(self):
6 self.items = []
7
8
9 def is_empty(self):
10 return self.items == []
11
12
13 def push(self, item):
14 self.items.append(item)
15
16
17 def pop(self):
18 return self.items.pop()
19
20
21 def peek(self):
22 last = len(self.items)-1
23 return self.items[last]
24
25
26 def size(self):
27 return len(self.items)
1 # http://tinyurl.com/jfybm4v
2
3
4 stack = Stack()
5 print(stack.is_empty())
>> True
1 # http://tinyurl.com/zsexcal
2
3
4 stack = Stack()
5 stack.push(1)
6 print(stack.is_empty())
>> False
1 # http://tinyurl.com/j72kswr
2
3
4 stack = Stack()
5 stack.push(1)
6 item = stack.pop()
7 print(item)
8 print(stack.is_empty())
>> 1
>> True
1 # http://tinyurl.com/zle7sno
2
3
4 stack = Stack()
5
6
7 for i in range(0, 6):
8 stack.push(i)
9
10
11 print(stack.peek())
12 print(stack.size())
>> 5
>> 6
1 # http://tinyurl.com/zoosvqg
2
3
4 class Stack:
5 def __init__(self):
6 self.items = []
7
8
9 def is_empty(self):
10 return self.items == []
11
12
13 def push(self, item):
14 self.items.append(item)
15
16
17 def pop(self):
18 return self.items.pop()
19
20
21 def peek(self):
22 last = len(self.items)-1
23 return self.items[last]
24
25
26 def size(self):
27 return len(self.items)
28
29
30 stack = Stack()
31 for c in "Hello":
32 stack.push(c)
33
34
35 reverse = ""
36
37
38 for i in range(len(stack.items)):
39 reverse += stack.pop()
40
41
42 print(reverse)
>> olleH
Queues
A queue is another data structure. A queue is also
like a list; you can add and remove items from it. A
queue is also like a stack because you can only add
and remove items in a certain order. Unlike a stack,
where the first item put in is the last out, a queue
is a first-in-first-out data structure (FIFO): the
first item added is the first item taken out.
1 # http://tinyurl.com/zrg24hj
2
3
4 class Queue:
5 def __init__(self):
6 self.items = []
7
8
9 def is_empty(self):
10 return self.items == []
11
12
13 def enqueue(self, item):
14 self.items.insert(0, item)
15
16
17 def dequeue(self):
18 return self.items.pop()
19
20
21 def size(self):
22 return len(self.items)
1 # http://tinyurl.com/j3ck9jl
2
3
4 a_queue = Queue()
5 print(a_queue.is_empty())
>> True
1 # http://tinyurl.com/jzjrg8s
2
3
4 a_queue = Queue()
5
6
7 for i in range(5):
8 a_queue.enqueue(i)
9
10
11 print(a_queue.size())
>> 5
1 # http://tinyurl.com/jazkh8b
2
3
4 a_queue = Queue()
5
6
7 for i in range(5):
8 a_queue.enqueue(i)
9
10
11 for i in range(5):
12 print(a_queue.dequeue())
13
14
15 print()
16
17
18 print(a_queue.size())
>> 0
>> 1
>> 2
>> 3
>> 4
>>
>> 0
Ticket Queue
A queue can simulate people waiting in line to buy
tickets for a movie:
1 # http://tinyurl.com/jnw56zx
2
3
4 import time
5 import random
6
7
8 class Queue:
9 def __init__(self):
10 self.items = []
11
12
13 def is_empty(self):
14 return self.items == []
15
16
17 def enqueue(self, item):
18 self.items.insert(0, item)
19
20
21 def dequeue(self):
22 return self.items.pop()
23
24
25 def size(self):
26 return len(self.items)
27
28
29 def simulate_line(self,
30 till_show,
31 max_time):
32 pq = Queue()
33 tix_sold = []
34
35
36 for i in range(10):
37 pq.enqueue("person"
38 + str(i))
39
40
41 t_end = time.time()\
42 + till_show
43 now = time.time()
44 while now < t_end \
45 and not pq.is_empty():
46 now = time.time()
47 r = random.\
48 randint(0,
49 max_time)
50 time.sleep(r)
51 person = pq.dequeue()
52 print(person)
53 tix_sold.append(person)
54
55
56 return tix_sold
57
58
59 queue = Queue()
60 sold = queue.simulate_line(5, 1)
61 print(sold)
>> person0
…
>> ['person0', 'person1', 'person2']
Vocabulary
Data structure: A format used to store and organize
information.
Popping: Removing an item from a stack.
Pushing: Putting an item onto a stack.
Last-in-first-out data structure: A data structure
where the last item put in is the first item taken
out.
LIFO: Last-in-first-out
Stack: A last-in-first-out data structure data
structure.
First-in-first-out data structure: A data structure
where the first item added is the first item taken
out.
FIFO: First-in-first-out
Queue: A first-in-first-out data structure.
Epoch: A point in time used as a reference.
Challenges
1. Reverse the string "yesterday" using a stack.
2. Use a stack to create a new list with the items
in the following list reversed: [1, 2, 3, 4, 5].
Solutions: http://tinyurl.com/j7d7nx2.
Chapter 22. Algorithms
"An algorithm is like a recipe."
~ Waseem Latif
FizzBuzz
It's finally time to learn to solve FizzBuzz, the popular interview question
designed to eliminate candidates:
Write a program that prints the numbers from 1 to 100. But for multiples of
three print "Fizz" instead of the number, and for the multiples of five print
"Buzz." For multiples of both three and five print "FizzBuzz."
1 # http://tinyurl.com/jroprmn
2
3
4 def fizz_buzz():
5 for i in range(1, 101):
6 if i % 3 == 0 \
7 and i % 5 == 0:
8 print("FizzBuzz")
9 elif i % 3 == 0:
10 print("Fizz")
11 elif i % 5 == 0:
12 print("Buzz")
13 else:
14 print(i)
15
16
17 fizz_buzz()
>> 1
>> 2
>> Fizz
…
You start by iterating through numbers 1 to 100. Then, you check if the
number is divisible by 3 and5. It is important to do this first, because if a
number is divisible by both, you need to print FizzBuzz and continue to the
next iteration of the loop. If you checked if a number was divisible by just 3
or 5 first, and found a number that was, you cannot print Fizz or Buzz and
continue to the next iteration of the loop, because the number could still be
divisible by 3 and 5, in which case printing Fizz or Buzz is incorrect; you
need to print FizzBuzz
Sequential Search
A search algorithm finds information in a data
structure like a list. A sequential search is a
simple search algorithm that checks each item in a
data structure to see if the item matches what it is
looking for.
If you were ever playing cards and looking for a
specific card in the deck, you probably did a
sequential search to find it. You went through each
card in the deck one by one, and if the card was not
the one you were looking for, you moved on to the
next card. When you finally came to the card you
wanted, you stopped. If you made it through the
entire deck without finding the card, you also
stopped, because you realized the card wasn't there.
Here is an example of a sequential search in Python:
1 # http://tinyurl.com/zer9esp
2
3
4 def ss(number_list, n):
5 found = False
6 for i in number_list:
7 if i == n:
8 found = True
9 break
10 return found
11
12
13 numbers = range(0, 100)
14 s1 = ss(numbers, 2)
15 print(s1)
16 s2 = ss(numbers, 202)
17 print(s2)
>> True
>> False
Palindrome
A palindrome is a word spelled the same way forward
and backward. You can write an algorithm that checks
if a word is a palindrome by reversing all the
letters in the word and testing if the reversed word
and the original word are the same. If they are, the
word is a palindrome:
1 # http://tinyurl.com/jffr7pr
2
3
4 def palindrome(word):
5 word = word.lower()
6 return word[::-1] == word
7
8
9 print(palindrome("Mother"))
10 print(palindrome("Mom"))
>> False
>> True
Anagram
An anagram is a word created by rearranging the
letters of another word. The word iceman is an
anagram of cinema, because you can rearrange the
letters in either word to form the other. You can
determine if two words are anagrams by sorting the
letters in each word alphabetically and testing if
they are the same:
1 # http://tinyurl.com/hxplj3z
2
3
4 def anagram(w1, w2):
5 w1 = w1.lower()
6 w2 = w2.lower()
7 return sorted(w1) == sorted(w2)
8
9
10 print(anagram("iceman", "cinema"))
11 print(anagram("leaf", "tree"))
>> True
>> False
1 # http://tinyurl.com/zknqlde
2
3
4 def count_characters(string):
5 count_dict = {}
6 for c in string:
7 if c in count_dict:
8 count_dict[c] += 1
9 else:
10 count_dict[c] = 1
11 print(count_dict)
12
13
14 count_characters("Dynasty")
Recursion
Recursion is a method of solving problems by
breaking the problem up into smaller and smaller
pieces until it can be easily solved. So far, you've
solved problems using iterative algorithms.
Iterative algorithms solve problems by repeating
steps over and over, typically using a loop.
Recursive algorithms rely on functions that call
themselves. Any problem you can solve iteratively
can be solved recursively; however, sometimes a
recursive algorithm is a more elegant solution.
1 # http://tinyurl.com/z49qe4s
2
3
4 def bottles_of_beer(bob):
5 """ Prints 99 Bottle
6 of Beer on the
7 Wall lyrics.
8 :param bob: Must
9 be a positive
10 integer.
11 """
12 if bob < 1:
13 print("""No more
14 bottles
15 of beer
16 on the wall.
17 No more
18 bottles of
19 beer.""")
20 return
21 tmp = bob
22 bob -= 1
23 print("""{} bottles of
24 beer on the
25 wall. {} bottles
26 of beer. Take one
27 down, pass it
28 around, {} bottles
29 of beer on the
30 wall.
31 """.format(tmp,
32 tmp,
33 bob))
34 bottles_of_beer(bob)
35
36
37
38
39 bottles_of_beer(99)
1 # http://tinyurl.com/h4k3ytt
2
3
4 if bob < 1:
5 print("""No more
6 bottles
7 of beer
8 on the wall.
9 No more
10 bottles of
11 beer.""")
12 return
1 # http://tinyurl.com/j7zwm8t
2
3
4 bottles_of_beer(bob)
Vocabulary
Algorithm: A series of steps that can be followed to
solve a problem.
Search algorithm: An algorithm that finds
information in a data structure (like a list).
Sequential search: A simple search algorithm for
finding information in a data structure that checks
each item in it to see if it matches what it is
looking for.
Palindrome: A word spelled the same forward and
backward.
Anagram: A word created by rearranging the letters
of another word.
Recursion: A method of solving problems by breaking
the problem up into smaller and smaller pieces until
it can be easily solved.
Iterative algorithm: Iterative algorithms solve
problems by repeating steps over and over, typically
using a loop.
Recursive algorithm: Recursive algorithms solve
problems using functions that call themselves.
Base case: A condition that ends a recursive
algorithm.
Challenge
1. Sign up for an account at http://leetcode.com,
and try to solve three of their easy-level algorithm
problems.
.
Chapter 23.
Best Programming Practices
"Always code as if the guy who ends up maintaining your code will be a
violent psychopath who knows where you live."
~John Woods
Production code is the code in a product people use. When you put software
into production, it means putting it out in the world. In this chapter, I cover a
few general programming principles that will help you write production-
ready code. Many of these principles originated in The Pragmatic
Programmer by Andy Hunt and Dave Thomas, a book that dramatically
improved the quality of my code.
DRY
DRY is a programming principle that stands for Don't Repeat Yourself. Do
not repeat the same, or nearly the same, code in a program. Instead, put the
code into one function that can handle multiple situations.
Orthogonality
Orthogonality is another important programming principle popularized by
The Pragmatic Programmer. Hunt and Thomas explain, "In
computing, the term has come to signify a kind of independence or
decoupling. Two or more things are orthogonal if changes in one do not
affect any of the others. In a well-designed system, the database code will be
orthogonal to the user interface: you can change the interface without
affecting the database, and swap databases without changing the interface."16
Put this in practice by remembering as much as possible that "a should not
affect b." If you have two modules—module a and module b—module
a should not make changes to things in module b, and vice versa. If you
design a system where a affects b; which affects c; which affects d; things
quickly spiral out of control and the system becomes unmanageable.
Follow Conventions
Taking time to learn the conventions of the new programming language will
help you read code written in the new language faster. PEP 8 is a set of
guidelines for writing Python code, and you should read it. It includes the
rules for extending Python code to new lines. It's available at
https://www.python.org/dev/peps/pep-0008/.
I use an IDE called PyCharm created by JetBrains. They offer a free version
as well as a professional version. I made a list of the features of PyCharm that
save me the most time:
2. In your workflow, you are probably copying and pasting code a lot. In
PyCharm, instead of copying and pasting, you can move code up and down
on the page you a
1. PyCharm supports version control systems like Git and SVN. Instead of
going to the command-line, you can use Git from PyCharm. The fewer trips
you have to make back and forth between your IDE and the command-line,
the more productive you will be.
Logging
Logging is the practice of recording data when your software runs. You can
use logging to help debug your program and gain additional insight into what
happened when your program ran. Python comes with a logging module
that lets you log to the console or a file.
When something goes wrong in your program, you don't want it to go
unnoticed—you should log information about what happened to review later.
Logging is also useful for collecting and analyzing data. For example, you
might set up a web server to log data—including the date and time—every
time it receives a request. You could store all of your logs in a database, and
create another program to analyze the data and create a graph displaying the
times of day people visit your website.
The blogger Henrik Warne writes, "One of the differences between a great
programmer and a bad programmer is that a great programmer adds logging
and tools that make it easy to debug the program when things fail." You can
learn how to use Python's logging module at
https://docs.python.org/3/howto/logging.html.
Testing
Testing a program means checking that the program "meets the requirements
that guided its design and development, responds correctly to all kinds of
inputs, performs its functions within an acceptable time, is sufficiently
usable, can be installed and run in its intended environments, and achieves
the general result its stakeholders desire."17 To test their programs,
programmers write more programs.
Code Reviews
In a code review someone reads your code and gives feedback. You should
do as many code reviews as you can—especially as a self-taught
programmer. Even if you follow all the best practices laid out in this chapter,
you are going to do things incorrectly. You need someone with experience to
read over your code and tell you the mistakes you are making, so you can fix
them.
Code Review is a website where you can get code reviews from a community
of programmers. Anyone can go on Code Review and post their code. Other
members of the Stack Exchange community review your code, give you
feedback about what you did well, and offer helpful suggestions on how you
can improve. You can visit Code Review at
http://codereview.stackexchange.com/.
Security
Security is an easy subject for the self-taught programmer to ignore. You
probably won't be asked about security in interviews, and security is not
important for the programs you write while you are learning to program.
However, once you get your first programming job, you are directly
responsible for the security of the code you write. In this section, I provide
some tips to keep your code safe.
Earlier, you learned to use sudo to issue a command as the root user. Never
run a program from the command-line using sudo if you don't have to
because a hacker will have root access if they compromise the program. You
should also disable root logins if you are managing a server. Every hacker is
aware there is a root account, so it is an easy target when attacking a system.
Another strategy for keeping your software secure is to minimize your attack
surface—the different areas of your program where attackers could extract
data or attack your system. By making your attack area as small as possible,
you reduce the likelihood of vulnerabilities in your program. Some strategies
for minimizing your attack surface: avoid storing confidential data if you
don't have to, give users the lowest level of access you can, use as few third-
party libraries as possible (the less code, the less amount of possible
exploits), and get rid of features that are no longer being used (less code, less
exploits).
Avoiding logging in as the root user on your system, not trusting user input,
and minimizing your attack surface are important steps to making sure your
programs are secure. But these are just starting points. You should always try
to think like a hacker. How would a hacker exploit your code? Thinking like
this can help you find vulnerabilities you otherwise would overlook. There is
a lot more to learn about security than I can cover in this book, so always be
thinking and learning about it. Bruce Schneier said it best—"Security is a
state of mind."
Vocabulary
Production code: The code in a product people use.
Production: When you put software into production, it means putting it out
in the world.
DRY: A programming principle that stands for Don't Repeat Yourself.
Orthogonality: "In computing, the term has come to signify a kind of
independence or decoupling. Two or more things are orthogonal if changes in
one do not affect any of the others. In a well-designed system, the database
code will be orthogonal to the user interface: you can change the interface
without affecting the database, and swap databases without changing the
interface."18
Debugger: A debugger is a program that allows you to stop the execution of
your code and move through your program line by line so you can see the
values of the variables in your code at different parts of your program.
Logging: The practice of recording data when your software runs.
Testing: Checking that the program "meets the requirements that guided its
design and development, responds correctly to all kinds of inputs, performs
its functions within an acceptable time, is sufficiently usable, can be installed
and run in its intended environments, and achieves the general result its
stakeholders desire." 19
Code review: When someone reads your code and gives you feedback.
Attack surface: The different areas of your program where attackers could
extract data or attack your system.
re on.
Chapter 24.
Your First Programming Job
"Beware of ‘the real world.' A speaker's appeal to it is always an invitation
not to challenge his tacit assumptions."
~ Edsger W. Dijkstra
The final part of this book is dedicated to helping you with your career.
Getting your first programming job requires extra effort, but if you follow my
advice, you should have no problem. Luckily, once you land your first
programming job and get some experience, when it comes time to look for
your next job, recruiters will be reaching out to you.
Choose a Path
When you apply for a programming job, you will be expected to know a
particular set of technologies, depending on the domain the job is in. While
it's fine to be a generalist (a programmer who dabbles in everything) while
you are learning to program, and it is possible to get a job as a generalist
programmer, you should probably focus on an area of programming you
enjoy and become an expert in it. Focusing on one programming path will
make getting a job easier.
Web and mobile development are two of the most popular programming
paths. There are two specialties within them: front end and the back end. The
front end of an application is the part you can see—like the GUI of a web
app. The back end is what you can't see—the part that provides the front end
with data. The titles for open programming jobs will read something like
"Python Backend Programmer," which means they are looking for someone
who programs the backend of a website and is familiar with Python. The job
description will list the technologies the ideal candidate will be familiar with,
along with any additional skills needed.
Some companies have a team devoted to the front end and another to the
back end. Other companies only hire full stack developers—programmers
that can work on both the front and back ends; however, this only applies to
companies building websites or apps.
There are many other programming areas you can work in, such as security,
platform engineering, and data science. Job descriptions on sites listing
programming jobs are a good place to learn more about the requirements of
different areas of programming. The Python Job Board, found at
https://www.python.org/jobs, is a good place to start. Read the requirements
for a few jobs, as well as the technologies they use, to get an idea what you
need to learn to be competitive for the type of job you want.
Getting an Interview
Once you've gained programming experience through either open source or
freelance work, it's time to start interviewing. I've found the most efficient
way to get an interview is to focus on LinkedIn. If you don't have a LinkedIn
account, create one to start networking with potential employers. Write a
summary about yourself at the top of your profile, and make sure to highlight
your programming skills. For example, a lot of people say something like
"Programming Languages: Python, JavaScript" at the top of their profile,
which helps lead recruiters searching for those keywords to them. Make sure
to put your open source or freelancing experience as your most recent job.
Once your profile is complete, start connecting with technical recruiters—
there are lots of technical recruiters on LinkedIn. They are always looking for
new talent and will be eager to connect with you. Once they accept your
invitation, reach out and ask if they are hiring for any open positions.
The Interview
If a recruiter thinks you are a good fit for the role they are hiring for, they will
send you a message on LinkedIn asking to set up a phone screen. The phone
screen will be with the recruiter, so it is usually non-technical, although I've
had recruiters ask me technical questions they've memorized the answer to
during first interviews. The conversation is about the technologies you know,
your previous experience, and figuring out if you would fit in with the
company's culture.
If you do well, you will advance to the second round—a technical phone
screen—where you speak with members of the engineering team. They will
ask you the same questions from the first interview. However, this time the
questions are accompanied by a technical test over the phone. The engineers
will give you the address of a website where they have posted programming
questions, and ask you to solve them.
If you make it past the second round, you will usually have a third interview.
The third interview is typically in person at the company's office. Like the
first two, you meet with different engineers on the team. They ask about your
skills and experience and administer more technical tests. Sometimes you
stay for lunch to see how you interact with the team. The third round is where
the famous whiteboard coding tests happen. If the company you are
interviewing for does whiteboarding, you will be asked to solve several
programming problems. I recommend buying a whiteboard and practicing
beforehand because solving a programming problem on a whiteboard is much
harder than solving it on a computer.
You can narrow down the questions to focus on even further by thinking
about the interview from the interviewer's perspective. Think about the
situation your interviewer is in; they say software is never complete, and it's
true. Your interviewer most likely has a lot of work and doesn't want to
dedicate a lot of time interviewing candidates. Are they going to spend their
valuable time coming up with original programming questions? Probably not.
They are going to Google "programming interview questions," and ask one of
the first ones they find. This situation leads to the same interview questions
coming up over and over again—and there are some great resources out there
to practice them! I highly recommend using LeetCode—I've found every
question anyone has ever asked me in a programming interview there.
Chapter 25.
Working on a Team
"You can't have great software without a great team, and most software
teams behave like dysfunctional families."
~ Jim McCarthy
Changing Code
By reading this book, you've demonstrated you are the type of person who is
constantly looking to improve. Unfortunately, not everyone on your team will
share your enthusiasm for becoming a better programmer. Many
programmers don't have the desire to keep learning—they are fine doing
things suboptimally.
Imposter Syndrome
Everyone who programs feels overwhelmed sometimes, and no matter how
hard you work there are going to be things you don't know. As a self-taught
programmer, it is especially easy to feel inadequate because someone asked
you to do something you've never heard of, or you feel like there are many
concepts in computer science you still do not understand. These things
happen to everyone—not just you.
The article "ABC: Always Be Coding" by David Byttow gives great advice
on how to get a job as a software engineer. The title says it all—always be
coding. You can find the article at https://medium.com/always-be-
coding/abc-always-be-coding-d5f8051afce2#.2hjho0px7. If you combine
ABC with a new acronym I made up—ABL—always be learning—you are
sure to have an exceptional career. In this chapter, I am going to review some
of the programming resources I've found helpful.
The Classics
There are a few programming books that are considered must-reads. The
Pragmatic Programmer by Andy Hunt and Dave Thomas; Design Patterns
by Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm (design
patterns are an important subject I didn't get a chance to cover); Code
Complete by Steve McConnell; Compilers: Principles, Techniques, and
Tools, by Alfred Aho, Jeffrey Ullman, Monica S. Lam, and Ravi Sethi; and
Introduction to Algorithms by the MIT Press. I also highly recommend
Problem Solving with Data Structures and Algorithms, a free, interactive,
excellent introduction to algorithms by Bradley N. Miller and David L.
Ranum and much easier to understand than MIT's Introduction to Algorithms.
Online Classes
Online coding classes are another way to improve your programming skills.
You can find all of my class recommendations at
http://theselftaughtprogrammer.io/courses.
Hacker News
Hacker News is a platform for user-submitted news hosted on the technology
incubator Y Combinator's website, found at https://news.ycombinator.com. It
will help you keep up to date with the newest trends and technologies.
Chapter 27.
Next Steps
"Love the little trade which thou hast learned, and be content therewith."
~ Marcus Aurelius
First of all—thank you for purchasing this book. I hope it's helped you
become a better programmer. Now that you're finished, it's time for you to get
down to business. Where do you go from here? Data structures and
algorithms. Get on LeetCode and practice those algorithms. Then practice
them some more! In this chapter, I give some final thoughts on how you can
continue to improve as a programmer (once you finished practicing writing
algorithms).
Find a Mentor
A mentor will help take your programming skills to the next level. One of the
hard things about learning to program is that there are so many things you
can do suboptimally without knowing it. I mentioned earlier you can help
combat this by doing code reviews. A mentor can do code reviews with you
to help improve your coding process, recommend books, and teach you
programming concepts you don't understand.
Strive to Go Deep
There is a concept in programming called a "black box," which refers to
something you use but do not understand how it works. When you first start
programming, everything is a black box. One of the best ways to get better at
programming is to open up every black box you find and try to understand
how it works. One of my friends told me it was a major "aha" moment when
he realized the command-line itself is a program. Opening up a black box is
what I call going deep.
Writing this book helped me go deep. There were certain concepts I thought I
understood, only to find out I couldn't explain them. I had to go deep. Don't
stop at just one answer, read all the explanations on a topic you can find. Ask
questions and read differing opinions online.
Other Advice
I once came across a forum topic discussing different ways to become a
better programmer. The top voted answer was surprising: Do things other
than programming. I've found this to be true—reading books like The Talent
Code by Daniel Coyle has made me a better programmer because he lays out
exactly what you need to do to master any skill. Keep your eye out for things
outside of programming you can bring to your programming game.
The last piece of advice I will leave you with is to spend as much time as you
can reading other people's code. It is one of the best ways to improve as a
programmer. When you are learning, make sure to strike a balance between
writing and reading code. Reading other people's code is going to be difficult
at first, but it is important because you can learn so much from other
programmers.
I hope you enjoyed reading this book as much as I enjoyed writing it. Please
feel free to email me at [email protected] for any reason. I
also have a programming newsletter you can sign up for at
http://theselftaughprogrammer.io and a Facebook group located
at https://www.facebook.com/groups/selftaughtprogrammers where you can
get in touch with me and a community of other people learning to program. If
you like this book, please consider leaving a review on Amazon at
https://www.amazon.com/dp/B01M01YDQA#customerReviews, it helps get
this book in the hands of more people, and I appreciate every review I
receive. Best of luck on the rest of your journey.
Acknowledgements
I want to thank everyone that helped make this book possible. My parents,
Abby and James Althoff, were so supportive during the entire process. My
Dad went through every page of the book and gave me amazing feedback. I
couldn't have made this happen without him. My girlfriend, Lauren Wordell,
put up with me working on this book at all times. I want to thank my
incredibly talented illustrator Blake Bowers; my editors Steve Bush,
Madeline Luce, Pam Walatka and Lawrence Sanfilippo; and my friend
Antoine Sindu—several of our discussions made it into the book. I also want
to thank Randee Fenner, who supported the project on Kickstarter and
introduced me to Pam. Shoutout to my former boss Anzar Afaq, who was
incredibly supportive when I joined his team at eBay. A big thank you to all
of the beta readers who read the book early and gave me feedback. Finally, I
want to thank everyone on Kickstarter that backed this project, especially Jin
Chun, Sunny Lee, and Leigh Forrest. Thank you all so much!
Citations
1.http://www.infoworld.com/article/2908474/application-development/stack-
overflow-survey-finds-nearly-half-have-no-degree-in-computer-science.html
2.http://www.wsj.com/articles/computer-programming-is-a-trade-lets-act-
like-it-1407109947?mod=e2fb
3.https://en.wikipedia.org/wiki/Syntax
4.https://en.wikipedia.org/wiki/Syntax
5.https://www.tutorialspoint.com/python/python_files_io.htm
6.https://maryrosecook.com/blog/post/a-practical-introduction-to-functional-
programming
7.http://whatis.techtarget.com/definition/abstraction
8.http://stackoverflow.com/questions/1031273/what-is-polymorphism-what-
is-it-for-and-how-is-it-used
9.http://stackoverflow.com/questions/1031273/what-is-polymorphism-what-
is-it-for-and-how-is-it-used
10.http://whatis.techtarget.com/definition/abstraction
11.https://en.wikipedia.org/wiki/Regular_expression
12.http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_04_01.html
13.https://en.wikipedia.org/wiki/Regular_expression
14.https://interactivepython.org/runestone/static/pythonds/Recursion/TheThreeLawsofRec