2  The Basics

In This Chapter

In the last chapter, you learned how to talk to the computer using the interactive shell. But the moment you close IDLE, the computer forgets everything you typed. To make a real program, you need a way to save your instructions. In this chapter, we will cover:

  • Variables and Memory: How Python actually stores data and remembers values.
  • String Literals: Teaching the computer how to read text.
  • The File Editor: Writing and saving permanent scripts.
  • Input and Output: Using print() and input() to talk to the user.
  • String Concatenation: Gluing text and variables together into sentences.
  • Code Comments: Leaving notes for your future self.

2.1 Variables and Computer Memory

When an expression evaluates to a value, you can use that value later by storing it in a Variable. A variable is a way to keep a reference to a piece of data you want to reuse.

We are going to use a Memory Model. This model will let you accurately predict exactly what the computer is doing behind the scenes.

Python stores every value in memory as an Object. Think of computer memory like a giant warehouse. Every time Python evaluates a value, it builds a container in that warehouse called an object. Every object has three things:

  1. A Type (like integer, float, or string).
  2. A Value (like 100 or 26.0 or "Dave").
  3. A Memory Address, which is exactly like a street address so the computer can find it later. We will call these addresses addr1, addr2, addr3, etc.

So, what is a variable? A variable simply contains a memory address. It acts like a name tag or a directional arrow pointing to a specific object in the warehouse.

The Assignment Statement

An assignment statement is how you tell Python to create these objects and attach variables to them. You type a name for the variable, followed by the equal sign (=), and then the expression.

In programming, the = sign does not mean “equals” like it does in math; it is the Assignment Operator. Let’s look at its general form:

variable = expression

The left side of the equal sign is called the LHS (Left-Hand Side). The right side is called the RHS (Right-Hand Side). Python always executes assignment statements in two strict steps:

  1. Evaluate the RHS: Python solves the expression on the right to produce a single value. It stores this value as an object in memory at a specific address (like addr1).
  2. Store the Address in the LHS: Python takes the variable name on the left and tells it to point to that new memory address.

Enter the following into your interactive shell:

>>> player_health = 100

When you press ENTER, you won’t see anything happen. But behind the scenes, Python followed our two steps perfectly:

  1. It evaluated the RHS (100) and created an integer object in memory at address addr1.
  2. It told the LHS variable player_health to store address addr1.
Figure 2.1: Variables are like name tags or sticky notes attached to values in the computer’s memory. The variable doesn’t hold the value 100, it only hold the address to where the value is stored.

Whenever Python needs to know what player_health is, it follows the arrow to addr1 and finds the value 100.

>>> player_health
100

Reassigning Variables

What happens if you change a variable later? This is where the memory model becomes incredibly useful. Consider this code:

>>> bonus_points = 25
>>> score = 2 * bonus_points
>>> score
50
>>> bonus_points = 30
>>> score
50

Many beginners look at this and get confused. If bonus_points was changed to 30, shouldn’t score automatically change to 60? No. Let’s trace the execution using our memory model to see exactly why!

Step 1: bonus_points = 25

  • RHS: Python evaluates 25, creating an object at address addr1.
  • LHS: The bonus_points variable is told to point to addr1.

Step 2: score = 2 * bonus_points

  • RHS: Python evaluates the math. It follows the bonus_points arrow to find 25. It multiplies 2 * 25 to get 50. It creates a brand new object in memory for 50 at address addr2.
  • LHS: The score variable is told to point to addr2.
Figure 2.2: Two different variables are pointing to two different addresses in memory. Each address holds its own data object.

Step 3: bonus_points = 30

  • RHS: Python evaluates 30, creating a new object at address addr3.
  • LHS: The bonus_points variable is updated. Its arrow is erased from addr1 and redrawn to point to addr3.
Figure 2.3: Two different variables are pointing to two different addresses in memory. Each address holds its own data object.

As you can see in your mind’s eye, changing where bonus_points points has absolutely no effect on where score points. A variable only holds the memory address of the value it was assigned at that exact moment in time!

Updating a Variable Using Itself

Because of this two-step process, you can even use a variable on both sides of an assignment statement! This is how we update scores or health in a game.

>>> score = 10
>>> score = score + 5
>>> score
15

