Interactive Media
Interactive Media
Expressions
The math problem 2 + 2 is an example of an expression. As Figure 1-2 shows, expressions are made up of
values (the numbers) connected by operators (the math signs) that produce a new value the code can use.
Computers can solve millions of expressions in seconds.
Evaluating Expressions
When a computer solves the expression 10 + 5 and returns the value 15, it has evaluated the expression.
Evaluating an expression reduces the expression to a single value, just like solving a math problem
reduces the problem to a single number: the answer. For example, the expressions 10 + 5 and 10 + 3 +
2 both evaluate to 15.
When Python evaluates an expression, it follows an order of operations just like you do when you do
math. There are just a few rules:
FUNCTIONS
- Random integer/ randint
- Print
- Input
- String/ str
- Integer/ int
- Float
The step where Python is currently working in the program is called the execution. When the program
starts, the execution is at the first instruction. After executing the instruction, Python moves down to the
next instruction.
Any text following a hash mark (#) is a comment. Comments are the programmer’s notes about what the
code does; they are not written for Python but for you, the programmer. Python ignores comments when it
runs a program. Programmers usually put a comment at the top of their code to give their program a title.
Naming Variables
Variable names are case sensitive, which means the same variable name in a different case is considered a
different variable.
Capitalizing your variables this way is called camel case (because it resembles the humps on a camel’s
back), and it makes your code more readable.
Flow Control Statement
- For, if, else, break
- Changes the flow of the program execution as it moves around your program.
- Always has a colon (:) after the condition. Statements that end with a colon expect a new block
on the next line.
- The if, for, and break statements are flow control statements that can make the execution skip
instructions, loop over instructions, or break out of loops. Function calls also change the flow of
execution by jumping to the instructions inside of a function.
Boolean Data type
- Has two values; true or false
- Boolean values must be entered with an uppercase T or F and the rest of the values name in
lowercase.
Comparison Operators
< less than
>greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to
Escape Characters
Escape character What is actually printed
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\n Newline
\t Tab
DRAGON REALM
In this game, the player is in a land full of dragons. The dragons all live in caves with their large piles of
collected treasure. Some dragons are friendly and share their treasure. Other dragons are hungry and eat
anyone who enters their cave. The player approaches two caves, one with a friendly dragon and the other
with a hungry dragon, but doesn’t know which dragon is in which cave. The player must choose between
the two.
The def statement defines a new function (in this case, the displayIntro() function), which you can
call later in the program.
Multiline Strings
So far, all of the strings in our print() function calls have been on one line and have had one quote
character at the start and end. However, if you use three quotes at the start and end of a string, then it can
go across several lines. These are multiline strings.
The or Operator
The or operator is similar to the and operator, except it evaluates to True if either of the two Boolean
values is True. The only time the or operator evaluates to False is if both of the Boolean values are False.
Function Parameters
Notice the text chosenCave between the parentheses. This is a parameter: a local variable that is used
by the function’s code. When the function is called, the call’s arguments are the values assigned to the
parameters.
The len() function returns an integer indicating how many characters are in the string passed to it. In this
case, it tells us that the string 'Hello' has 5 characters.
The time module has a function called sleep() that pauses the program.
These short pauses add suspense to the game instead of displaying the text all at once.
Types of Bugs
Syntax errors This type of bug comes from typos. When the Python interpreter sees a syntax error,
it’s because your code isn’t written in proper Python language. A Python program with even a single
syntax error won’t run.
Runtime errors These are bugs that happen while the program is running. The program will work
up until it reaches the line of code with the error, and then the program will terminate with an error
message (this is called crashing). The Python interpreter will display a traceback: an error message
showing the line containing the problem.
Semantic errors These bugs—which are the trickiest to fix—don’t crash the program, but they
prevent the program from doing what the programmer intended it to do. For example, if the
programmer wants the variable total to be the sum of the values in variables a, b, and c but
writes total = a * b * c, then the value in total will be wrong. This could crash the program later on,
but it won’t be immediately obvious where the semantic bug happened.
The Debugger
It can be hard to figure out the source of a bug because the lines of code are executed quickly and the
values in variables change so often. A debugger is a program that lets you step through your code one line
at a time in the same order that Python executes each instruction. The debugger also shows you what
values are stored in variables at each step.
Globals Area
The Globals area in the Debug Control window is where all the global variables are displayed.
Remember, global variables are variables created outside of any functions (that is, in the global scope).
Locals Area
In addition to the Globals area, there is a Locals area, which shows you the local scope variables and their
values. The Locals area will contain variables only when the program execution is inside of a function.
When the execution is in the global scope, this area is blank.
If you get tired of clicking the Step button repeatedly and just want the program to run normally, click the
Go button at the top of the Debug Control window. This will tell the program to run normally instead of
stepping.
Go Executes the rest of the code as normal, or until it reaches a breakpoint (see “Setting
Breakpoints” on page 73).
Step Executes one instruction or one step. If the line is a function call, the debugger will step into
the function.
Over Executes one instruction or one step. If the line is a function call, the debugger won’t step
into the function but instead will step over the call.
Out Keeps stepping over lines of code until the debugger leaves the function it was in when Out was
clicked. This steps out of the function.
Quit Immediately terminates the program.
HANGMAN
Hangman is a game for two people in which one player thinks of a word and then draws a blank line on
the page for each letter in the word. The second player then tries to guess letters that might be in the word.
If the second player guesses the letter correctly, the first player writes the letter in the proper blank.
But if the second player guesses incorrectly, the first player draws a single body part of a hanging man.
The second player has to guess all the letters in the word before the hanging man is completely drawn to
win the game.
List Concatenation
You can join several lists into one list using the + operator, just as you can with strings. Doing so is
called list concatenation.
The in Operator
The in operator can tell you whether a value is in a list or not. Expressions that use the in operator
return a Boolean value: True if the value is in the list and False if it isn’t.
Calling Methods
A method is a function attached to a value. To call a method, you must attach it to a specific value using a
period. Python has many useful methods, and we’ll use some of them in the Hangman program.
missedLetters A string of the letters the player has guessed that are not in the secret word
correctLetters A string of the letters the player has guessed that are in the secret word
secretWord A string of the secret word that the player is trying to guess
The getGuess() function will be called so that the player can enter a letter to guess. The function returns
the letter the player guessed as a string. Further, getGuess() will make sure that the player types a valid
letter before it returns from the function.
elif Statements
The next part of the Hangman program uses elif statements. You can think of elif or “else-if” statements
as saying, “If this is true, do this. Or else if this next condition is true, do that. Or else if none of them is
true, do this last thing.”
The values between the curly brackets are key-value pairs. The keys are on the left of the colon and
the key’s values are on the right. You can access the values like items in lists by using the key. To see an
example, enter the following into the interactive shell:
>>> spam = {'hello':'Hello there, how are you?', 4:'bacon', 'eggs':9999}
>>> spam['hello']
'Hello there, how are you?'
>>> spam[4]
'bacon'
>>> spam['eggs']
9999
The choice() function in the random module takes a list argument and returns a random value from it.
This is similar to what the previous getRandomWord() function did. You’ll use choice() in the new
version of the getRandomWord() function.
>>> import random
>>> random.choice(['cat', 'dog', 'mouse'])
'mouse'
>>> random.choice(['cat', 'dog', 'mouse'])
'cat'
A del statement will delete an item at a certain index from a list. Because del is a statement, not a function
or an operator, it doesn’t have parentheses or evaluate to a return value.
Multiple Assignment
Multiple assignment is a shortcut to assign multiple variables in one line of code. To use multiple
assignment, separate your variables with commas and assign them to a list of values.
TICTACTOE
This chapter features a Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people. One player
is X and the other player is O. Players take turns placing their X or O. If a player gets three of their marks
on the board in a row, column, or diagonal, they win. When the board fills up with neither player
winning, the game ends in a draw.
The None value represents the lack of a value. None is the only value of the data type NoneType. You
might use the None value when you need a value that means “does not exist” or “none of the above.”
THE BAGELS DEDUCTION GAME
Bagels is a deduction game in which the player tries to guess a random three-digit number (with no
repeating digits) generated by the computer. After each guess, the computer gives the player three types
of clues:
String Interpolation
String interpolation, also known as string formatting, is a coding shortcut. Normally, if you want to use
the string values inside variables in another string, you have to use the + concatenation operator:
>>> name = 'Alice'
>>> event = 'party'
>>> location = 'the pool'
>>> day = 'Saturday'
>>> time = '6:00pm'
>>> print('Hello, ' + name + '. Will you go to the ' + event + ' at ' +
location + ' this ' + day + ' at ' + time + '?')
Hello, Alice. Will you go to the party at the pool this Saturday at 6:00pm?
Because this program manipulates text to convert it into secret messages, you’ll learn several new
functions and methods for manipulating strings. You’ll also learn how programs can do math with text
strings just as they can with numbers.
The science of writing secret codes is called cryptography. For thousands of years, cryptography has
made it possible to send secret messages that only the sender and recipient could read, even if someone
captured the messenger and read the coded message. A secret code system is called a cipher. The cipher
used by the program in this chapter is called the Caesar cipher.