What is Programming in Python (Best Tutorial 2019)

What is Programming in Python

What is Programming in Python

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.

 

What is Python

Python is an open-source programming language created by Dutch programmer Guido van Rossum and named after the British sketch comedy group, Monty Python’s Flying Circus. 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 in everything from building web servers to creating desktop applications. Because of its popularity, there is a large demand for Python programmers.

 

Installing Python

In order to follow the examples in this blog, you need to have Python 3 (version 3 of Python) installed. You can download Python for Windows and OS X at Download Python. 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 blog will not work if you are using Python 2.

 

Python is available for both 32-bit and 64-bit computers. If you have a new computer, purchased after 2007, it is most likely a 64-bit computer. If you aren’t sure if your computer is 32-bit or 64-bit, an internet search should help you figure it out. If you are on Windows or a Mac, download the 64- or 32-bit version of Python, open the file and follow the instructions.

 

The Interactive Shell

Python comes with a program called IDLE (short for the interactive development environment ); it is also the last name of Eric Idle, one of the members of Monty Python’s Flying Circus. IDLE is where you will be typing your Python code. Once you’ve downloaded Python, search for IDLE in Explorer (PC), Finder (Mac) or Nautilus (Ubuntu). I recommend creating a desktop shortcut to make it easy to find.

 

Click on the IDLE icon and a program with the following lines will open up (although this could change so don’t worry if the message is absent or different) :

Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)