Let’s trace score = score + 5 using our rules:

  1. Evaluate the RHS: Python looks at score + 5. It follows the current score arrow to find 10. It adds 10 + 5 to get 15. It creates a new object in memory for 15 at address addr2.
  2. Store the Address in the LHS: Python updates the score variable so it stops pointing at the old 10 and points to the new 15 at address addr2.

Rules for Naming Variables

You can create as many variables as you need, but Python has three strict rules for naming them. If you break these rules, your program will crash with a SyntaxError:

  1. No spaces allowed. You cannot name a variable player health. Instead, programmers use an underscore (_) to represent a space: player_health.
  2. Cannot start with a number. A variable can be named player1, but it can never be named 1st_player.
  3. No special symbols. You cannot use symbols like !, @, -, or $ in your variable names. Only letters, numbers, and underscores are allowed.

Finally, variable names are case-sensitive. To the computer, Score, SCORE, and score are three completely different variables! It is a common practice in Python to keep all your variable names entirely lowercase so you don’t accidentally mix them up.

A good variable name describes the data it is attached to. Give your variables descriptive names like gold_coins rather than just g2897.

2.2 String Literals: How Computers See Text

Humans intuitively know the difference between a word and a number. If I show you the word “Apple” and the number “5”, you know you can eat one and count with the other. Computers don’t have this intuition.

If you want the computer to store text in a variable, you have to explicitly signal to the computer that you are typing words. In Python, text is called a String.

