Getting Started with Python#

Programs are made of instructions called statements. In this lecutre you’ll learn your first Python statements and how to use the Jupyter Notebook to experiment with and run programs. Instructions perform an action on inputs and produce a result. In the example below print is the action and the words Hello World are the input to the function.

Copy this code into the cell below:

print("Hello World") 

Execute the cell by pressing Ctrl-Enter or clicking the “Play” button above:

Cells can be edited. Edit the cell above to change “Hello World” to your name and re-run the cell. If you’re just learning to program it’s important to see how the action and the input relate to one and other. The statement begins with the action and the input is in parentheses ( and ). Statements are run one at a time, from top to bottom. The first statement of a program is always on the first line, just like the first word of a book. The program below performs the print action multiple times with different input.

print("Roses are red")
print("Violets are blue")

Add print instructions to the cell above to complete the poem. Do you see how they are executed in order?

Comments#

A comment is a part of a program that’s ignored by Python. Comments are meant for the humans. Comments explain what code is doing to someone who is trying to read it. Comments make code more clear and easy to read. Comments begin with the hash # character. Here’s an example:

# The next line prints "Hello World" 
print("Hello World")

Copy the code into this cell:

Notice that the comment is a different color! Try placing the # before the print function an re-running the cell. What happens when you comment out the print statement? If you’re just getting started with programming put a comment before every line of code that explains what the next line does. The commens will help you remember instructions.

Expressions#

In Python (and all other programming languages) an expression is a way to convey a value. A value can be a number, words or anything that can be stored in the computer’s memory. Here are some examples of values:

5  
5.5 
"Hello World"

More complex expressions are created by performing operations on values, like addition and subtraction. We’ll learn more about operations in the Operators lesson. Here are examples of expressions that perform operations:

5 + 10 
"Hello" + "World"
100 + 1 / 2 

The Jupyter Notebook automatically displays the value of an expression if it’s the last line of a cell. In the cell below try typing in each of the expressions that you see in this section and execute them:

Statements#

A statement performs an action most often but not always by using a function. A function is like the verb in a sentence, it describes the action that will be taken. The print function displays a value. The output appears just below the code cell. Here are examples of how to take the expressions from the previous section and make them into statements using print:

print(5)
print(5.5)
print("Hello World")
print(5 + 10)
print("Hello" + "World")
print(100 + 1 / 2)

In most lectures you’ll learn new functions and even write your own. Use the next cell to enter in the print statements:

Notice how the output of each print statements appears below the code cell, not just the last one like an expression.

Functions#

Functions are parts of parts of a program that take input called arguments, do some computation and produce outputs called return values. The arguments to a function are surrounded by parenthesis –( and )– and separated by commas (,). Functions can have any number of arguments, including none at all. Functions are statements that are also expressions because executing a function results in a value (the return value). The return value can be used the same way as any other value.

The len function returns the length of its argument. If the argument is "Hello World" it returns 11, which is the number of letters in “Hello World” plus one for the space. Here’s an example of how the len function performs an action that results in a value:

print(len("Hello World"))

Enter the example code in the next cell:

Functions like len and print stand on their own. But, most functions are class functions. Class functions use the dot (.) to identify the subject of the function. You can think of a class function as making a sentence in English in the form of subject, verb, predicate. Here’s an example of a class function:

"i'm not shouting".upper()

You can read this statement as, Take the letters in, “i’m not shouting,” and convert them to upper case.

Here’s another example of a class function. This one takes argument:

"i'm not shouting".replace('not', 'really')

This statement can be read as, Take the string, “i’m not shouting,” and replace “not” with “really”.

One of the great things about class functions is that they can sometimes be chained together to make for compact but readable code. Here’s how to combine the last two class functions into one statement:

"i'm not shouting".replace('not', 'really').upper()

Try typing the example code into the next cell:

Compound Statements#

Later in the course we’ll learn that some statements can contain other statements. These are known as compound statements. For now here’s an example of a compound statement that prints a different greeting at different times of day.

from datetime import datetime 

# Get the current clock time.
now = datetime.now()  

# Compound statement: Decide what to say based on the current time
if now.hour < 12:
    print("Good morning.")
elif now.hour < 5:
    print("Good afternoon.")
else:
    print("Good evening.")

Import Statements#

There is a core set of Python functions that are always available, including the print function. To use the full power of Python, programs access add-on functions inside of packages. Anyone can create a Python package and make it available for other people to use. Jupyter, for example, is a Python package. The import statement makes functions in a package available to your program. This statement imports the p4e.drawing package and makes Turtle available to the notebook.

from p4e.drawing import Turtle

Copy and run the statement.

Once you import a package it’s available as long this notebook is open or until you restart the kernel. If you close and open the notebook again you have to re-run the import statement. Now that we have a turtle available we can create a new Turtle and show it on the screen.

# Create a new Turtle named tu
tu = Turtle()
# Show the turtle.
display(tu)

Let’s drive the turtle around. The turtle has it’s own functions. Here are a few to get started:

tu.draw(100)  # Move forward 100 pixels 
tu.turn(90)   # Turn left 90 degrees 
tu.clear()    # Clear the arena and go back to the middle 

Code, Run, Debug#

No one ever types a program perfectly on the first try. No one. Ever. After typing all of the code run the program to see if it works. It can be discouraging when a program that seems right doesn’t work for some reason. Please remember that being a master programmer means having made every mistake so many times that you can quickly spot problems. If you’re just beginning you are building that experience and it can be frustrating.

Run the program in the next cell. It has a bug!

from p4e.drawing import Turtle 
tu = Turtle()
display(tu)

# Draw a square 
tu.draw(100)
tu.turn(90)
tu.draw(100)
tu.turn(80)
tu.draw(100)
tu.turn(90)
tu.draw(100)

You might be able to spot the bug in the previous cell but not all bugs are easy to spot. The debugger is an essential tool to help you understand what your program is really doing. Look in the upper right corner of this tab and you’ll see a bug icon with a little switch next to it. Turn the switch on. Did you notice a change in the cell above? The change is subtle, but when the switch is on there’s a little more space on the left margin. Click to the left of the number “1” and a red dot appears. In class I show you how to use the “Next” button in the debugger to step through your program one statement at a time. When you become skilled as a programmer you will be able to this process in your head.