[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on Darwin

Type "copyright", "credits" or "license()" for more information.

>>> 

This program is called the interactive shell. You can type Python code directly into the interactive shell and the shell prints the results. At the prompt (>>>) type:

print ( "Hello, World!" )

and press enter.

 

IDLE might reject code that is copied from Kindle, other eblogs or word processors like Microsoft Word. If you copy and paste the code and get an unexplainable error message, try typing the code directly into the window. You must type the code exactly as it is written in the example, including quotation marks, parentheses, and any other punctuation.

 

The interactive shell will respond by printing Hello, World!

In the programming world, when you teach someone a new programming language, it is the tradition that the first program you teach them is how to print Hello, World! So, congratulations! You just wrote your first program.

 

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.” This will open up a text editor, which usually has a blank white background. You can write your code in this text editor, then save it to run later.

 

When you run your code, the output of the code you wrote will appear in the interactive shell. You need to save your 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 files have to end with .py. Once you’ve saved your file, click “Run” (again, 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 a line of code. However, in this case, 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?

 

Comments

A comment is a line (or part of a line) of code written in English (or another language) preceded by a special symbol that tells 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.

 

A comment explains what a line of code does. Programmers use comments to clarify why they did something to make the line of code easier to understand for whoever reads it. You can write whatever you want in a comment, as long as it is only one line long. Here is an example of a comment taking up an entire line of code, followed by an example of a comment taking up part of a line of code:

# This is a comment

print ( "The comment does not affect this code" )

>> The comment does not affect this code

print ( "The comment does not affect this code" ) # This is a comment >> The comment does not affect this code

 

You should only write a comment if you are doing something unusual in your code, or to explain 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:

print ( "Hello, World!" ) # this line of code prints Hello, World!

It is unnecessary because it is very clear what this line of code does. Here is an example of a good comment:

d = math.sqrt(l**2 + w**2) # length of the diagonal

 

Even if you understood exactly how this code works (and you will be the end of Part I), you still might not know how to calculate the length of a diagonal of a rectangle, which is why this comment is useful.

 

Printing

We are not limited to printing “Hello, World!” in our programs. We can print whatever we’d like as long as we surround it with quotes:

print ( "Python" )

>> Python

print ( "Hola!" )

>> Hola!

Lines

Python programs are divided into lines of code. Take a look at this program:

# line1

# line2

# 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 specific line in your program. Sometimes a piece of code is long and takes up more than one line. When this happens, it is ok for the code to extend to the next line (when extended according to Python's rules) :

print ( """This is a really really really really really really really really long line of code.""" )

I will explain the rules for extending lines of Python code in Part V.

 

Keywords

The Python language has a list of words with special meaning. These are called keywords

. for is a keyword we’ve already seen that is used to execute code multiple times. We will learn more keywords throughout this blog.

 

Spacing

Let’s take another look at our program that prints Hello, World! a hundred times:

# calthoff/tstp

for i in range ( 100 ):

print ( "Hello, World!" )

As I noted earlier, the print is indented by four spaces. We will cover why shortly, but it has to do with letting 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.

 

Spacing is not used like this in other programming languages. Other approaches include using keywords or brackets instead of spacing. Python proponents believe the required use of proper spacing makes Python less tedious to read and write than other languages, but the best approach to this problem is frequently debated amongst programmers.

 

Data Types

Different kinds of data in Python are grouped into different categories or data types. In Python, each data value, like 2 or "Hello, World!" , is called an object. We will learn more about objects in Part II, but for now think of an object as a data value in Python with three properties: an identity, a data type and a value.

 

The identity of an object is where it is stored in memory, which never changes (and which we will be ignored for now). The data type of an object is the category of data the object belongs to and determines the properties the object has. This also 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 a data type called str, short for string, and the value "Hello, World!" . When we refer to an object with an str data type, we call it a string. A string is a sequence of one or more characters surrounded by quotes. You can use single quotes or double quotes, but the quotes at the beginning and end of a given string must match:

“Hello, World!”

>> Hello, World!

‘Hello, World!’

>> Hello, World!

A character can be any symbol found in a Unicode character table like the interactive one found at Unicode® character table. Strings are used to represent text, and they have unique properties.

 

The numbers we used to do math in the previous section are also objects—but they are not strings, they have a different data type. Whole numbers have the data type int, short for integer. Numbers like 2 , 3 , 4 and 10 all have the data type int. Another way of saying this is they are all integers. Like strings, integers have their own properties. For example, you can divide two integers, but you cannot divide two strings.

 

Although whole numbers are integers, fractional numbers (numbers with a decimal point) have a different data type called float. 2.1 , 8.2 and 9.9999 are all examples of objects with the float data type. They are called floats. Like all data types, floats have their own properties and behave in a certain way. Floats behave similarly to integers:

2.2 + 2.2

>> 4.4

But , there are some important differences between floats and integers you will learn about later. Objects with a bool data type have a value of either True or False and are called booleans. Objects with a data type NoneType always have the value None. Objects with a NoneType data type is used to represent the absence of a value.

I will explain how the different data types are used in programming throughout this blog.

 

Constants and Variables

You can use Python to do math just like you would use a calculator. You can add, subtract, divide, multiply, raise a number to a power and much more. 

 

A constant is a value that never changes. Each of the numbers in the previous example is a constant: the number two will always represent the value 2. A variable, on the other hand, refers to a value; but that value can change. A variable consists of a name made up of one or more characters. That name gets assigned to a value using the assignment operator (the = sign). Unlike a constant, the value of a variable value can change.

Some programming languages require the programmer to include variable "declarations" that tell the programming language what data type the variable will be. Python makes it simpler: you create a variable simply by assigning a value to it using the assignment operator.

 

Often when programming, you want to increment (increase) the value of a variable, or decrement (decrease) the value of a variable. Because this is such a common operation, Python has a special syntax—a shortcut—for incrementing and decrementing variables. To increment a variable, you assign the variable to itself, and on the other side of the equals sign you add the variable to the number you want to increment by:

x = 10

x = x + 1

x

>> 11

To decrement a variable, you do the same thing, but instead subtract the number you want to decrement by:

x = 10

x = 10 - 1

x

>> 9

 

Variables are not limited to storing integer values—they can refer to any data type:

my_string = “Hello, World!”

>> 

my_float = 2.2

>> 

my_boolean = True

>> 

You can name variables whatever you’d like, as long as you follow four rules:

  • 0. 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!”
  • 0. Variable names can only contain letters, numbers and the underscore symbol.
  • 0. You cannot start a variable name with a number. Although you can start a variable with an underscore, it has a special meaning that we will cover later , so avoid using it until then.
  • 0. You cannot use Python keywords for variable names. You can find a list of keywords here: Python keywords - presenting Python keywords

 

Syntax

Syntax is the set of rules, principles, and processes that govern the structure of sentences in a given language, specifically word order.The English language has a syntax, and so does Python. For example, in English you must end a sentence with a period. Python also has a set of rules that must be followed, so it also has syntax.

 

In Python, strings are always surrounded by quotes. This is an example of Python’s syntax. The following is a valid Python program:

print ( "Hello, World!" )

 

It is a valid program because we followed Python’s syntax by using quotes around our text when we defined a string. If we only used quotes on one side of our text we would violate Python’s syntax, and our code would not work. Python does not like when you violate its syntax, and in the next section you find out what happens when you do.

 

Errors and Exceptions

If you write a Python program and disregard Python’s syntax you will get one or more errors when you run your program. When this happens, the Python shell will inform you your code did not work and gives you information about the error that occurred. Look at what happens if you try to define a string in Python with a quote on only one side:

my_string = “Hello World.

>> File "/Users/coryalthoff/PycharmProjects/se.py", line 1 my_string = 'd

^

 

SyntaxError: EOL while scanning string literal

This is called a syntax error. Syntax errors are fatal. A program cannot run with a syntax error. When you run a program with a syntax error, Python lets you know about it in the shell. The message will tell 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, errors like this 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 line 1 of your code. After staring at it for a while, you would eventually notice there is only one quote. To fix it, 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:

>> SyntaxError: EOL while scanning string literal

 

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 example of an exception that occurs if you try dividing by zero.

 

The difference between a syntax error and an exception is 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 blog). When an exception occurs, Python programmers say “ Python (or your program) raised an exception”. Here is an example of an exception:

10 / 0

>> ZeroDivisionError: integer division or modulo by zero If you incorrectly indent your code, you get an IndentationError :

y = 2

x = 1

 

>> IndentationError: unexpected indent

As you are learning to program, you will frequently get syntax errors and exceptions (including ones we 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 stare at it until you figure out the solution (or search the internet for the error or exception if you are stumped).

 

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 can make decisions by analyzing the values of variables. A conditional statement is code that is able to execute additional code circumstantially. Here is an example in pseudocode (fake code used to illustrate an example) to help clarify how this works:

If (expression) Then

(code_area1)

Else

(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 of the code defined in code_area1 gets executed. If the expression defined in the first conditional statement is False , all of the code defined in code_area gets executed.

 

The first part of the example is called an if statement , and the latter 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:

# calthoff/tstp

country = "America"

if country == "America" :

print ( "Hello, America!" )

else :

print ( "Hello, Canada!" )

>> Hello, America!

Lines 2 and 3 form an if statement. An if statement is made up of a line of code starting with the if keyword followed by an expression, a colon, an indentation and one or more lines of code to be executed if the expression in the first line evaluates to True. Lines 3 and 4 form an else statement. An else statement starts with the else keyword, followed by a colon, an indentation and one or more lines of code to execute if the expression in the if statement evaluates to False.

 

Together they form an if else statement. This example prints Hello, America! because of the expression in the if statement evaluates to True. If we change the variable country to Canada, the expression in the if statement will evaluate to False, the else statement’s code will execute and our program will print Hello Canada! instead.

# calthoff/tstp

country = "Canada"

if country == "America" :

print ( "Hello, America!" )

else :

print ( "Hello, Canada!" )

>> Hello Canada!

An if statement can be used on its own:

# calthoff/tstp

country = "America"

if country == "America" :

print ( "Hello, America!" )

>> Hello, America!

You can have multiple if statements in a row:

# calthoff/tstp

x = 2

if x == 2 :

print ( "The number is 2." )

if x % 2 == 0 :

print ( "The number is even." )

if x % 2 != 0:

print ( "The number is not odd." )

>> The number is 2.

>> The number is even.

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 is executed, but the third expression evaluates to False, so its code is not executed.

 

If you really want to get crazy, you can even put an if statement inside of another if statement. This is called nesting:

# calthoff/tstp x = 10

y = 11

if x == 10 :

if y == 11 :

print (x + y)

>> 21

In this case, x + y will only print if the expressions in both if statements evaluate to True. An else statement cannot be used on its own; it can only be used at the end of an if else statement. We use the elif keyword to create elif statements. if stands for else if, and elif statements can be indefinitely added to an if else statement to allow it to make additional decisions.

 

If an if else statement has elif statements in it, the if statement expression gets evaluated first. If the expression in that statement evaluates to True , its code is executed and no other code is executed. However, if it evaluates to False , each consecutive elif statement is evaluated. As soon as an expression in an if statement evaluates to True , its code is executed and no more code executes. If none of the if statements evaluate to True , the code in the else statement is executed. Here is an example of an if else statement with elif statements in it:

# calthoff/tstp

country = "Thailand"

if country == "Japan" :

print ( "Hello, Japan!" )

elif country == "Thailand" :

print ( "Hello, Thailand!" )

elif country == "India" :

print ( "Hello, India!" )

elif country == "China" :

print ( "Hello, China!" )

else :

print ( "Hello, world!" )

>> Hello, Thailand!

Here is an example where none of the expressions in the elif statements evaluate to True , and the code in the else statement is executed:

# calthoff/tstp

country = "Mars"

if country == "America" :

print ( "Hello, America!" )

elif country == "Canada" :

print ( "Hello, Canada!" )

elif country == "Thailand" :

print ( "Hello, Thailand!" )

elif country == "Mexico" :

print ( "Hello, Mexico!" )

else :

print ( "Hello, world!" )

>> Hello, World!

Finally, you can have multiple if statements and elif statements in a row:

# calthoff/tstp

x = 100

if x == 10 :

print ( "10!" )

elif x == 20 :

print ( "20!" )

else :

print ( "I don’t know what x is!" )

if x == 100 :

print ( "x is 100!" )

if x % 2 == 0:

print ( "x is even!" )

else :

print ( "x is odd!" )

>> I don’t know what x is!

>> x is 100!

>> x is even!

Statements

A statement is a technical term that describes various parts of the Python language. You can think of a Python statement as a command or a calculation. This will become more clear as we take a look at examples of different kinds of Python statements. In this section, we will also take a detailed look at the syntax of statements.

 

Don't worry if some of this seems confusing at first. Spend as much time as necessary rereading this section and go back to the earlier examples and compare them with what you are learning here. It might take a while to understand the syntax of statements, but it will start to make more sense the more time you spend practicing Python and will help you understand several programming concepts.

 

Python has two kinds of statements: simple statements and compound statements. Simple statements can be expressed in one line of code, whereas compound statements generally span multiple lines (but can be written in one line in some circumstances). Here are some examples of simple statements:

print ( "Hello, World!" )

>> ‘Hello, World!”

2 + 2

>> 4

The compound statement s generally span more than one line of code. You’ve already seen multiple examples of compound statements: if statements, if-else statements and the first program we wrote in this blog that printed “Hello, World!” one hundred times are all examples of compound statements.

 

Compound statements are made up of one or more clause . A clause consists of two or more lines of code: a header followed by a suite (s). A header is a line of code in a clause that contains a keyword followed by a colon and a sequence of one or more lines of indented code. After the indent there are one or more suites. A suite is just a line of code in a clause. The suites are controlled by the header. Our program that prints “Hello, World!” a hundred times is made up of a single compound statement:

# calthoff/tstp (for i in range ( 100 ):

print ( "Hello, World!" )

>> Hello World

>> Hello World

>> Hello World

…

The first line of the program is the header. It’s made up of a keyword— for —followed by a colon and an indented line of code. After the indentation is a suite — print(“Hello, World!”) . In this case, the header uses the suite to print Hello, World! a hundred times. This is called a loop. This code only has one clause.

 

A compound statement can also be made up of multiple clauses. You already saw this with if else statements. Anytime an if statement is followed by an else statement, the result is a compound statement with multiple clauses. When a compound statement has multiple clauses, the header clauses work together.

 

In the case of an if-else compound statement, when the if statement evaluates to True , the if statement’s suites execute and the else statement’s suites do not execute. When the if statement evaluates to False , the if statement’s suites do not execute and the else statement’s suites execute instead. The last example from the previous section has three compound statements:

# calthoff/tstp x = 100

if x == 10 :

print ( "10!" )

elif x == 20 :

print ( "20!" )

else :

print ( "I don’t know what x is!" )

if x == 100 :

print ( "x is 100!" )

if x % 2 == 0:

print ( "x is even!" )

else :

print ( "x is odd!" )

>> I don’t know what x is!

>> x is 100!

>> x is even!

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, statements can have spaces between them. Space between statements does not affect the code. Sometimes spaces are used between statements to make the code more readable:

print ( "Michael" )

print ( "Jordan" )

>> Michael

>> Jordan

 

 Functions

A function is a compound statement that can take input, execute instructions, and optionally return an output. Calling a function means giving the function the input it needs too it can execute its instructions and optionally return an output. Functions in Python are similar to functions in math. If you don’t remember functions from algebra, here is an example:

 

# the following is algebra, not Python code f(x) = x * 2

The left half of the equation defines a function f —that takes one parameter— x . A parameter is data passed you pass into a function when its called. A function can have one parameter, multiple parameters or no parameters. A function’s parameters are its input.

 

The right half of the equation is the definition of the function (the instructions it executes when called). The right-hand side of the equation user is able to use the parameter that was passed in ( x ) to make a calculation and return the result (the output). In this case, our function takes a parameter ( x); , multiplies it by 2; and returns the result.

 

In both Python and algebra, you call a function with the following syntax: [function_name]([parameters_seperated_by_commas] ) . You call a function by putting parentheses after the function name. TYou put the parameters go inside the parenthesis with each parameter separated by a comma. If we call the function we just defined above (?) and pass in the parameter 4, we get the following result:

# the following is algebra, not Python code f(4)

>> 8

If we pass in 10 as a parameter we get 20:

f(10)

>> 20

In our first example, we called our function with 4 as a parameter ( x ). Our function executed its code, x * 2, and returned the result — 8. In our second example, we called our function with 10 as a parameter ( x ). Our function executed its code, x * 2, and returned the result — 20.

 

Representing Concepts

This is abrupt, maybe something like “As you may have figured out by now…”We are not limited to printing “Hello, World!” in our programs. We can print whatever we’d like:

print(“Python!”)

>> Python!

 

From here on out, I will use the following convention to explain concepts like the idea that you can print anything in Python: print(“[what_you_want_to_print]”) . The brackets and the text inside of them represent that you need to be replaced by a piece of code substitute a piece of code in place of them.

 

When you are trying to follow an example written in this format like this, do not type the brackets. The words inside of the brackets are a hint for the code you need to replace the brackets with. Everything outside of the not in brackets represents actual code that you should type. This format is a way of expressing that you can type

print(“[what_you_want_to_print]”) into Python, replace [what_you_want_to_print] with

whatever you want to print, and Python will print it:

print(“I do not like green eggs and ham.”)

print(“The Cat in the Hat”)

>> I do not like green eggs and ham

>> The Cat in the Hat

Programming is full of conventions: agreed upon ways of doing things. This format is an example of a convention that is used in the programming world and will be used throughout the blog.

 

Defining Functions

To create a function in Python we choose a function name, define its parameters, define what the function will do, and we can choose to optionally return a value (if we don’t return a value the function will return None ). We use the following syntax to define a function:

def [function_name]([parameters_seperated_by_commas]):

[function_definition]

Our mathematical function f(x) = x * 2 looks like this in Python:

# calthoff/tstp

def f(x):

return x * 2

>> 

The keyword def tells Python you are about to define a function. is a keyword used to define a function. When you use it, Python knows you are about to define one. After def , you can name your function anything whatever you’d like. By convention, you should never use capital letters in your function name, and if there are two words in your function name you should separate them with an underscore—like_this. Once you’ve named your function, put parentheses after it.

 

Inside the parenthesis, you put your parameter(s). In this (the previous?) example, our function only has one parameter ( x ), but if you want your function to accept more than one parameter, you must separate each parameter inside the parenthesis with a comma. After the parenthesis, you put a colon and indent by four spaces (like any other compound statement).

 

Any code indented four spaces after the colon is the function’s definition. In this case, our function’s definition is only one line— return x * 2 . return is another keyword. It is used to define the value a function outputs when you call it, referred to as the value the function returns.

To call a function in Python, we use the syntax we learned earlier: [function_name]().

Here is an example of calling our function with 2 as a parameter:

f(2)

>> 

You will notice the console didn’t print anything. Our function worked, but it just didn’t print the result because we didn’t tell Python too. If we want to print the value our function returned, we can save our function’s output in a variable:

# calthoff/tstp result = f(2)

print(result)

>> 4

 

You can save the result your function returns in a variable whenever you need to use the value later in your program. Functions are not only just used to return values. Returning a value is optional, as is including a return statement in your function. Aside from returning values, functions also encapsulate functionality you want to reuse. For example:

#add GitHub

def even_odd(x):

if x % 2 == 0:

print(“even”)

else:

print(“odd”)

even_odd(2)

even_odd(3)

>> even

>> odd

We didn’t define a value for our function to return, but our function is still useful. ItOur function tests if x % 2 == 0 and prints whether x is even or odd depending on the result. Remember, modulo returns the remainder when you divide two numbers. If there is no remainder when you divide a number by 2 (modulo returns 0 ) the number is by definition even.

 

If there is a remainder, the number is odd. You may need to use this functionality in several different places in your program. It would be poor programming to type the code we used in our function’s definition every time you want to use this functionality. That’s what functions are for. You put functionality in a function, and it lets you easily reuse that functionality throughout your program, without having to do any extra work. This is a little confusing - are you going to explain later on? You could mention this is something you’ll cover how to do in blog __.

 

Parameters

So far, we’ve only defined functions that accept one parameter. A function doesn’t have to take any parameters. Here is an example of a function that does not take any parameters:

# calthoff/tstp

def f():

return 1 + 1

result = f()

print(result)

>> 2

Here is an example of a function that accepts multiple parameters:

# calthoff/tstp (

def f(x, y, z):

return x + y + z

result = f(1, 2, 3)

print(result)

>> 6

There are two types of parameters a function can accept. The parameters we’ve seen so far are called required parameters. When a function is called, all of the required parameters must be passed into the function, or you will get an error in your program. There is another kind of parameter—optional parameters—that let the caller of the function pass in a parameter if they want to, but they do not have to.

 

If they do not pass in a parameter, a default value defined by the function will be used instead. You define optional parameters are defined with the following syntax: [function_name]([parameter_name]=[paramater_value]) . Like required parameters, optional parameters they must be separated by commas. Here is an example of a function that takes an optional parameter:

# calthoff/tstp

def f(x=10):

if x == 10:

print(“x is ten”)

else:

print(“x is not ten”)

default = f()

pass_in = f(2)

print(default)

print(pass_in)

>> ‘x is ten’ I’m confused why there are single quotes or any quotes at all.

>> ‘x is not ten’I’m confused why there are single quotes or any quotes at all.

First, we call our function without passing in a parameter. Because the parameter is optional we don’t have to pass it in this is allowed, and x is assigned the value we defined in our optional parameter— 10. When our function is called, x is equal to 10, and so ‘x is ten’(if there should be single quotes above, leave it, if not take them out) prints.

 

Next—we call our function again—but this time we pass in 2 as a parameter. The default value 10 is ignored because we provided a value this time, and so x gets 2 and “x is not ten” (same thing about the quotes, even if I’m just missing something I think they should be single quotes) prints. You can define a function with both required and optional parameters, but there is one rule: all of your required parameters must be defined before your optional parameters:

def required_optional(x, y=10)

return x + y

>> 

Passing Parameters

When you define a function with parameters, sometimes those parameters have to be a specific data type in order for the function to work. How do you communicate this to whoever calls your function? When you write a function, it is good practice to leave a comment at the top of the function explaining what data type each parameter needs to be.

 

We will discuss this further in Ppart V. When you give a function parameters when you call it, it is referred to as “passing” the function parameters. This sentence makes sense, but is fairly confusing. Could it be: When you give a function parameters THEN you call it, it is referred to as “passing” the function parameters.

 

pass

We can use the keyword pass to create a function that does nothing:

””” calthoff/tstp

”””

def f():

pass

f()

>> 

pass The pass keyword is useful whenever you want to create a function, but finish the definition later.

 

Nested Functions

You can define a function inside of a function. This is called nesting. The first function is called the outer function, and the second function is called the inner (or nested) function, or nested function. Here is an example:

def f ():

print ( "Inner Function!" )

def x ():

print ( "Nested Function!" )

x()

f()

>> Inner Function!

>> Nested Function!

We will not be covering why this is important in this blog because you do not need it is not important to use nested functions when you are learning to program., but I wanted to include this example so you know that it is possible.

 

Scope

Variables have an important property called scope we didn’t discuss when we first covered them. When you define a variable, the variable’s scope refers to what part of your program has access to it. This is determined by where the variable is defined in your program. If you define a variable outside of a function the variable has a global scope: the variable can be accessed anywhere in your program.

 

If you define a variable inside of a function (or class) it has local scope: the variable cannot be accessed anywhere in your program—; it can only be accessed in the function (or class) it was defined in (or any nested functions or classes). Here are some examples of variables with global scope:

x = 1

y = 2

z = 3

>> 

These variables were not defined inside of a function (or class) and therefore have a global scope. This means we can access them anywhere—including inside of a function:

x = 1

y = 2

z = 3

def f():

print(x)

print(y)

print(z)

f()

>> 1

>> 2

>> 3

 

If we define these same variables inside of a function, we can only access them inside of that the function we defined them in (or a function nested inside the function we defined them in). If we try to access them outside of the function they were defined in, Python raises an exception:

def f ():

x = 1

y = 2

z = 3

print (x)

print (y)

print (z)

>> NameError: name 'x' is not defined

If we stick to using these variables inside our function, there is no problem:

def f ():

x = 1

y = 2

z = 3

print (x)

print (y)

print (z)

f()

>> 1

>> 2

>> 3

If you want to change the value of a global variable inside a local scope, you need to use the global keyword followed by the variable you want to change:

# calthoff/tstp x = 100

def f():

global x

x += 1

print(x)

f()

>> 101

The reason programming languages have scope is because having no scope (every variable can be accessed anywhere in a program) causes problems. If you have a large program, and you write a function that uses the variable x , you might accidentally change the value of a variable called x that was previously defined in your program; which will change the behavior of your program and may cause an error or unexpected results.

 

The larger your program gets, and the more variables it has, the more likely this becomes. However, with scope, if you define a variable x inside of a function, there is a guarantee you will not accidentally change the value of any previously defined variables outside of your function because in order to change the value of a variable outside of your function, you must explicitly use the global keyword.

 

Built-in Functions

Python comes with a library of built-in functions. They perform all sorts of different functionality and are ready to use without any work on your part. We’ve already seen one example of a built-in function—the first program we wrote used the print function to print “Hello, World!” . lens is another built-in function. It returns the length of an object—like a string. The length of a string is the number of characters in it.

len(“Monty”)

>> 5

len(“Python”)

>> 6

type is another built-in function. It returns what data type an object is:

type(“Hello World”)

>> <type 'str'>

type(100)

>> <type 'int'>

type(1.0)

>> <type 'float'>

The built-in str function takes an object and returns a new object with a string data type. For example, we can use str to convert an integer to a string.

str(100)

>> '100'

int takes an object and returns a new object with an integer data type:

int(“1”)

>> 1

And float takes an object and returns a new object with an integer data type:

float(100)

>> 100.0

input is a built-in function that collects information from the person using our program.

“““

”””

age = input("How old are you?")

age = int(age)

if age < 21:

print("You are young!")

else:

print("Wow you are old!")

>> How old are you?

 

The input function takes a string as a parameter and displays the string to the person using the program in the shell. They can then type a response into the shell, and we can save their response in a variable—in this case, we save the response in the variable age.

 

Next, we use the int function to change the age from a string to an integer because input collects data from the user as a string, and we want our variable to be an integer so we can compare it to other integers. Once we have an integer, our if else statement determines which message gets printed to the user, depending on what they typed into the shell. If the user types a number smaller than 21, “You are young!” prints. If the user types a number greater than 21, “Wow you are old!” prints.

 

Exception Handling

When you rely on user input from the input function, you do not control the input to your program—the user does, and that input could cause an error. For example, say we write a program to collect two numbers from a user, and print out the result of the first number divided by the second number:

a = input(“type a number”)

b = input(“type another number”)

a = int(a)

b = int(b)

print(a / b)

>> type a number

>> 10

>> type another number

>> 5

>> 2

Our program appears to work. However, we will run into a problem if the user inputs 0 as the second number:

a = input(“type a number”)

b = input(“type another number”)

a = int(a)

b = int(b)

print(a / b)

>> type a number

>> 10

>> type another number

>> 0

>> ZeroDivisionError: integer division or modulo by zero

Our program works—until the user decides to enter 0 as the second number, in which case our program raises an exception. We cannot allow people to use this program and hope they will not enter 0 as the second number. One way to solve this is to use exception handling, which allows you to “catch” exceptions if they occur and decide what to do.

 

The keywords try and except are used for exception handling. We can change our program to use exception handling so if a user enters 0 as the second number, our program prints a message telling them not to enter 0 instead of raising an exception.

 

In Python, exceptions are objects—which allows us to use to them in our programs. Each exception in Python is an object. You can see the full list of built-in exceptions here: Built-in Exceptions. Whenever you are in a situation where you think your code may raise an exception, you can use a compound statement with the keywords try and expect to catch the exception.

 

The try clause defines the error that could occur. The except clause defines code that will only execute if the exception defined in your try clause occurs. Here is an example of how we can use exception handling in our program so if a user enters 0 as the second number our program doesn’t break:

a = input(“type a number”)

b = input(“type another number”)

try:

print(a / b)

except ZeroDivisionError:

print(“b cannot be zero. Try again.”)

>> type a number

>> 10

>> type another number

>> 0

>> “b cannot be zero. Try again.”

If the user enters anything other than 0 , the code in our try block is executed and our except block doesn’t do anything. But if the user enters 0 , instead of raising an exception, the code in our except block is executed and our program prints “b cannot be zero. Try again.” .

 

Docstrings

Docstrings are comments at the top of a function or method that explain what the function or method does, and documents what types of the parameters should be passed to it. Here is an example:

def add (x , y):

"""

Returns x + y.

:param x: int first integer to be added.

:param y: int second integer to be added.

:return : int sum of x and y.

"""

return x + y

The first line of the docstring clearly explains what our function does. When other developers reuse your function or method, they do not want to have to read through all of your code to figure out what it does. The rest of the lines of the docstring lists the function’s parameters, its return value, and some additional information, including the type for all of the parameters and the return value.

 

Docstrings will help you program faster because if you forget what a piece of code does, you can quickly figure it out by reading the docstring instead of all of the code in a function, class or method. It will also make it much easier for other programmers to use your code. In some cases I’ve omitted docstrings I normally would have included them to make my code as concise as possible for easy reading—but whenever I am writing code for production (code that is actually used by other people)— I use doc strings.

 

Lists

A list is a mutable container that stores objects in a specific order. When a container is mutable it means the objects in the container can change—objects can be added and removed from the container.

[image]

Lists are represented in Python with brackets. There are two syntaxes to create a list. We can create an empty list with the list function:

new_list = list()

new_list

>> []

Or we can create an empty list with brackets:

new_list = []

new_list

>> []

 

Both syntaxes create a new empty list. When you create a new list with the list function you can also pass in objects you want to add to your list as parameters:

my_list = list (“Apple”, “Orange”, “Pear”)

my_list

>> ['Apple', 'Orange', 'Pear'] Or like this using the second syntax:

my_list = [“Apple”, “Orange”, “Pear”]

my_list

>> ['Apple', 'Orange', 'Pear']

Each object in a list is called an item in the list. In this example, there are three items in our list: ‘Apple’ , ‘Orange’ and ‘Pear’ . Lists keep their items in order—the order the items entered the list. Unless we change the order of our list, ‘Apple’ will always be the first item, ‘Orange’ the second item and ‘Pear’ the third item. ‘ Apple’ is at the beginning of the list, and ‘Pear’ is at the end. We can add a new item to the end of our list using the append function:

my_list.append(“Banana”)

my_list.append(“Peach”)

my_list

>> ['Apple', 'Orange', 'Pear', ‘Banana’,’Peach’]

Lists are not limited to storing strings—they can store any data type:

new_list = []

new_list.append(True)

new_list.append(100)

new_list.append(1.1)

new_list.append(‘Hello’)

>> [True, 100, 1.1, ‘Hello’]

Every item in a list has a position in the list—called its index. You can figure out the index of an item in a list by starting at the beginning of the list and counting. The only tricky part is you have to start counting at zero because the first item in a list has an index of zero. So the first item in a list is at index zero, the second item in a list is index one, and so on.

 

Counting starting at zero takes some getting used to, so don’t worry if it frustrates you at first. You can access each item in a list with its index using the syntax [list_name][[index]] . I put the index in two brackets to represent that [index] should be replaced but should be inside brackets.

my_list = [“Apple”, “Orange”, “Pear”]

my_list[0]

my_list[1]

my_list[2]

>> Apple

>> Orange

>> Pear

You can change an item in a list by setting the index of the item to a new object:

color_list = [“blue”, “green”, “yellow”]

color_list

color_list[2] = “red”

color_list

>> [“blue”, “green”, “yellow”]

>> [“blue”, “green”, “red”]

If you try to access an index that doesn’t exist, Python will raise an exception:

color_list = [“blue”, “green”, “yellow”]

color_list[4]

>> IndexError: list index out of range

You can remove the last item from a list with pop :

color_list = [“blue”, “green”, “yellow”]

color_list

item = color_list.pop()

item

color_list

>> [“blue”, “green”, “yellow”]

>> “yellow”

>> [“blue”, “green”]

You cannot pop from an empty list, if you do Python will raise an exception.

You can check if an item is in a list using the keyword in :

color_list = [“blue”, “green”, “yellow”]

“green” in color_list

>> True

Add the keyword not to check if an item is not in a list:

color_list = [“blue”, “green”, “yellow”]

“black” not in color_list

>> True

You can get the size of a list (the number of items in it) with the len function:

len(color_list)

>> 3

Finally, you can get a range of items in a list with slicing. We slice a list with a start index and an end index separated by a colon in brackets outside of our list. Slicing returns a new list (a “slice” of the old one) made up of everything between the start and end index. The syntax for slicing is [list_name][[start_index:end_index]]. Here is an example of slicing a list:

new_list = ['Apple', 'Orange', 'Pear', ‘Banana’, ‘Peach’] new_list[0:3]

>> ['Apple', 'Orange', 'Pear']

 

A “gotcha” with slicing is the start index includes the item at that index, but the end index doesn’t include the item at the end index, it only includes the item before the end index. This means if you want to slice from “Apple” to “Pear”, you need to slice from index 0, to index 3 (instead of index 2), because the item at the end index is not included in the slice.

 

Tuples

A tuple is an immutable container that stores objects in a specific order. When a container is immutable it means the contents of the container cannot change. That means unlike a list, once you put an object into a tuple, you can no longer change it. Once you create a tuple you cannot change the value of any of the items in it, you cannot add new items to it, and you cannot remove items from it. Tuples are represented with parenthesis. There are two syntaxes to create a tuple:

my _tuple = tuple()

my_tuple

>> ()

And

my_tuple = ()

my_tuple

>> ()

 

If you want your tuple to contain objects, you must add them to your tuple when you create it.

Here is how you add items to a tuple using the first syntax:

my_tuple = tuple(“brown”, “orange”, “yellow”)

my_tuple

>> (“brown”, “orange”, “yellow”) And the second:

my_tuple = (“brown”, “orange”, “yellow”)

my_tuple

>> (“brown”, “orange”, “yellow”)

A tuple with one item in it still needs a comma after the item:

(‘self_taught’,)

>> (‘self_taught’,)

 

Once you’ve created your tuple, if you try to add an object to it, Python will raise an exception:

my_tuple = (“brown”, “orange”, “yellow”)

my_tuple[1] = “red”

>> TypeError: 'tuple' object does not support item assignment

You can, however, access data from a tuple like a list—you can reference an index and slice a tuple:

my_tuple = (“brown”, “orange”, “yellow”)

my_tuple[0]

my_tuple[1:2]

>> yellow

>> ('yellow', 'orange')

 

You can check if an item is in a tuple using the keyword in:

my_tuple = (“brown”, “orange”, “yellow”)

“brown” in my_tuple

>> True

Add the keyword not to check if an item is not in a tuple:

my_tuple = (“brown”, “orange”, “yellow”)

“black” not in my_tuple

>> True

You may be wondering why you would want to use a data structure that appears to be like a list, but less helpful. Tuples are useful when you are dealing with values you know will never change, and you don’t want other parts of your program to have the ability to change those values.

 

A good example is if you are working with geographic coordinates. You may want to store the longitude and latitude of New York in a tuple because you know the longitude and latitude of New York is never going to change, and you want to make sure other parts of your program don’t have the ability to accidentally change them.

 

Dictionaries

Dictionaries are another built-in container for storing objects. They are mutable—but unlike lists and tuples—they do not store objects in a specific order. Instead, dictionaries are used to map one object (called the key) to another object (called the value). Dictionaries are represented with curly brackets. There are two syntaxes for creating dictionaries:

my_dict = dict()

my_dict

>> {}

And:

my_dict = {}

my_dict

>> {}

 

You add objects to a dictionary by mapping a key to a value. Each key mapped to a value in a dictionary is called a key-value pair. Here is how you create key-value pairs when you create a dictionary with the first syntax:

my_dict = dict({“Apple”: “Red”, “Banana”: “Yellow”})

my_dict

>> {'Apple': 'Red', 'Banana': 'Yellow'} And the second:

my_dict = {“Apple”: “Red”, “Banana”: “Yellow”} my_dict

>> {'Apple': 'Red', 'Banana': 'Yellow'}

 

Both syntaxes have a key separated from a value by a colon. Each key-value pair must be separated by a comma. Unlike a tuple, if you have just one key value pair, you do not need a comma after it. Once you’ve added key-value pairs to a dictionary, you can use a key to lookup a value. You can only use a key to lookup a value. You cannot use a value to lookup a key:

my_dict[‘Apple’]

>> Red

Dictionaries are mutable, so once you’ve created one you can add more key-value pairs with the syntax [my_dictionary][[key]]=[value] :

my_dictionary = dict()

my_dictionary[“programming”] = “awesome” my_dictionary[“programming”]

my_dictionary[“Bill Gates”] = “rich”

my_dictionary[“Bill Gates”]

my_dictionary[“america_founded”] = 1776

my_dictionary[“america_founded”]

>> awesome

>> rich

>> 1776

You can use the in a keyword to check if a key is in a dictionary. You cannot use the in a keyword to check if a value is in a dictionary.

“Bill Gates” in my_dictionary

>> True

Add the keyword not to check if a key is not in a dictionary:

“Bill Plates” not in my_dictionary

>> True

Finally, you can delete a key-value pair from a dictionary with the keyword del

my_dictionary

del my_dictionary[ 'Bill Gates' ]

my_dictionary

>> {'america_founded': 1776, 'programming': 'awesome', 'Bill Gates': 'Rich'}

>> {'america_founded': 1776, 'programming': 'awesome'}

 

Triple Strings

If a string is more than one line, you need to put it in triple quotes:

“““line one

line two

line three

”””

If you try to define a string that spans more than one line with single or double quotes, you will get a syntax error.

 

Index es

Strings are iterable. You can access each character in a string with its index, just like you can access each item in a tuple. Like tuples, the first character in a string starts with index 0 and each subsequent index is incremented by 1.

my_string = “LAX”

my_string[0]

my_string[1]

my_string[2]

>> ‘L’

>> ‘A’

>> ‘X’

 

In this example, we used the indexes 0 , 1 , and 2 to access each of the characters in the string “LAX” . If we try to access an element past the last element, Python raises an exception:

my_string = “LAX”

my_string[3]

>> IndexError: string index out of range

 

Strings are Immutable

Strings, like tuples, are immutable. You cannot change characters in a string. If you want to change the characters in a string, you need to create a new string.

Sometimes you will want to create a string using variables. This is done with the format method:

year_started = “1989”

“Python was created in {}.”.format(year_started)

>> ‘Python was created in 1989.’

 

The format function looks for any occurrences of {} in the string and replaces them with the values you pass into the format.

You are not limited to using {} once, you can put as many of them in your string as you’d like:

# calthoff/tstp year_started = “1989”

creator = “Guido van Rossum”

country = “the Netherlands”

my_string = “Python was created in {} by {} in {}.”.format(year_started, creator, country)

print(my_string)

>> ‘Python was created in 1989 by Guido van Rossum in the Netherlands.’

 

split

Strings have a method called split used to separate one string into two strings. You pass the split method the character or characters you want to use to separate the string—for example, we can pass in a period to separate this quote by Daniel Coyle into two different strings:

””” Practice doesn’t make perfect. Practice makes myelin, and myelin makes perfect.”””.split(“.”)

>> ["Practice doesn't make perfect", ' Practice makes myelin, and myelin makes perfect', '']

The result is a list with two different strings split at the period in the original string.

 

join

The join method lets you add new characters in between every character in a string:

my_string = ‘abc’

join_result = ‘+’.join(my_string)

join_result

>> ‘a+b+c’

You can turn a list of strings into a single string by calling the join method on an empty string ( “” ) and passing in a list:

the_Fox = [“The”, “fox”, “jumped”, “over”, “the”, “fence”, “.”]

one_string = “”.join(the_Fox)

one_string

>> The fox jumped over the fence.

 

replace

The replace method lets you replace every occurrence of a character(s) with another character(s). The first parameter is the character(s) to replace and the second parameter is the character(s) to replace it with.

my_string = “The cat jumped over the hat.”

my_string = my_string.replace(“a”, “@”)

my_string

>> “The c@t jumped over the h@t.”

 

index

We can get the index of the first occurrence of a character in a string with the index method. We pass in the character we are looking for, and we get the index of the first occurrence of the character in the string:

‘cat’.index(‘a’)

>> 1

The in keyword checks if one string is in another string and returns True or False :

“Playboy” in ””” A picture from Playboy magazine is the most widely used for all sorts of image processing algorithms” ””

>> True

Add the keyword not in front of in to check if one string is not in another string:

“ hello ” not in ””” The computer virus was initially designed without any harmful intentions ”””

>> True

 

Escaping Strings

What if you want to use quotes inside a string? If we use quotes inside a string we get a syntax error:

””” Sun Tzu said "The supreme art of war is to subdue the enemy without fighting." "


>> SyntaxError: invalid syntax

We can solve this with escaping, which means putting a special symbol in front of a character that has special meaning in Python (in this case the special character is a quote), to let Python know that this particular character is meant to be a character, and not the special Python symbol it usually represents. The special symbol we use to escape our quote is a backslash.

“““Sun Tzu said \"The supreme art of war is to subdue the enemy without fighting.\" ”””

>> ' Sun Tzu said "The supreme art of war is to subdue the enemy without fighting." '

 

Newline

We can use “\n” inside a string to represent a newline:

print(“line1 \nline2”)

>> ‘line1’

>> ‘line2’

 

Concatenation

We can add two strings together using the addition operator. The result will be one string with the characters from the first string followed by the characters from the next strings. This is called concatenation:

“cat” + “in” + “the” + “hat”

> ‘catinthehat’

“cat ” + “in ” + “the ” + “hat ”

>> ‘cat in the hat’

 

String Multiplication

We can also multiply a string by a number with the multiplication operator:

“cat” * 3

>> ‘catcatcat’

 

For Loops

For loops execute a set of instructions a certain number of times. You give a for loop a number to start at (we will call this number a ), a number to stop at (we will call this number z ), a set of instructions, and a variable that keeps track of the number of times the instructions have been executed (we will call this variable i ).

 

You can think of a for loop as a circle. It goes round and round executing instructions. Every time the loop executes its instructions, i (which starts at the value of a ) gets incremented by 1. When i becomes equal to z , then the for loop stops.

 

You define a for loop with the syntax for [variable_name] in range(a, z): [code_to_execute] where a is the number to start at, z is the number to stop at, and [variable_name] is a variable name of your choosing that gets assigned to whatever number the loop is on (we’ve been referring to it as i ) and code_to_execute is the code you define that is executed each time around the loop. This all is easier to understand with an example:

# calthoff/tstp

for i in range(0, 10):

print(i)

>> 0

>> 1

…

>> 9

In this example, we chose i as our variable_name. This is the variable name people in the Python community usually use when they write a for a loop. Your code_to_execute has access to the variable i.

 

When we run this program, our program enters ours for the loop. a starts at 0 , z starts at 10 and I starts at the same value as a — 0. The first time around the loop i is 0 , and our for loop executes its instructions— print(i) — which prints 0 (because i is equal to 0 ). The next time around the loop, i is incremented by 1 , so i is now 1, and so 1 gets printed.

 

The next time around the loop, i is incremented by 1 again, and so now i is 2, and so 2 gets printed. Eventually, I will equal 10. When this happens, nothing will print, because i is equal to z and so the loop ends.

 

When a loop ends, its instructions stop executing, and Python moves on to the next line of code after the loop. That is why 9 is the last number printed. If there were more code after our loop, Python would execute it, but in this example, there is not, and so the program ends.

 

There is another for loop syntax we can use for iteration. Iteration means going one by one through an iterable. An iterable is an object that has indexes. Some examples of iterables are strings, lists, tuples and dictionaries. Iteration is done with the syntax for variable_name in iterable: [code_to_execute] .

 

Just like the first syntax, we chose a variable name and define the code to be executed each time around the loop. In this syntax, instead of our loop executing code until i is equal to z , our loop starts at the first index in the iterable, and stops after the last index. Also variable_name gets assigned to the item at the index we are at (in the iterable). Here is an example:

# calthoff/tstp

my_string = “Python”

for character in my_string:

print(character)

>> ‘P’

>> ‘y’

>> ‘t’

>> ‘h’

>> ‘o’

>> ‘n’

# calthoff/tstp

my_list = [“a”, “b”, “c”]

for item in my_list:

print(character)

>> ‘a’

>> ‘b’

>> ‘c’

# add github

my_tuple = (“a”, “b”, “c”)

for item in my_tuple:

print(character)

>> ‘a’

>> ‘b’

>> ‘c’

# add github

my_dict = {“self”: “taught”, “programming”: “wizard”} for key in my_dict:

print(key)

>> “self”

>> “wizard”

Each of these examples loops through an iterable, and prints each item in it. You will notice we used several different variable names for variable_name . In this syntax, instead of using i , you want to use a descriptive variable name. In the first example, we used character , because each item at an index in a string is called a character.

 

In the second and third examples, we used item , because each object in a list or tuple is called an item. In the last example, we used key , because when you iterate through a dictionary like this, you can only access each key in the dictionary, not the value— so we chose a variable name to make this clear.

 

Being able to loop through an iterable is very useful. Iterables are used to store data, and you can use for loops to loop through your data to easily make changes to it, or move the data from one iterable to another.

 

While Loops

While for loops execute code a certain number of times, while loops execute code as long as the expression in its header evaluates to True. The syntax for creating a while loop is while [expression]: [code_to_execute] . Like a for loop, a while loop goes around like a circle executing code. The difference is instead of executing code a set amount of times, a while loop executes code as long as the expression we define in its header evaluates to True.

 

If we use an expression that always evaluates to True, our loop will run forever. This is called an infinite loop. Writing an infinite loop is easy (be prepared to press control-c on your keyboard in the Python shell. It is the only way to stop an infinite loop from running).

# calthoff/tstp

while True:

print(“Hello, World!”)

>> Hello World

...

Because a while loop runs as long as its expression evaluates to True —and True always evaluates to True —this loop will run forever, continuously executing the code we defined. In other words, our program will never stop printing “Hello, World!”. Now let’s look at a while loop with an expression that will eventually evaluate to False :

# calthoff/tstp x = 10

while x > 0:

print(‘{}’.format(x))

x -= 1

print(“Happy New Year!”)

>> 10

>> 9

>> 8

>> 7

>> 6

>> 5

>> 4

>> 3

>> 2

>> 1

>> ‘Happy New Year!’

Our while loop will execute its code as long as the expression we defined is True. In this case, that means it will execute its code as long as x > 0. x starts at 10 ( we defined x before we created our while loop). The first time through our loop, x is 10 , so x > 0 evaluates to True. Our while loop’s code prints x and then decrements x by 1 — x is now 9.

 

The next time around the loop x gets printed and x becomes 8 . This continues until x becomes 0 , at which point x > 0 evaluates to False and our loop ends. Python then executes the next line of code after our loop— print(“Happy New Year!”) — which prints “Happy New Year!”.

 

Break

You can prematurely end a for or while loop with the keyword break. For example, the following loop will run one hundred times:

# calthoff/tstp for i in range(0, 100):

print(i)

>> 0

>> 1

...

But if we add a break statement to the code the loop executes, the loop only runs once:

# calthoff/tstp

for i in range(0, 100):

print(i)

break

>> 0

The loop goes around once and prints 0 . When the the break keyword is executed, the loop ends. This is useful in many situations. For example, we can write a program that asks the user for input until they type “q” to quit:

# calthoff/tstp

“““If you are unfamiliar the reference in this example, go watch Monty Python and the Holy

Grail!”””

questions = [“What is your name?”, “What is your favorite color?”, “What is your

quest?”]

n = 0

while True:

print(“Type q to quit”)

answer = input(questions[n])

if answer == “q”:

break

n += 1

if n > 2:

n = 0

Each time through our infinite loop, our program will ask the user a question from our list of questions. We use the variable n to keep track of a number which we use as an index to get a question from our questions list. When n becomes greater than 2 , we’ve run out of questions and we set n back to 0 which will ask the first question in the list. This will go on indefinitely, unless the user types in “q” , in which case our program hits the break keyword and the loop ends, which ends our program.

 

Continue

You can use the keyword continue to stop executing a for or while loop’s code, and jump to the top of a loop. Say for instance, we want to print the numbers from 1 to 5 , except for the number 3 . We can do this by using a for loop with the continue keyword:

# calthoff/tstp

for i in range(1, 6) :

if i == 3:

continue

print(i)

>> 1

>> 2

>> 4

>> 5

 

In our loop, when i equals 3 , our program hits the continue keyword. Instead of causing our loop to exit completely—like the break keyword—the loop persists but we get jumped to the top of our loop, which means any of the loop’s code that would have executed that time around the loop gets skipped. In this case when i is equal to 3 , everything after continue is skipped (in this case print(i) ). The result is 3 is not printed. Here is the same example with a while loop:

# add GitHub i = 1

while i <= 5:

if i == 3:

continue

print(i)

 

Nested Loops

You can combine loops in various ways. For example, you can have one loop inside of another loop. You can also have a loop inside a loop inside a loop. There is no limit to the amount of times you can do this, although in practice you want to limit the number of times you do.

 

When a loop is inside another loop, the second loop is said to be nested in the first loop. The first loop is called the outer loop, and the nested loop is called the inner loop. When you nest two loops, the inner loop runs its full course each time around the outer loop. Here is an example:

# calthoff/tstp

for i in range(1, 3):

print(i)

for a letter in [‘a’, ‘b’, ‘c’]:

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 outside loop runs—in this case twice. If we changed our outer loop to run three times, the inner loop would iterate through the list three times.

 

If you have two lists of numbers and want to create a new list with all of the numbers from each list added together you can use two for loops:

# calthoff/tstp list1 = [ 1 , 2 , 3 , 4 ]

list2 = [ 5 , 6 , 7 , 8 ] added_up = []

for i in list1: for j in list2:

added_up.append(i + j)

print (added _up)

>> [6, 7, 8, 9, 7, 8, 9, 10, 8, 9, 10, 11, 9, 10, 11, 12]

In the second for loop we used the variable j because i is already in use by the first loop.

 

Importing Built-in Modules

In order to use a module, you must import it first, which means use a special syntax to make the code in the module available to use in your program. This is done with the syntax import [module_name]. import is a keyword for importing modules and must be followed by the module name. For now, we are only going to learn how to import built-in modules and modules located in the same folder as the module you are importing it from.

 

We can import Python’s built-in math module with the following syntax:

import math

>> 

 

The math module is a module that comes with Python when you install it. It is a regular Python file with a bunch of math-related functionality—it contains Python functions that are useful when you are doing the math. Once you’ve imported a module, you can use any of the code from it. You can access a function in the module with the syntax [path_to_module]. [function_name]() . With this syntax, you can use any of the code (such as a function) from the math module in your program:

import math

math.fabs(-3)

>> 3

The fabs function returns the absolute value of the parameter you pass in. You may be wondering how you are supposed to know there is a math module with a function called fabs in it. A list of Python’s built-in modules can be found at Python Module Index. If you search for the math module, there is a link that takes you to a page that lists every function in the math module, what each function does, and what parameters it takes.

 

Another built-in module is the random module. Here is an example of importing the random module, and using a function from it called randint that takes two numbers as parameters and returns a random number between them.

# The output of this program might not be 52 when you run it—it’s random! import random

random.randint(0,100)

>> 52

 

There are other syntaxes for importing modules, but in general import [module_name] is the syntax you should use, and the one we will be using throughout the blog. Finally, you should do all of the imports for your program at the top of your file.

 

Importing Modules

In this section, we are going to create a module, and use the code from it in another module. First, create a new folder on your computer called tstp, then create a file called http://hello.py in it.

# calthoff/tstp

def print_hello():

print(“Hello”)

Save the file. Inside the tstp folder, create another Python file called http://project.py.

# calthoff/tstp import hello

hello.print_hello()

>> ‘Hello’

Using the import keyword we can easily use code from our first module in our second module.

 

Working With Files

The open function takes a string representing the path to a file and a string representing the mode to open the file in as parameters. The path to a file—also called a file path— represents the location on your computer a file resides, for example: /Users/calthoff/my_file.txt is the file path to a file called my_file.txt.

 

Each word separated by the slash that precedes it is the name of a folder. Together they represent the location of that file. If a file path only has the name of the file, Python will look for the file in whatever folder you are running your program in.

 

The second parameter represents the mode to open the file in, which determines the actions you will be able to perform on the file. Here are a few of the modes you can open a file with:

“r” Opens a file for reading only.

“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 both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

5

Once you’ve passed the open function a file path and mode as parameters, open creates a file object we can use to read or write to our file (or both depending on the mode you chose). Here is an example of writing to a file:

my_file = open(“my_file.txt”, “w”)

my_file.write(“Hello from Python!”)

my_file.close()

>> 

open creates a new file called my_file.txt (because we passed in “w” as our model) in whatever directory you ran our program in. We save our file object returned by the open function in the variable my_file.

 

Now we can call the write method on our file object, which accepts a string as a parameter and writes it to the new file we created. Finally, we closed our file by calling the close method on the file object. This is an important step. Whenever you open a file using the open method, you need to close it with the close method. If you have a program where you use the open method on multiple files, and you forget to close them, it can cause problems in your program.

 

Using with

Because forgetting to close files you opened can cause problems, there is a second, preferred syntax for opening files. The preferred way to open a file in Python is to use a compound statement using the with keyword and the syntax with open(‘my_file’,[mode]) as [variable_name]: [your_code].

 

When you use a compound statement using with the file automatically closes after the last suite executes in the statement. The file object gets saved in a variable of your choosing ( [variable_name] ). Here is the example from the previous section written using the preferred syntax for opening a file:

# calthoff/tstp with open(‘my_file.txt’, ‘w’) as my_file:

my_file.write(‘Hello from Python!’)

>> 

As long as you are inside of them with the statement, you can work with the file you opened using the variable you created—in this case my_file. As soon as Python leaves them with the statement, it closes the file for you.

 

Reading Files

If you want to access the contents of a file (read the file) you pass in “r” as the second parameter to open. Then you can call the read method on your file object which returns an iterable you can iterate through to get each line of the file.

# calthoff/tstp

with open(“my_file.txt”, “r”) as my_file:

for line in my_file.read():

print(line)

> > Hello from Python!

 

You can only call read on a file once (each time you run your program) to gets its contents, so you should save the file contents in a variable or container if you need to use the file contents again later in your program. For example, we could change the previous example to save the file contents in a list:

#

my_list = list()

with open(“my_file.txt”, “r”) as my_file:

for line in my_file.read():

my_list.append(line)

print(my_list)

> > Hello from Python!

With the file contents saved in a list, we can easily access it later in our program whenever we need it.

 

CSV Files

Python comes with a built-in module for working with CSV files. CSV stands for comma separated value. It is a file format commonly used in Microsoft Excel: a program for creating spreadsheets. A comma in a CSV file is called a delimiter. Every piece of data separated by a comma represents a cell in Excel. Each line of the CSV file represents a row in Excel. Here is an example of the contents of a csv file:

# my_file.csv one, two, three four, five, six

 

You could load this file into excel and one, two and three would each get their own cells in the first row of the spreadsheet; and four, five and six would each get their own cells in the second row of the spreadsheet.

 

We can use a with a statement to open a CSV file like the example from the previous section, but inside the with statement, we need to use the csv module to convert our file object into a csv object. The csv module has a method called a writer that accepts a file object and a delimiter and returns a csv object with a method called writers we can use to write to our CSV file:

# calthoff/tstp

import csv

with open (‘ my_file.csv’ , ‘w’ ) as csvfile: spamwriter = csv . writer(csvfile, delimiter = ',’) spamwriter . writerow([ ‘one’, ‘two’, ‘three’ ]) spamwriter . writerow([‘ four’, ‘five’, ‘six’ ])

>> 

 

The write row method accepts a list as a parameter. Every item in the list gets written to the CSV file and each item is separated by the delimiter you passed to the writer method (in this case a comma). writers only write one row, so we have to call it twice to create two rows. When you run this program, it will create a new file called my_file.csv and when you open the file with a text editor, it will look like this:

# my_file.csv one, two, three four, five, six

 

If you load this file into Excel (or Google Sheets a free Excel alternative), the commas disappear, but one, two and three will each have their own cell in row one; and four, five and six will each have their own cell in row two.

 

We can also use the csv module to read the contents of a file. To read from a CSV file, first, we pass in ‘r’ to open as the second parameter. This opens the file for reading only. Instead of using the writer method like the previous example, we use the reader method but still, pass in the file path and a comma as the delineator.

We can call the join method on a comma to add a comma between each value to print the contents of the file as it appears in the original file:

# calthoff/tstp import csv

with open(‘my_file.csv’, ‘r’) as csvfile:

spamreader = csv . reader(csvfile, delimiter = ',' )

for row in spamreader:

print ( ',' . join(row))

>> one,two,three

>> four, five, six

 

Hangman

First, we create a function called hangman we can call to start the game. The word to guess is stored in the variable word (you can change the word the player has to guess by changing the variable). We use another variable wrong_guesses to keep track of how many incorrect letters the player has guessed.

 

When each string in the stages list is printed on a new line, a picture of hangman forms. letters_left is a list made up of each character in a word . We will use it to keep track of which letters are left to guess in our word.

 

The scoreboard is a list of strings used to keep track of the hints we display to the user e.g., “c __ t” if the word is “cat”. The initial value of score_board is calculated with [‘__’] * len(word) which returns a list made up of the number of underscores to start with. For example, if the word is “cat” score_board starts as [“__”, “__”, “__”] .

 

Finally, we have a winning variable that starts as False to keep track of whether the player has won the game yet or not. To start the game off we print Welcome to Hangman. When you build a game, you normally use a loop that continues until the game is over.

 

Here is the loop we will use in our game:

while wrong_guesses < len (stages) - 1 :

print ( ' \n ' )

guess = input ( "Guess a letter" )

if guess in letters_left:

character_index = letters_left.index(guess)

score_board[character_index] = guess

letters_left[character_index] = '$'

else :

wrong_guesses += 1

print ( '' .join(score_board))

print ( ' \n ' .join(stages[ 0 : wrong_guesses + 1 ]))

if '__' not in score_board:

print ( 'You win! The word was:' )

print ( ' ' .join(score_board))

win = True

break

Our loop continues as long as the variable wrong_guesses is less than the len(wrong_guesses) - 1. wrong_guesses keeps track of the number of wrong letters the user has guessed, so as soon as the user has guessed more wrong letters than the number of strings that make up the hangman, the game is over.

 

The reason we subtract 1 is because the length function in Python does not count from 0, it counts from 1. In order to compensate for this, we have to subtract one, to compensate for the fact that length counts starting from 1 instead of 0. The reason we want to count from 0 is because stages is a list, and we are going to be using wrong_guesses as an index to get the strings from stages and indexes start at 0.

 

Inside our loop, we print a blank space to make our game look nice when it’s printed in the shell. Next, we collect the player’s guess with the built-in input function and store the value in the variable guess.

 

I the guess is in letters_left (a variable from the beginning of our program that keeps track of the letters that haven’t been guessed yet), the player guessed correctly. If the player guessed correctly we need to update our score_board list, which we use later in the game to display the score. If the user guessed “c” , we want to change our score_board to look like this: [“c”, “__”, “__”] .

 

We use the index method on our letters_left list to get the first index of the letter that was guessed. We use that index to replace the underscore in score_board at the index with the correctly guessed letter. We have a problem though. Because index only returns the first index of the character we are looking for, our code will not work if the word (the word the player is guessing) has more than one of the same character.

 

To compensate for this, we modify letters_left by replacing the character that was just correctly guessed with a dollar sign so that the next time around the loop, if there is more than one letter in the word index will find the second occurrence of the letter since the first occurrence of the letter was replaced by a dollar sign. If on the other hand, the player guesses an incorrect letter, we simply increment wrong_guesses by 1.

 

Next, we print the scoreboard and print our hangman using our score_board and stages lists. To print the scoreboard, all we have to do is print '' .join(score_board).

 

Printing the hangman is trickier. When each of the strings in our stages list is printed on a new line, a complete picture of a hangman is printed. We can easily create the entire hangman by printing ' \n ' .join(stages). This connects each string in the stages list with a blank space ( \n). But we want to print our hangman at the stage we are currently at, which we accomplish by slicing our stages list.

 

We start at stage 0 and slice up until whatever stage we are at (represented by the variable wrong_guesses ) plus one. The reason we add one is because when you are slicing, the end slice does not get included in the results. This gives us only the strings we need to print the stage of the hangman we are currently on which we then print.

 

The last thing we do in our loop checks if the user has won the game If there are no more underscores in the score_board list, we know the user has guessed all the letters and won the game. If the user has won, we print that they won and we print the word they correctly guessed. We also set the variable win to True which is used when we break out of our loop.

 

Once we break out of our loop, if the user won, we do nothing, and the program is over. If the user did not win, the variable win will be False. If that is the case we know the user lost the game and we print the full hangman, print “You lose!” followed by the word they incorrectly guessed:

if not win:

print ( ' \n ' .join(wrong_guesses[ 0 : stage]))

print ( 'You lose! The words was {}' .format(word))

hangman()

 

State

One of the fundamental differences between different programming paradigms is the handling of state. The state is the data your program has access to. Programs store data in variables—so the state is the value of a program’s variables at a given time the program is running.

 

Imperative Programming

In Part I, we learned to program imperatively. Imperative programming can be described as “do this, then that”. An imperative program is a sequence of steps moving toward a solution—with each step changing the program’s state. An example of imperative programming would be:

x = 2

y = 4

z = 8

xyz = x + y + z

>> 14

Each step of the program changes the program's state. We get to xyz by first defining x, followed by y, followed by z and finally defining xyz.

 

Functional Programming

Functional programming is another popular programming paradigm. It originates from lambda calculus. Functional programming involves writing functions that—given the same input— always return the same output. In functional programming, you only program with functions, you do not use classes—a feature of object-oriented programming we will learn about shortly.

 

There is a lot of jargon in functional programming and Mary Rose Cook does a great job cutting through it with her definition, “Functional code is characterized by one thing: the absence of side effects. It doesn’t rely on data outside the current function, and it doesn’t change data that exists outside the current function.” 61 She follows her definition with an example which I will also share with you. Here is an unfunctional function:

a = 0

def increment ():

global a

a += 1

Here is a functional function :

def increment (a):

return a + 1

The first function is unfunctional because it relies on data outside of itself, and changes data outside of the current function by incrementing a global variable. The second function is functional because it does not rely on any data outside of itself, and it does not change any data outside of itself either. Functional programmers write functions this way to eliminate side effects—the unintended consequences that happen when you are constantly changing the state of your program.

 

Object-oriented Programming

The object-oriented programming paradigm involves writing programs where you define and create objects that interact with each other. We’ve been programming with objects this whole time—strings, integers, and floats are all examples of objects. But you can also define your own objects using classes. Classes are the blueprint used to create objects. You can think of a class as the idea of an object. Think of an orange. An orange is an object. A fruit weighing between 2 to 10 ounces is the idea of an orange—a class.

 

We can model oranges in Python by defining a class we can use to create orange objects. We define a class using the class keyword followed by the name we want to give our class. A class is a compound statement with a header followed by suites. You write suites after the header, which can be simple statements, as well as compound statements called methods.

 

Methods are like functions, but they are defined inside of a class, and can only be called on the object the class can create. We saw different examples of this in blog 5 when we called various methods on strings. Here is an example of how we can represent an orange using a class in Python:

#

class Orange :

print ( "Orange created!" )

 

We started with the class keyword followed by the name of our class—in this case, Orange because we are modeling oranges. By convention, classes in Python always start with a capital letter and are written in camelCase—which means if a class name is made up of more than one word, the words should not be separated by an underscore (like a function name), instead each word should be capitalized like this.

 

After our class definition, we have a simple statement— print(“Orange created!”). This code will execute when we create an orange object. With this class definition, we can create as many Orange objects as we’d like:

orange = Orange()

print ( type (orange) )

print (orange )

>> Orange created!

>> <class '__main__.Orange'>

>> <__main__.Orange object at 0x101a787b8>

We created a new Orange object using the same syntax we use to call a function—[ classname](). This is called instantiating an object, which means creating a new object. “Orange created!” prints as soon as we instantiate our Orange object. When we print type(orange), the type function tells us our Orange object is an instance of the Orange class we just created.

 

When we print our Orange object, Python lets us know it is an Orange object, and then gives us its location in memory. When you print an object like this, the location in memory printed on your computer will not be the same as the example, because the object’s location in memory changes each time the program runs.

 

Now we are going to add a method to our Orange class. You define a method with the same syntax as a function. There are only two differences: a method must be defined as a suite in a class, and a method has to accept at least one parameter (except in special cases I won’t go into). You can name the first parameter of a method whatever you’d like, but by convention, the first parameter in a method is always named self, and I’ve never seen this convention broken.

 

The reason every method must have the first parameter is that whenever a method is called on an object, Python automatically passes the method the object that called it. This concept exists in most programming languages that support object-oriented programming, however, Python makes the passing of self as a parameter explicit whereas many other languages make it implicit. What I mean is that Python makes you explicitly define self in every method you create whereas in other languages self is just implied to have been passed to the object.

 

Inheritance

Inheritance in programming is similar to genetic inheritance. In genetic inheritance, you can inherit attributes from your parents, like your eye color. Similarly, when you create a class, it can inherit from another class (which is then called its parent class)—giving the new class you created the parent class’s variables and methods. In this section, we will model a kid and adult using inheritance. First, we define a class to represent an adult:

 

class Adult ():

def __init__ ( self , name , height , weight , eye_color):

"""height is in feet, weight in lbs."""

self .name = name

self .height = height

self .weight = weight

self .eye_color = eye_color

def print_name ( self ):

print ( self .name)

tom = Adult( "Tom" , 6 , 150 , "brown" )

print (http://tom.name)

print (tom.height)

print (tom.weight)

print (tom.eye_color)

tom.print_name()

>> Tom

>> 6

>> 150

>> brown

>> Tom

Using this class we can create Adult objects with a name, height, weight and eye color. In addition, our Adult objects have a method called print_name that prints the parent’s name.

 

We can model a human child that also has a name, height, weight, eye color and can print its name; with an extra method we don’t want our Adult objects to have called print_cartoon ; using inheritance. You inherit from a parent class by adding parenthesis to the class name you are defining, and passing in the class name you want to inherit from as a parameter. Here is an example:

class Adult ():

def __init__ ( self , name , height , weight , eye_color):

# height is in feet, weight in lbs. self .name = name

self .height = height self .weight = weight

self .eye_color = eye_color

def print_name ( self ):

print ( self .name)

class Kid (Adult):

def print_cartoon ( self , favorite_cartoon):

print ( "{}'s favorite cartoon is {}" .format( self .name , favorite_cartoon))

child = Kid( "Lauren" , 3 , 50 , "blue" )

print (http://child.name)

print (child.height)

print (child.weight)

print (child.eye_color)

child.print_name()

child.print_cartoon( 'DuckTales' )

>> brown

>> Ricky

>> DuckTales s

By passing in Adult to our Kid class, our Kid class inherits the variables and methods of our Adult class: when we create a Kid object we pass it a name, height, weight, and eye color; and our Kid object is able to use the method print_name; all of which was inherited from its parent class (without having to define any of it in our Kid class). This is important because not having to repeat code makes our program smaller and therefore more manageable.

 

After inheriting from our Adult class, all we had to do was define a new method called print_cartoon in our Kid class to create a Kid class with all of the functionality of our Adult class, plus additional functionality; all without affecting our Adult class.

 

Polymorphism

The best definition I’ve found of polymorphism is “polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types) ” An interface refers to one or more functions or methods. Let’s take a look at a situation where this is the case:

print( 'Hello World' )

print( 200 )

print( 200.1 )

>> “Hello World”

>> 200

>> 200.1

In this example, we were able to present the same interface (the print function) for three different data types: a string, an int and a float. We didn’t need to call three separate functions — print_string, print_int, or print_float in order to print these three different data types— instead Python has just one interface for all of them.

 

Let’s take a look at another example. Say we want to write a program that can draw different shapes: triangles, squares, and circles. Each of these shapes is drawn in a different way, so the methods to draw them would all have different implementations. In Python, we can create different draw methods for each shape so that Triangle.draw() will draw a triangle, Square.draw() will draw a square, and Circle.draw() will draw a circle.

 

Each of these shape objects has its own draw interface that knows how to draw itself. When we have a shape object, we know we can call the draw function to draw the shape. The same interface is presented for all the different shape data types.

 

If Python did not support polymorphism— we would need a function that creates a triangle, and another function called draw_triangle to draw it; a function to create a circle, and a function called draw_circle to draw it; etc. Because Python has polymorphism, every shape can simply be drawn with its draw method.

 

This makes our shape objects much easier to use and explain. Instead of explaining—we have three functions representing three different shapes, and another three functions that draw each of them; we can simply tell whoever is using the code: we have three shapes—if you want to draw one—call its draw method.

 

Abstraction

We use abstraction in object-oriented programming when we create a class and define its methods. Say we create a class to represent a person. When we define our person class— and the methods that go with it— we are creating an abstraction. Our definition of a person could include eye color, hair color, height and ethnicity as well as the ability to read, write and draw.

 

We could have a five foot three person with blue eyes, blonde hair unable to read, write or draw. Or we could have a six-foot five-person with brown eyes, brown hair that can read, write and draw. Both of these fall into the category of the person abstraction we’ve created.

 

When we design object-oriented programs, we create abstractions of different concepts that all work together to form our program. For example, we may create an abstraction of a person, and an abstraction of a government and model how many people live under each government in the world. Abstraction allows us to model objects with clear boundaries, and have them interact with each other. 

 

Encapsulation

In object-oriented programming, encapsulation hides our codes internal data. When the code is encapsulated, it means when it is called, the caller cannot access the code's internal data. Take a look at the method get_data :

class Data :

def get_data (self, index , n):

data = [ 1 , 2 , 3 , 4 , 5 ]

data.append(n)

 

The method has a variable called data. When we call get_data, there is no way for us to access this variable because of encapsulation. If there was no encapsulation, we might be able to access the variable data —and append n to it—like this:

# warning this code does not work Data.get_data.data.append(6)

 

If this was allowed, anyone could access the data variable in our get_data method. Instead of relying on our implementation of the get_data method—they could append n to data themselves. This is not a problem—until we change the implementation of get_data. What if we decide to want the variable data to be a tuple instead of a list?

 

If we make this change, it will break anyone’s code calling append on the variable data, because tuples do not have an append method. But because of encapsulation, this scenario is not possible (which is why the code does not work), and we can be assured changes to the internal implementation of our code won’t break our client’s code (client is a term for the person using a piece of code).

 

Composition

While the composition is not one of the four pillars of object-oriented programming, it is an important concept related to the rest. The composition is used to represent “has a” relationships—it occurs when one object stores another object as a variable. For example, say we want to represent the relationship between a dog and its owner—this is a “has a” relationship—a dog has an owner. First, we define our dog and people classes:

class Dog ():

def __init__ (self, name, breed, owner):

self .name = name

self .breed = breed

self .owner = owner

class Person ():

def __init__ ( self , name):

self .name = name

When we create our dog object, we pass in a person object as the owner parameter:

mick = Person( "Mick Jagger" )

dog = Dog( "Stanley" , "French Bulldog" , mick)

print (dog.owner)

>> Mick Jagger

Now our dog Stanley has an owner—a Person object named Mick Jagger—we can easily reference.

 

How Variables Work

In this section, we are going to learn more about variables. Variable “point” to an object.

number = 100

number points to an integer object with the value 100.

[illustration of a point to an object]

number = 101

 

When we assign a new value to number, it points to a new integer object with the value 101, and the old integer object with a value of 100 is discarded because it is no longer being used. Two variables can point to the same object:

x = 100

y = x

x points to an integer object with a value of 100. When we assign y to x, y now points to the same integer object x points to they both point to an integer object with a value of 100.

What do you think the following program will print?

x = 10

y = x

x += 1

print(x)

print(y)

 

The answer is 11 and 10. x points to an integer object with a value of 10, and when we create y, it points to the same integer object. When we increment x, x points to a new integer object —with a value of 11, but the integer object with a value of 10 is not discarded, because it is being used: y still points to the integer object with a value of 10.

 

So when we print x, 11 prints because we assigned x to a new integer object—11—but when we print y — 10 prints because changing the value of x, which points to the integer object 11, does not affect the value of y. Here is another example to illustrate this point. What do you think the output of this code will be?

x = [1, 2, 3]

y = x

y[2] = 100

print(x)

print(y)

The output will be [1, 2, 100] twice . The reason is that both x and y point to the same list object. In the third line, we make a change to that single list object, and when we print both variables, it prints the list object they both point to, with the changes made in line 3.

The keyword is returns True if two objects are the same object (they are stored in the same location in memory) and False if not.

class Person :

def __init__ ( self ):

self .name = 'Bob'

bob = Person()

the_same_bob = bob

print (bob is the_same_bob)

another_bob = Person()

print (bob is another_bob)

>> True

>> False

When we use the keyword is with bob and the_same_bob, the result is True because both variables point to the same Person object. When we create a new Person object and compare it to the original bob the result is False because the variables point to different Person objects.

 

None

The built-in constant None is used to represent the absence of a value:

x= None

x

>> None

We can test if a variable is None using conditional statements.

x = 10

if x:

print ( "x is not None" )

else :

print ( "x is None :( " )

>> x is not None

x = None

if x:

print ( "x is not None" )

else :

print ( "x is None :( " )

>> x is None :(

While this may not seem useful now, it will be later.

 

Classes Are Objects

In Python, classes are objects. This idea comes from the influential programming language SmallTalk. This means that when running a program in which you define a class—

 

Python turns it into an object—which you can then use in your program:

class Pterodactyl :

pass

print (Pterodactyl)

>> <class '__main__.Pterodactyl'>

Without any work on our part, Python turns our class definition into an object which we can then use in our program, by printing it for instance.

 

Class Variables vs. Instance Variables

Classes can have two types of variables—class variables and instance variables. All of the variables we’ve seen so far have been instance variables defined with the syntax self. [variable_name] = [variable_value] . Instance variables belong to the object that created them. In other words, we can do this:

class Liger :

def __init__ ( self , name):

self .name = name

connor = Liger( "Connor" )

print (http://connor.name )

 

>> Connor

Class variables belong to both the class that created them and the object. That means we can access them with the class object Python creates for each class:

class Liger :

interests = [ "swimming" , "eating" , "sleeping" ]

def __init__ ( self , name):

self .name = name

print (Liger.interests)

>> ['swimming', 'eating', 'sleeping']

 

In this example, we never created a Liger object, yet we were able to access the interests class variable. This is because class variables can be accessed by the class that created them. Class variables can also be accessed by the object:

class Liger :

interests = [ "swimming" , "eating" , "sleeping" ]

def __init__ ( self , name):

self .name = name

larry = Liger( "Larry" )

print (larry.interests)

>> ['swimming', 'eating', 'sleeping']

Class variables are useful when you want every object in a class to have access to a variable. In this case, the name of each Liger can be unique, but all of our Ligers to have access to the same list of interests.

 

Private variables

Most programming languages have the concept of private variables and methods: special variables and methods the designer of a class can create that the object has access to, but the programmer using the object does not have access to. One situation private variables and methods are useful in is if you have method or variable in your class the class uses internally.

 

But you plan to change the implementation of your code later on (or you want to preserve the flexibility to have the option to), and therefore don’t want whoever is using the class to rely on those variables and methods used internally because they might change (and would then break their code).

 

Unlike other languages, Python does not have private variables. Variables that are not private are called public variables, and all of Python’s variables are public. Python solves the problem private variables resolve another way—by using the convention. In Python, if you have a variable or method the caller should not access, you precede its name with an underscore. Python programmers know if a method or variable has an underscore, they shouldn’t use it, although they are still able to at their own risk. Here is an example of a class that uses this convention:

class PublicPrivateExample:

def __init__ ( self ):

self .public_variable = "callers know they can access this"

self ._dontusethisvariable = "callers know they shouldn't access this"

def public_method( self ):

# callers know they can use this method

pass

def _dont_use_this_method( self ):

# callers know they shouldn't use this method pass

Python programmers reading this code will know self.public_variable is safe to use, but they shouldn’t use self._dontusethisvariable , and if they do, they do so at their own risk because the person maintaining this code has no obligation to keep self.dontusethisvariable around because callers are a not supposed to be accessing it. The same goes for the two methods: Python programmers know public_method is safe to use, whereas _dont_use_this_method is not.

 

Overriding Methods

When a class inherits a method from a parent, we have the ability to override it. Take a look at the following example:

class Mammal :

def __init__ ( self , name):

self .hunger = 100

self .tired = 100

self .name = name

def print_result ( self , amount , action):

print ( "{} {} decreased by {}." .format( self .name , action , amount))

def eat ( self , decrease):

self .hunger -= decrease

self .print_result(decrease , 'hunger' )

def sleep ( self , decrease):

self .tired -= decrease

self .print_result(decrease , 'tiredness' )

class Dolphin (Mammal):

pass

class Tiger (Mammal):

def sleep ( self , decrease):

self .tired -= decrease

print ( "The tiger is really tired!" )

dolphin = Dolphin( 'dolphin' )

dolphin.eat( 10 )

dolphin.sleep( 10 )

tiger = Tiger( 'tiger' )

tiger.eat( 10 )

tiger.sleep( 10 )

> > dolphin hunger decreased by 10. >> dolphin tiredness decreased by 10. >> tiger hunger decreased by 10.

>> The tiger is really tired!

We created two classes that inherit from Mammal. The first class, the Dolphin , inherits all of its functionality from the Mammal parent class without making any changes. The second class Tiger defines a method called sleep, with different functionality than the sleep method it inherited from its parent class. When we call tiger.sleep , the new method we defined gets called instead of the inherited method. Other than this, Tiger and Dolphin have all the same functionality inherited from the parent class Mammal.

 

Super

The built-in super function, lets us call a method a class inherited from its parent. The super function is used with the syntax super().[parent_method]([parameters]) where you replace parent_method with the parent method you want to call and pass it any parameters it needs.

 

The parent method is then called and executed, and the rest of the code in the method super was called from then finishes executing. Here is an example of how we can call the Mammal parent class's sleep method from our Tiger classes’ sleep method, in order to use the code from the Mammal class’s sleep method followed by additional functionality:

class Tiger (Mammal):

def sleep ( self , decrease):

super ().sleep(decrease)

print ( "The tiger is really tired!" )

tiger = Tiger( 'tiger' )

tiger.eat( 10 )

tiger.sleep( 10 )

>> tiger tiredness decreased by 10.

>> The tiger is really tired!

First, we use the super keyword to call the Mammal parent class’s sleep method and pass in the decrease variable as a parameter. Mammal’s sleep method is executed and prints “tiger tiredness decreased by 10”. The Tiger classes sleep method then executes the new functionality we added to the Tiger classes sleep method and “The tiger is really tired!” prints.

 

By using the super keyword we were able to give a child class the functionality from a parent class’s method without having to retype the functionality in the child class. This is important because you should always avoid repeating code with the same functionality in different places in your program when you can.

 

Overriding Built-in Methods

Every class in Python automatically inherits from a parent class called Object. All classes in Python inherit methods from this parent class. Python’s built-in functions use these methods (which we learned are called magic methods)—in different situations—like when we print an object:

class Lion :

def __init__ ( self , name):

self .name = name

lion = Lion( "Dilbert" )

print (lion)

>> <__main__.Lion object at 0x101178828 >

When we print our Lion object, Python calls the __repr__ method on our object, which it inherited from the Object parent class. It prints whatever the __repr__ method returns. We can override this built-in method to change what happens when the print function prints our object.:

class Lion:

def __init__ ( self , name):

self .name = name

def __repr__ ( self ):

return self .name

lion = Lion( "Dilbert" )

print (lion)

>> Dilbert

Because we overrode the __repr__ method, when we print our Lion object, the Lion object’s name— Dilbert — gets printed instead of something like <__main__.Lion object at 0x101178828 > which the inherited __repr__ method would have returned.


Not all magic methods are inherited. Python expressions like 2 + 2 expect the operands to have a method the operator can use to evaluate the expression. In example 2 + 2 , integer objects have a method called __add__ which is called when the expression is evaluated, but __add__ is not inherited when you create a class. We can create objects that can be used as operands in an expression with the addition operator by defining a __add__ method in our class:
class AlwaysPositive :

def __init__ ( self , number):

self .number = number

def __add__ ( self , other):

return abs ( self .number + other.number)

x = AlwaysPositive(- 20 )

y = AlwaysPositive( 10 )

print (x + y)

>> 10

Our AlwaysPositive objects can be used as operands in an expression with the addition operator because we defined a method called add. The method must accept the second parameter, because when an expression with an addition operator is evaluated, __add__ is called on the first operand object, and the second operand object gets passed into __add__ as a parameter. The expression then returns the result of __add__ .


In this example, we added a twist. We used the function abs to return the absolute value of the two numbers being added together. Because we defined __add__ this way, two AlwaysPositive objects added together will always return the absolute value of the sum of the two objects.

 

Finding Bash

You can find Bash by searching for a 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.

 

Using Bash

Bash is similar to the Python Shell. The Bash command line shell takes its own programming language called Bash as input. The programming language Bash has commands—which are like functions in Python. We start with a keyword; type a space; type the parameter we want to give the command (if any); hit the enter key, and Bash returns the result. One of Bash’s commands is an echo , which is similar to the print function in Python. Here is an example:

$ echo Hello, World! >> Hello, World!

 

We typed the command echo into Bash, followed by a space and Hello, World! as a parameter. When we press enter, Hello, World! prints in the Bash command line shell. You can also use programs you’ve installed—like Python—from the Bash command line shell. Enter the command python3 to use Python from the shell:

$python3

>> 

Now you can execute Python code:

print(“Hello, World!”)

>> Hello, World! Enter exit() to exit Python.

 

Relative vs Absolute Paths

An operating system is made up of directories and files. A directory is another word for a folder on your computer. All directories and files have a path. A path is as an address where a directory or file exists in your operating system. When you are using the Bash command line shell, you are always in a directory, located at a specific path. You can see the path you are at by entering the command pwd in the Bash command line shell:

pwd

>> /Users/bernie

pwd stands for the print working directory (a working directory is a directory you are currently in), and the path that prints on your computer will be the name of whatever directory you are in.

 

The folders in your operating system are a tree. A tree is an important concept in Computer Science called a data structure. In a tree, there is a root at the top. The root can have branches, and each one of the branches can have more branches, and those branches can have branches. This goes on indefinitely.

[add an illustration of a tree data structure]

root

/ \

home etc

/ \

bernie bin

/ \

test projects

Every branch on the tree is a directory, including the root. The tree shows how they are connected to each other. When you are using Bash, at any given time you are at one of the locations on the tree, and a path is a way of expressing that location. There are two ways of expressing a location on Unix-like operating systems: absolute paths and relative paths.

 

An absolute path is a way of expressing a location starting from the root directory. An absolute path is made up of the name of folders in the tree, in order, separated by backslashes. The absolute path to the Bernie directory (for the operating system illustrated above) is /home/Bernie . The first slash represents the root directory; followed by the home directory; followed by another slash and the Bernie directory.

 

The other way of specifying a location on your computer is called using a relative path. Instead of starting at the root directory, a relative path is relative to the directory you are in. Your operating system knows a path is relative when it doesn’t begin with a backslash. If we were located in the home directory in the example above, the relative path to the projects directory would be Bernie/projects . If we were in the home directory, the relative path to Bernie is simply Bernie .

 

Navigating

You can use the cd command, which stands for change directory, to navigate to a directory using an absolute or relative path. Enter the cd command followed by the absolute path / to navigate to the root directory:

$ cd /

You are now in your root directory, which you can verify with the command pwd :

$ pwd >> /

The command ls , which stands for list directories, prints the folders in the directory you are in:

$ ls

>> bin dev initrd.img lost+found

...

You can create a new directory with the command mkdir . Directory names cannot have spaces in them. Use the mkdir command to make a new directory called tstp :

$ mkdir tstp

>> 

Verify the new directory exists with the command ls . Now use the cd command to enter the tstp directory by passing in the relative path to tstp as a parameter:

$ cd tstp

Now use the cd command followed by two periods to return to the folder you were in before you entered the tstp directory:

$ cd ..

Delete the new directory using the command rmdir , which stands for remove directory:

$ rmdir tstp

Use the command ls to verify the directory was deleted.

 

Flags

Commands have a concept called flags that allow the issuer of the command to change the behavior of the command. If you use a command without any flags, all of the command's flags are set to false. But if you add a flag to a command, the flag is set to true and the behavior of the command changes.

 

The - and -- symbols are used to attach flags to a command. -- the author is an example of a flag you can add to the ls command to print the author of all of the directories and files that get listed. This example is for Linux, on OS X you can use the same flag but you need to use one dash instead of two. Here is an example of using the --author flag with the ls command:

$ ls --author

>> drwx------+ 13 coryalthoff 442B Sep 16 17:25 Pictures

...

When you add the --author flag to your ls command, the name of each directory and folder in your current directory will print—as well as some additional information, including the name of the person that created them.

 

vim

Vim is a command line text editor. It's like Microsoft Word, except you use it from the command line. If you are using Ubuntu, first install vim with the command apt-get install vim. Make sure to enter Y when prompted. If you are using a Mac, it should come with vim If you are using the online bash shell, it already has vim installed.

 

You can create a new file with vim by going to the command line and using the command vim [name of the file to create] . Use the command vim self_taught.txt to create a new text file called self_taught.txt. Press the I or insert key and type a paragraph of text into the file. Any paragraph of text you find on the internet will do.

 

The reason you have to hit the I or insert key when you first enter a file is that vim has different modes optimized for different activities. vim starts in, Normal Mode, which is not meant for adding text to the file (it is meant for easy navigation)—you can delete text in normal mode, but you cannot insert new text. Once you press the I or insert key and enter normal mode, you can use vim like a word processor—try typing into vim.

 

Since you can’t use your mouse to move the cursor around, it’s important to learn a few shortcuts to jump to different locations in your document, so that you don’t end up using the arrow keys on your keyboard (because that’s slow). To practice moving around, first make sure you are in Normal Mode ( control-c ).

 

You can move to the beginning of a word by pressing b and the end of a word with e. 0 will move you to the beginning of the line you are on, while the dollar signs $ will move you to the end of the line. H will move you to the first line of the page and L will move you to the last. You can delete entire lines of text in normal mode by pressing the d key twice. Spend some time using these keys to get familiar with navigating through a file using vim.

 

To exit vim you need to first switch to Normal Mode by pressing control-c. Next press the shift key and then hit the colon key (while still holding the shift key). From here you can type q! if you want to quit without saving your changes to the file, or type x if you want to save your changes and quit. Once you’ve typed one of these options, press the enter key to exit.

 

vim is useful in a few situations: servers are usually only accessed with a command line shell, so if you want to make changes to a file on a server, you need to use a command line text editor, and once you get good at using vim, it is often faster to use it to make changes than using a conventional word processor. Try typing vimtutor in the Bash command line shell and see what happens.

Touch

You can use the command touch followed by a file path to quickly create a new file:

$ touch purple_carrots.txt

>> 

 

View A File With less

The less command enables you to view files from the command line. Pick a file on your computer and use the command less [filepath] to view the file from the command line in the less program. Make sure you are in the same folder you created the file selftaught.txt in with vim and pass the filename as a parameter:

$ less self_taught.txt

>> whatever text you put in your file Press q to exit.

 

Users

Operating systems have different users. A user represents a person in the world— someone using the operating system—and each user has different activities they are allowed to do—called their permissions—as well as their own directories and files that other users can’t access. Users can also be placed into groups, with an entire group given. You can see the name of the user you are on your operating system with the command whoami :

$ whoami >> cory

 

Normally you start as the user you created when you installed your operating system. This user is not the most powerful user the operating system has. The root user is the highest level user, which means it has the highest level of permissions. Every system has a root user. The root user can do an anything: for example, the root user can create or delete other users.

 

For security reasons, you normally do not log in as the root user. Instead, you use a command called sudo in front of another command to temporarily use the power of the root user to issue the command. sudo allows you to do most things as the root user, but not everything. Make sure to be careful using sudo, because using commands with sudo can harm your operating system if you don’t know what you are doing.

 

Permissions

Every directory and file on your computer has a set of permissions. These permissions define what actions a user can perform on them. There are three types of permissions: r , rw and x , which stand for reading, write and execute. Reading a file means viewing it, writing a file means changing it, and executing a file means running it as a program. You can view a file or directory’s permissions with the command ls -lah [name_of_file]. Use the command touch to create a new file called tstp :

$ touch tstp

>> 

Now we can view the files permissions:

$ ls -lah tstp

-rw-r--r-- 1 coryalthoff staff 5B Feb 21 11:55 http://test.py

Our file has three permissions that apply to three different groups of users—represented by - rw-r--r-- . The first set applies to the owner of the file, the second set applies to the group assigned the file and the third set applies to everyone. So in this example, the owner of the file has permission to read and write the file, whereas everyone else can only read the file.

 

You can add and subtract permissions with the command chmod (short for change mode). You can add permission to read with the command chmod +r, permission to read and write with the command chmod +rw, and permission to execute with chmod +x. You can subtract the same permissions with chmod - r, chmod -w and chmod - x, respectively.

 

Bash Programs

If we want to run a bash script from the command line, we need to give the file owner permission to execute. Create a new file called hello_world.sh and type echo Hello, World! in it. The reason we use the .sh extension is to let anyone who sees this file know it is a Bash script.

 

The syntax ./[file_name] is used to execute a file in the directory you are in. You execute a file with /[file_name] and the period means look for the file in the current directory. You could also replace the period with the path to the file. Try executing the file (make sure you are in the same directory as the file):

$ ./hello_world.sh >> Permission denied

 

The reason the console printed permission denied is because we do not have permission to execute the file. We can change that with the chmod command.

$ chmod u+x hello_world.sh $ ./hello_world.sh .

>> Hello, World!

In the example above, we added u to +x to form u+x because u stands for the user, and we only wanted to give ourselves the ability to execute the file. If you are repeating an argument from the previous command line, in this case, the filename, you can use !$ to represent the repeated argument.

 

Hidden Files

Your operating system, and different programs on your computer use hidden files to store data. Hidden files in Unix-like systems are files that by default are not shown to users because changing them can affect the program(s) that depends on them. Hidden files start with a period—for example— .hidden. You can see hidden files using the command ls with the flag -a , which stands for all. Create a hidden file named .self_taught with touch .hidden and test if you can see it with the commands ls and ls - a.

 

Environmental Variables

Your operating system can store and use variables called environmental variables. You can create a new environmental variable from the command line with the syntax export variable_name=[variable_value]. In order to use an environmental variable, you must put a dollar sign in front of the environmental variable’s name. For example:

$ export x=100

$ echo $x >> 100

Creating an environmental variable from the command line is not permanent. If you quit the command line, reopen it, and type echoes $x , the terminal will no longer print 100.

 

We can make the environmental variable x persistent by adding it to a hidden file used by Unix-like operating systems called .profile located in your home directory. Go to your home directory with the command cd ~ (~ is a shortcut for representing your home directory on Unix-like operating systems) and open your .profile file using vim with the command vim .profile. Make sure to enter Normal Mode, type export x=100 into the first line of the file, and exit with: x . Close and reopen your command line, and you should still be able to print the environmental variable you defined:

$ echo $x >> 100

The environmental variable x gets 100 as long as it’s defined in your .profile file.

$PATH

 

When you type a command into the Bash command shell, it looks for the command in all of the directories stored in an environmental variable named $ PATH. $PATH is a string of directory paths separated by colons. The Bash command shell looks in each of these directories for a file matching the name of the command you typed. If the file is found, the command is executed, if not the command shell prints “command not found”. Use echo to print your $PATH environmental variable (your $PATH may look different than mine):

echo $PATH

>> /usr/local/sbin:/user/local/bin:/usr/bin:

...

 

In this example there are three directory paths in $PATH : /usr/local/sbin , /user/local/bin and /usr/bin . The Bash command line shell will be able to execute any command found in these three directories. You can see where a command like grep is installed by passing it as a parameter to the command which :

$ which grep >> /usr/bin/grep

The grep command is located in /usr/bin , one of the locations in my operating system’s $PATH environmental variable.

 

pipes

In Unix-like systems, the character | is known as a pipe. You can use a pipe to use the output of one command as the input for another command. For example, we can pass the output of the ls command as the input of the less command to open less with all of the files in the current directory:

$ ls | less

>> Applications

...

The result is a text file with the output of ls opened up in the program less (press q to quit less ) . You are not limited to piping two commands—you can chain multiple commands together using pipes.

 

cat

You can use the versatile cat command to display the contents of a file and to catenate, which means “to connect in a series.”. Create a new file called hello.txt and add Hello, World! as the first line. Now use the cat command to print the contents of the file:

$ cat hello.txt

>> echo Hello, World!

 

To use the cat command to catenate two files, first create a file called c1.txt and add the text Boy. Then create another file called c2.txt and add the text Meets World. Now we can catenate them by passing both files as parameters to the cat command, followed by the greater than symbol ( > ), and the name of the new file to create:

$ cat c1.txt c2.txt > combined.txt

>> 

Open up the newly created combined.txt which should say Boy Meets World.

 

Recent Commands

You can scroll through your recent commands by pressing the up and down arrows in the command line shell. To see a list of all of your recent commands use the command history :

$ history

>> 1. echo Hello, World!

>> 2. pwd

>> 3. ls

…

Jump Around

When you are typing a command in the terminal, there will be times where you want to edit the command you’ve already typed. Your first instinct will be to use the arrow right or left key to move the cursor to the part you want to change. But this is slow. Instead, you should use shortcuts that will get you there faster.

 

Type echo hello, world! (without pressing Enter) in the terminal and use, esc b to move the cursor back one word, and esc f to move the cursor forward one word. You can also move the cursor to the beginning of the line with control a or the end of the line with control e.

 

Tab Complete

Tab complete is a feature that will help improve the speed you get things done from the command line shell. If you are in the middle of typing a command you and press the tab button on your keyboard, the command line shell will try to autocomplete the command for you.

 

Try it for yourself by typing ech in the command line followed by tab; ech will automatically get turned into echo. You can also use tab to complete file or directory paths. Start typing the path of the directory you are in and finish it off by pressing tab. If you press tab and nothing happens, it is because two commands or paths are named similarly, and the shell doesn’t know which to choose.

 

For example, if you have a directory named the car, and another directory named candy, and you type ca and try to tab complete, nothing will happen because the shell won’t know whether to choose car or candy. If you add an n so you’ve type can, and press tab complete, the shell will autocomplete candy because the shell knows the car is not correct.

 

Wildcard

A wildcard is a character used to match a pattern. Two examples of wildcards are an asterisk and a question mark. The asterisk wildcard matches everything either starting or ending with a pattern, depending if you put it before or after the pattern. Asterisk wildcards are commonly used with the command ls. The command ls *.txt will show any files in the current directory that end with .txt, whereas ls .txt* will show any files that with .txt.

 

A question mark will match any single character. Sols t?o will show any files or directories that match t followed by any character followed by o. If you had directories named two and too, they both would get printed.

 

Other Tools

If your terminal gets cluttered, you can clear it with the command clear. If a process is taking too long, you can kill it with control+c. Another powerful command is grepped, used to search files for patterns.

 

Regular Expressions

quote

A regular expression is a sequence of characters used to look for a pattern in a string. In this blog, we are going to practice using regular expressions from the command line using grep, a command for using regular expressions to search files. We will also learn to use regular expressions in Python.

 

The - c flag in Python executes Python passed in as a string, and import this prints the Zen of Python when executed. Copy and paste the Zen of Python into the file zen.txt. I also recommend reading it as it contains some great wisdom. Use the function exit() to exit Python. If you are using the online bash shell.

If you are using a Mac, set the following environment variables in the terminal:

$ export GREP_OPTIONS='--color=always'

$ export GREP_COLOR='1;35;40'

 

This will make grep highlight the words matched in the terminal, which happens by default on Ubuntu but not on OSX. Remember, setting an environmental variable from the terminal is not permanent, so if you exit the terminal and come back you will have to set the environmental variables again. Add the environmental variables to your .profile file if you want to make the change permanent.

 

Simple Match

The command grep accepts a regular expression and the path to a file to look for the regular expression in as parameters. From the command line, in the directory where you created the file zen.txt, enter the following command:

$ grep Beautiful zen.txt

>> Beautiful is better than ugly.

 

Beautiful is the regular expression and zen.txt is the path to the file to look for the regular expression in. Beautiful is a sequence of characters that match the word Beautiful. This is the simplest kind of regular expression. Your console printed the line Beautiful is better than ugly . with Beautiful highlighted because it is the word the regular expression matched.

 

Ignore Case

If we change our regular expression from Beautiful to beautiful, it will no longer match anything in the Zen of Python. Enter grep beautiful http://zen.py to see for yourself. If we want our regular expression to match the word beautiful regardless of the case (whether or not characters are capitalized), we can use the flag -i :

$ grep -i beautiful zen.txt

>> Beautiful is better than ugly.

Because we added the flag -i to our command, grep ignores case and highlights Beautiful again.

Only Return Matched

grep returns the entire line of the file a match was found on. We can return the exact word matched by using the flag -o :

$ grep -o Beautiful zen.txt >> Beautiful

 

Normally, grep would have returned Beautiful is better than ugly. but because we added the flag - o, only the exact match, Beautiful, gets returned.

 

Match Beginning and End

Regular expressions have certain characters that don’t match themselves but instead do something special. For example, the ^ character is used to look for matches only if they occur at the beginning of a line:

$ grep ^If zen.txt

>> If the implementation is hard to explain, it's a bad idea.

>> If the implementation is easy to explain, it may be a good idea.

Similarly, we can use the dollar sign to only match the lines that end with a pattern:

$ grep idea.$ zen.txt

>> If the implementation is hard to explain, it's a bad idea.

>> If the implementation is easy to explain, it may be a good idea.

 

The lines matched both ends with the idea. The line Namespaces are one honking great idea -- let's do more of those! was ignored because although it includes the word idea, it does not end with the word idea. You can also combine the two anchor matches we’ve covered into the regular expression ^$ to search for empty lines in a file.

 

Match Multiple Characters

You can use brackets in a regular expression to match any of the characters inside the brackets. In this example, instead of matching text from our zen.txt file, we are going to use a pipe to pass in a string to grep :

$ echo Two is a number and too is not. | grep -i t[ow]o >> Two is a number and too is not.

 

Remember, the pipe symbol passes the output of one command as the input of the next. In this case, the output of the echo is passed as the input of grep. The command echo Two is a number and too is not. | grep -i t[ow]o will match both two and two because the regex is looking for at followed by either an o or a w followed by an o .

 

Escaping

What if we want to match one of the special characters we’ve been discussing, like the dollar sign? We can do this by escaping the character. We covered escaping in the blog Manipulating Strings: escaping means prefixing a character with a special character to let the program evaluating the syntax know you want to use the actual character and not the special meaning the character normally has. Escaping in regular expressions is done with a backward slash:

$ echo I love $ | grep \\$

>> I love $

 

Normally, the dollar sign has the special meaning of only matching something at the end of a line, however, because we escaped it, our regex looks for the dollar sign.

 

Regular Expressions in Python

Python has a library called re that lets you use regular expressions in Python programs. The symbols in Python regular expressions are not always the same as grep , but the concept of regular expressions is the same.

#

calthoff/tstp

import re

line = "Match this."

matchObj = re.search( 'this' , line)

if matchObj:

print (matchObj.group())

else :

print ( "No match!" )

>> this

re comes with different methods like search, which returns the first occurrence of the pattern you are looking for. If a match is found, an SRE_Match object is returned, and we can get the match by calling the function group() . If no match is found, re.search() returns None .

We can use the function find() in there module to find every occurrence of a pattern, instead of just the first match.

#

calthoff/tstp import re

line = """The numbers 172 can be found on the back of the U.S. $5 dollar bill in the bushes at the base

of the Lincoln Memorial."""

matchObj = re.findall( '\d+' , line)

if matchObj:

print matchObj

else :

print ( "No match!" )

>> [‘172’, ‘5’]

re.findall() returns a list of all the strings matching the pattern, and an empty list if there is no match. The + symbol matches the preceding character one or more times. If we want to match everything in between two underscores, we can do it with:

#

import re

line = """__yellow__ __red__ and __blue__ are colors"""

matchObj = re.findall( '__.*?__' , line)

if matchObj:

print matchObj

else :

print ( "No match!" )

The two underscores match two underscores, the period matches any character, and the question mark followed by an asterisk means keep matching any character until there is another double underscore.

 

Packages

A package is software “packaged” for distribution—it includes the files that make up the actual program, as well as files with metadata (data about data); such as the software’s name, version number, and dependencies (programs that need to be downloaded in order for it to run properly). Package managers download packages, install them—which means downloading any dependencies the package has.

 

Apt-get

Apt-get is a package manager that comes with Ubuntu. You cannot use apt-get from the online Bash command line shell emulator. You need to have Ubuntu installed so you can use the command sudo. If you do not have Ubuntu installed on your computer, you can skip this section.

You install a package with sudo apt-get install [package_name] . Here is an example of installing a package named aptitude :

$ sudo apt-get install aptitude

>> Do you want to continue? [Y/N] Y

…

>> Processing triggers for libc-bin (2.19-0ubuntu6.7) …

 

Make sure to type Y when prompted with “Do you want to Continue [Y/N]”. The aptitude package should now be installed. You can use it by typing aptitude into the Bash command line shell:

$ aptitude

>> 

This will open up Aptitude, a helpful program that shows information about packages. You should see a list of all the packages installed on your operating system under the option Installed Packages, as well as a list of packages you’ve yet to install, under Not Installed Packages.

You can also list the packages that have been installed with apt-get with the command apt list --installed :

$ apt list --installed >> python3-requests...

 

You can remove packages using aptitude with the syntax apt-get uninstall [package_name]. If you want to remove aptitude from your computer, you can uninstall it with sudo apt-get uninstall aptitude. That’s all there is to it—installing and removing programs is as simple as using two commands with apt-get.

 

Homebrew

Homebrew is a popular package manager for OS X. If you have a Mac, you can install Homebrew from the command line. Go to Homebrew and copy and paste the provided script in the terminal. Once installed, you should see a list of commands when you type brew into your terminal:

$ brew

>> Example usage:

>> brew [info | home | options ] [FORMULA...]

...

We can install packages with Homebrew using the syntax install [package_name] . Use the following command to install a package called calc :

$ brew install calc

...

>> ==> Pouring calc-2.12.5.0.el_capitan.bottle.tar.gz

>> /usr/local/Cellar/calc/2.12.5.0: 518 files, 4.4M

A calculator program called calc is now installed. You can use it by typing calc from the command line (type quit to exit);

$ calc >> 2 + 2 >> 4

The command brew list prints the software you’ve installed using Homebrew:

$ brew list >> calc

You can remove packages using Homebrew with the syntax brew uninstall [package_name] . If you want to remove calc from your computer, you can uninstall it with the command brew uninstall calc. That is all you need to know—you are ready to use Homebrew to manage your packages.

 

OneGet

OneGet is the first package manager to come with Windows: it was first released with Windows Ten. If you do not have Windows Ten, you can download OneGet by following the instructions on its GitHub page: OneGet/oneget. We can install packages on OneGet using the command pip

 

pip

Pip is used to download Python packages. Pip will install a Python package for you, and once installed, you can import the program you downloaded as a module in your Python programs. First, check Pip is installed by going to either the Bash command line shell, or the Command Prompt if you are using Windows (which you can find by searching Command Prompt from the Run Window) and typing pip .

$ pip

>> Usage:

pip <command> [options]

Commands:

install

download

Install packages.

Download packages.

A list of commands you can use with pip should print. Pip comes with Python when you download it, but in earlier versions it didn’t so if nothing happens when you enter pip, google “installing pip with easy_install”.

 

We can use pip install [package_name] to install a new package. You can find all of the Python packages available for download at PyPI – the Python Package Index . There are two ways to specify a package: you can just use the package name, or you can give the package name followed by == and the version number. If you use the package name, the most recent version will get downloaded.

 

Sometimes you don’t want the most recent version, you want a specific version, which is why the second option exists. Here is an example of how we can install a package called Flask, a popular Python package that lets you easily create websites, using a version number:

pip install Flask==0.10.1

>> 

On Unix-like systems you need to use sudo :

sudo pip install Flask==0.10.1

>> 

When the installation is finished, the flask module will be installed in a special folder on your computer called site-packages. Site-packages is automatically included in your Python path, so when Python imports a module, it looks in site-packages to see if it's there.

 

Now, if you write a program, you will be able to import and use the Flask module.

Create a new Python file and add the following code:

from flask import Flask

app = Flask(__name__)

@ app.route ( '/' ) def index ():

return "Hello, World!"

app.run( port = '8000' )

If you go to http://127.0.0.1:8000/ (http://127.0.0.1:8000/) in your web browser, you will see a website that says “Hello, World!”.

pip freeze

>> Flask==0.10.1

…

You can use the syntax pip freeze > [filename] to save names of all the packages you’ve installed with pip to a file. Create a requirements file with:

pip freeze > requirements.txt

>> 

 

Open requirements.txt with a text editor to see the new file.This file is useful because you can use the syntax pip install [requirements_file] to install all the packages listed in a requirements file. This command is useful for quickly downloading the dependencies of a Python program that has not been listed on pypi and thus is not available on pip.

 

Finally, you can uninstall programs you’ve downloaded with pip uninstall [package_name].To uninstall Flask, use the following command:

pip uninstall flask .

…

>> Proceed (y/n)? y

...

Recommend