The REPL
Throughout the class, we're going to do a lot of hands-on, dive-in, figure-it-out-along-the-way work. There's a good chance you'll have a lot of moments when you don't know exactly what's going on, and that's okay! I want to keep your hands on they keyboard, and your mind working hard. If you get stuck, don't worry, I'm here to help.
REPL
As we jump right in, we're going to start with typing code at the Python REPL.
REPL stands for Read-Execute-Print Loop, but don't worry about remembering that. What you should remember is that the Python REPL (sometimes called the Python shell or Python command prompt) is a place where we can do quick and dirty Python-y stuff. It's great for testing things out, and getting familiar with how Python works.
To start the REPL, open up a command/terminal window. In your command/terminal window, type:
$ python3
This will start the REPL. You can tell when you are in the REPL because the prompt will change to be >>>
.
Note
If you're on Windows and python3
doesn't work, try py
.
We can type code in the Python REPL and once we hit Enter
Python will execute our code and print out the result.
Arithmetic
Let's look at some basic math:
>>> 2 + 2
4
Python has numbers and arithmetic, just like every other programming language.
You can add integers. You can add floating point numbers.
>>> 2 + 2
4
>>> 1.4 + 2.25
3.65
You can subtract, multiply, and divide numbers.
>>> 4 - 2
2
>>> 2 * 3
6
>>> 4 / 2
2.0
>>> 0.5 / 2
0.25
Note that division between two integers in Python 3 returns a float.
>>> 3 / 2
1.5
If you want your integers to round-down you can use a double slash:
>>> 3 // 2
1
We can use double asterisks to raise a number to a power. For example, 2 to the tenth power is 1024:
>>> 2 ** 10
1024
REPL Exercises
Let's play around in the REPL. Open a command/terminal window and type python3
.
Quick! What's
4 + 7
?What's the volume of a room that's
8.5
feet long by19.5
feet wide by10
feet tall?What happens if you throw spaces in between the numbers? What happens if you don't?
Do parentheses work the way you'd expect?
A "googol" is
10
raised to the power100
. Can Python compute that? Try it out!A "googolplex" is
10
raised to the power of one googol. Can you compute that with Python? (Hint: put parentheses around the expression you just typed)
Bonus: Text
Can you figure out what
%
does?What if we just want to print text in the REPL? Can you figure out how to do that?