To create a string, you must surround your text with quote marks (" or '). Type this into the shell:

>>> greeting = "Hello, computer!"
>>> greeting
'Hello, computer!'

The quotes are a strict signal. They create a String Literal. They tell the computer: “Treat everything inside these quotes exactly as written, and do not try to do math with it or treat it like a variable name.”

You can use single quotes (') or double quotes ("), but they must match. You cannot start a string with a double quote and end it with a single quote.

Sometimes, though, the text you want to store itself contains a quote mark. Imagine you want to write the sentence I'm learning Python. If you try to wrap the whole string in single quotes, Python gets confused:

>>> message = 'I'm learning Python'

The apostrophe in I'm looks like the end of the string, so Python thinks the string ended too early. This is why we need to be careful when writing text that contains quotes.

There are two common ways to avoid the problem:

  1. Use double quotes around the outside of the string:
>>> message = "I'm learning Python"
>>> print(message)
I'm learning Python
  1. Escape the quote inside the string by putting a backslash before it:
>>> message = 'I\'m learning Python'
>>> print(message)
I'm learning Python

The backslash tells Python to treat the next character as part of the string, instead of as the end of the string. This is called escaping. Escaping is useful whenever you want to include a quote mark inside a string, and it can also help with other special characters.

String Math: Concatenation and Repetition

What happens if you try to do math with a string?

>>> "Bat" + "man"
'Batman'
>>> "John" + " " + "Smith"
'John Smith'

When you use the + operator with strings, it does not do math. Instead, it glues the pieces of text together into a single, longer string. This is called String Concatenation, and it is incredibly useful!

You can also use the multiplication operator (*) on strings! If you multiply a string by an integer, Python will repeat that string over and over.

>>> "Ha" * 3
'HaHaHa'

2.3 Making the Computer Talk: print()

In the interactive shell, typing 2 + 2 immediately spit out 4. In a saved script, the computer does math silently. If you want the computer to actually show you the answer, you have to explicitly command it to print the result to the screen.

To do this, we use the print() function. A function is like a mini-program built into Python that does a specific job. The job of print() is to display whatever you put inside its parentheses.

Type this into your new File Editor window:

print("Hello, world!")
print("I am a Python program.")

user_name = "Arthur"
print(user_name)

Now, let’s run it. Go to the top menu of your File Editor and click Run -> Run Module (or just press the F5 key). IDLE will ask you to save the file. Save it as hello.py in a folder where you can easily find it.

Once you save it, watch your Interactive Shell window. You should see:

Hello, world!
I am a Python program.
Arthur

Notice that print("Hello, world!") printed the exact text because of the quote marks, but print(user_name) looked up the value that the variable was attached to and printed the text stored inside it!

2.4 Making the Computer Listen: input()

A program isn’t very useful if the user can’t interact with it. We need a way to ask the user questions and wait for their answers. We do this using the input() function.

The input() function does two things:

  1. It prints a message to the screen (usually a question).
  2. It pauses the entire program and waits for the user to type something and press ENTER.

When the user types their answer, you must catch it and attach a variable to it, otherwise, the computer will instantly forget it.

Delete the code in your File Editor and try this:

hero_name = input("Brave adventurer, what is your name? ")
print("Welcome to the castle, " + hero_name + "!")

Run this (F5). The shell will ask the question and wait. If you type “Arthur” and hit ENTER, the string "Arthur" is stored and the hero_name variable is attached to it. Then, line 2 uses String Concatenation to glue the greeting, the variable, and the exclamation point together into one sentence! If you type "Arthur", the computer evaluates "Welcome to the castle, " + "Arthur" + "!" and prints: Welcome to the castle, Arthur!

Note: Don’t forget to put a space inside the quotes after the comma, otherwise it will print castle,Arthur!

2.5 Leaving Notes: Code Comments

Code is for computers, but comments are for humans. Whenever Python sees a hashtag (#), it completely ignores everything else on that line. Comments are often alone on their line but they can also be at the end of the line after other code.

# this is a comment
name = "Bob" # this is also a comment

As a programmer, you will often write code, go to sleep, and wake up the next day with absolutely no memory of how your code works. Get in the habit of leaving comments above your code to explain why you wrote it.

2.6 Saving and Running Scripts

The IDLE Interactive Shell is a great sandbox for testing single lines of code, but it is not how real programs are made. Real programs are written in a text document, saved as a file, and then handed to the computer to read all at once.

When you write a list of instructions in a file, it is called a Script.

To write a script, we need to open IDLE’s File Editor. Go to the top menu in IDLE and click File -> New File. A new, blank window will pop up. This is your editor.

Figure 2.4: To write Python script we can save and run, we need to open the File Editor.

When you write code in this window, the computer will not respond immediately when you hit ENTER. Instead, it will wait until you save the file and tell it to run. When you do, the computer will execute your code using Top-to-Bottom Execution. It will read line 1, do what it says, then move to line 2, and so on, until it reaches the bottom of the file.

You can run your script file from in the IDLE file editor by clicking Run -> Run Module in the top menu or by pressing the F5 key. If you have not already saved it you will be asked to save. Then it will open a new window with the output.

2.7 The Project: The Mad Libs Generator

You now have all the tools required to build your first real application! We are going to build a simple Mad Libs generator using variables, input(), and string concatenation. The program will ask the user for a few random words and then print out a ridiculous story.

Open a new file and save it as madlibs.py. Then type the following code into your editor:

# A simple Mad Libs generator

print("Welcome to the Mad Libs Generator!")
print("Please answer the following questions...")

# Get words from the user and store them in variables
adjective1 = input("Give me an adjective: ")
animal = input("Give me an animal: ")
verb = input("Give me a verb (ending in 'ing'): ")
place = input("Give me a place: ")
adjective2 = input("Give me another adjective: ")

# Print the final story by gluing the strings and variables together!
print("\n--- YOUR STORY ---")
print("One day, I was walking to " + place + ".")
print("Suddenly, I saw a " + adjective1 + " " + animal + "!")
print("It was " + verb + " right toward me!")
print("I was so " + adjective2 + ", I ran all the way home!")

Note: The \n inside the print statement is a special trick that creates a blank new line, making your output look cleaner!

Run the module and play your very first program! Here is an example of what the output might look like:

--- YOUR STORY ---
One day, I was walking to Mt. Fuji.
Suddenly, I saw a cosmic earthworm!
It was cooking right toward me!
I was so slimey, I ran all the way home!

As you write more scripts and save more files it becomes important to organize your files well. For this course you should have a folder on your computer to save your projects in and consider making multiple folders inside for each chapter or project.


Challenges

Now it is time to experiment. Try to complete these challenges on your own.

Challenge 1: The Broken Greeting

A fellow programmer tried to write a script that asks for a player’s name and prints a welcome message. However, their code is crashing! Look at the code below, figure out what they did wrong, and rewrite it so it works perfectly.

# Broken Code!
print("Welcome to the game!")
player_name = input("What is your name? ")
print("It is nice to meet you, " + playername)

Challenge 2: More Mad Libs

Now that you can build a basic Mad Libs generator, try adding more questions to make the story even more interesting! Write a longer story with more blanks to fill in. You will have to ask the user for more words and glue them all together.