CH 1
CH 1
P y t h o n B as i cs
>>> 2 + 2
4
The IDLE window should now show some text like this:
>>> 2
2
E rrors A re Ok ay !
Programs will crash if they contain code the computer can’t understand, which
will cause Python to show an error message. An error message won’t break
your computer, though, so don’t be afraid to make mistakes. A crash just means
the program stopped running unexpectedly.
If you want to know more about an error message, you can search for the
exact message text online to find out more about that specific error. You can
also check out the resources at http://nostarch.com/automatestuff/ to see a list
of common Python error messages and their meanings.
14 Chapter 1
There are plenty of other operators you can use in Python expressions,
too. For example, Table 1-1 lists all the math operators in Python.
>>> 2 + 3 * 6
20
>>> (2 + 3) * 6
30
>>> 48565878 * 578453
28093077826734
>>> 2 ** 8
256
>>> 23 / 7
3.2857142857142856
>>> 23 // 7
3
>>> 23 % 7
2
>>> 2 + 2
4
>>> (5 - 1) * ((7 + 1) / (3 - 1))
16.0
In each case, you as the programmer must enter the expression, but
Python does the hard part of evaluating it down to a single value. Python
will keep evaluating parts of the expression until it becomes a single value,
as shown in Figure 1-1.
Python Basics 15
(5 - 1) * ((7 + 1) / (3 - 1))
4 * ((7 + 1) / (3 - 1))
4 * ( 8 ) / (3 - 1))
4 * ( 8 ) / ( 2 )
4 * 4.0
16.0
These rules for putting operators and values together to form expres-
sions are a fundamental part of Python as a programming language, just
like the grammar rules that help us communicate. Here’s an example:
This is a grammatically correct English sentence.
This grammatically is sentence not English correct a.
The second line is difficult to parse because it doesn’t follow the rules
of English. Similarly, if you type in a bad Python instruction, Python won’t
be able to understand it and will display a SyntaxError error message, as
shown here:
>>> 5 +
File "<stdin>", line 1
5 +
^
SyntaxError: invalid syntax
>>> 42 + 5 + * 2
File "<stdin>", line 1
42 + 5 + * 2
^
SyntaxError: invalid syntax
You can always test to see whether an instruction works by typing it into
the interactive shell. Don’t worry about breaking the computer: The worst
thing that could happen is that Python responds with an error message.
Professional software developers get error messages while writing code all
the time.
16 Chapter 1
common data types in Python are listed in Table 1-2. The values -2 and 30,
for example, are said to be integer values. The integer (or int) data type indi-
cates values that are whole numbers. Numbers with a decimal point, such as
3.14, are called floating-point numbers (or floats). Note that even though the
value 42 is an integer, the value 42.0 would be a floating-point number.
Python programs can also have text values called strings, or strs (pro-
nounced “stirs”). Always surround your string in single quote (') characters
(as in 'Hello' or 'Goodbye cruel world!') so Python knows where the string
begins and ends. You can even have a string with no characters in it, '',
called a blank string. Strings are explained in greater detail in Chapter 4.
If you ever see the error message SyntaxError: EOL while scanning string
literal, you probably forgot the final single quote character at the end of
the string, such as in this example:
The expression evaluates down to a single, new string value that com-
bines the text of the two strings. However, if you try to use the + operator on
a string and an integer value, Python will not know how to handle this, and
it will display an error message.
>>> 'Alice' + 42
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
'Alice' + 42
TypeError: Can't convert 'int' object to str implicitly
Python Basics 17
The error message Can't convert 'int' object to str implicitly means
that Python thought you were trying to concatenate an integer to the string
'Alice'. Your code will have to explicitly convert the integer to a string,
because Python cannot do this automatically. (Converting data types will
be explained in “Dissecting Your Program” on page 22 when talking
about the str(), int(), and float() functions.)
The * operator is used for multiplication when it operates on two inte-
ger or floating-point values. But when the * operator is used on one string
value and one integer value, it becomes the string replication operator. Enter
a string multiplied by a number into the interactive shell to see this in action.
>>> 'Alice' * 5
'AliceAliceAliceAliceAlice'
The expression evaluates down to a single string value that repeats the
original a number of times equal to the integer value. String replication is a
useful trick, but it’s not used as often as string concatenation.
The * operator can be used with only two numeric values (for multipli-
cation) or one string value and one integer value (for string replication).
Otherwise, Python will just display an error message.
Assignment Statements
You’ll store values in variables with an assignment statement. An assignment
statement consists of a variable name, an equal sign (called the assignment
operator), and the value to be stored. If you enter the assignment statement
spam = 42, then a variable named spam will have the integer value 42 stored in it.
18 Chapter 1
Think of a variable as a labeled box that a value is placed in, as in
Figure 1-2.
u >>> spam = 40
>>> spam
40
>>> eggs = 2
v >>> spam + eggs
42
>>> spam + eggs + spam
82
w >>> spam = spam + 2
>>> spam
42
Just like the box in Figure 1-3, the spam variable in this example stores
'Hello' until you replace it with 'Goodbye'.
Python Basics 19
Figure 1-3: When a new value is assigned to a variable,
the old one is forgotten.
Variable Names
Table 1-3 has examples of legal variable names. You can name a variable
anything as long as it obeys the following three rules:
20 Chapter 1
Variable names are case-sensitive, meaning that spam, SPAM, Spam, and sPaM
are four different variables. It is a Python convention to start your variables
with a lowercase letter.
This book uses camelcase for variable names instead of underscores;
that is, variables lookLikeThis instead of looking_like_this. Some experienced
programmers may point out that the official Python code style, PEP 8, says
that underscores should be used. I unapologetically prefer camelcase and
point to “A Foolish Consistency Is the Hobgoblin of Little Minds” in PEP 8
itself:
“Consistency with the style guide is important. But most impor-
tantly: know when to be inconsistent—sometimes the style guide
just doesn’t apply. When in doubt, use your best judgment.”
A good variable name describes the data it contains. Imagine that you
moved to a new house and labeled all of your moving boxes as Stuff. You’d
never find anything! The variable names spam, eggs, and bacon are used as
generic names for the examples in this book and in much of Python’s docu-
mentation (inspired by the Monty Python “Spam” sketch), but in your pro-
grams, a descriptive name will help make your code more readable.
Now it’s time to create your first program! When the file editor window
opens, type the following into it:
v print('Hello world!')
print('What is your name?') # ask for their name
w myName = input()
x print('It is good to meet you, ' + myName)
y print('The length of your name is:')
print(len(myName))
Python Basics 21
z print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
Once you’ve entered your source code, save it so that you won’t have
to retype it each time you start IDLE. From the menu at the top of the file
editor window, select File4Save As. In the Save As window, enter hello.py
in the File Name field and then click Save.
You should save your programs every once in a while as you type them.
That way, if the computer crashes or you accidentally exit from IDLE, you
won’t lose the code. As a shortcut, you can press ctrl-S on Windows and
Linux or z-S on OS X to save your file.
Once you’ve saved, let’s run our program. Select Run4Run Module
or just press the F5 key. Your program should run in the interactive shell
window that appeared when you first started IDLE. Remember, you have
to press F5 from the file editor window, not the interactive shell window.
Enter your name when your program asks for it. The program’s output in
the interactive shell should look something like this:
When there are no more lines of code to execute, the Python program
terminates; that is, it stops running. (You can also say that the Python pro-
gram exits.)
You can close the file editor by clicking the X at the top of the window.
To reload a saved program, select File4 Open from the menu. Do that now,
and in the window that appears, choose hello.py, and click the Open button.
Your previously saved hello.py program should open in the file editor window.
22 Chapter 1
Comments
The following line is called a comment.
Python ignores comments, and you can use them to write notes or
remind yourself what the code is trying to do. Any text for the rest of the
line following a hash mark (#) is part of a comment.
Sometimes, programmers will put a # in front of a line of code to tem-
porarily remove it while testing a program. This is called commenting out
code, and it can be useful when you’re trying to figure out why a program
doesn’t work. You can remove the # later when you are ready to put the line
back in.
Python also ignores the blank line after the comment. You can add as
many blank lines to your program as you want. This can make your code
easier to read, like paragraphs in a book.
v print('Hello world!')
print('What is your name?') # ask for their name
The line print('Hello world!') means “Print out the text in the string
'Hello world!'.” When Python executes this line, you say that Python is
calling the print() function and the string value is being passed to the func-
tion. A value that is passed to a function call is an argument. Notice that
the quotes are not printed to the screen. They just mark where the string
begins and ends; they are not part of the string value.
Note You can also use this function to put a blank line on the screen; just call print() with
nothing in between the parentheses.
w myName = input()
This function call evaluates to a string equal to the user’s text, and the
previous line of code assigns the myName variable to this string value.
Python Basics 23
You can think of the input() function call as an expression that evalu-
ates to whatever string the user typed in. If the user entered 'Al', then the
expression would evaluate to myName = 'Al'.
>>> len('hello')
5
>>> len('My very energetic monster just scarfed nachos.')
46
>>> len('')
0
The print() function isn’t causing that error, but rather it’s the expres-
sion you tried to pass to print(). You get the same error message if you type
the expression into the interactive shell on its own.
24 Chapter 1
>>> 'I am ' + 29 + ' years old.'
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
'I am ' + 29 + ' years old.'
TypeError: Can't convert 'int' object to str implicitly
Python gives an error because you can use the + operator only to add
two integers together or concatenate two strings. You can’t add an integer
to a string because this is ungrammatical in Python. You can fix this by
using a string version of the integer instead, as explained in the next section.
>>> str(29)
'29'
>>> print('I am ' + str(29) + ' years old.')
I am 29 years old.
>>> str(0)
'0'
>>> str(-3.14)
'-3.14'
>>> int('42')
42
>>> int('-99')
-99
>>> int(1.25)
1
>>> int(1.99)
1
>>> float('3.14')
3.14
>>> float(10)
10.0
Python Basics 25
The previous examples call the str(), int(), and float() functions
and pass them values of the other data types to obtain a string, integer,
or floating-point form of those values.
The str() function is handy when you have an integer or float that you
want to concatenate to a string. The int() function is also helpful if you
have a number as a string value that you want to use in some mathematics.
For example, the input() function always returns a string, even if the user
enters a number. Enter spam = input() into the interactive shell and enter 101
when it waits for your text.
The value stored inside spam isn’t the integer 101 but the string '101'.
If you want to do math using the value in spam, use the int() function to
get the integer form of spam and then store this as the new value in spam.
Now you should be able to treat the spam variable as an integer instead
of a string.
>>> spam * 10 / 5
202.0
Note that if you pass a value to int() that it cannot evaluate as an inte-
ger, Python will display an error message.
>>> int('99.99')
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
int('99.99')
ValueError: invalid literal for int() with base 10: '99.99'
>>> int('twelve')
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
int('twelve')
ValueError: invalid literal for int() with base 10: 'twelve'
26 Chapter 1
>>> int(7.7)
7
>>> int(7.7) + 1
8
In your program, you used the int() and str() functions in the last
three lines to get a value of the appropriate data type for the code.
The myAge variable contains the value returned from input(). Because
the input() function always returns a string (even if the user typed in a num-
ber), you can use the int(myAge) code to return an integer value of the string
in myAge. This integer value is then added to 1 in the expression int(myAge) + 1.
The result of this addition is passed to the str() function: str(int(myAge)
+ 1). The string value returned is then concatenated with the strings 'You
will be ' and ' in a year.' to evaluate to one large string value. This large
string is finally passed to print() to be displayed on the screen.
Let’s say the user enters the string '4' for myAge. The string '4' is con-
verted to an integer, so you can add one to it. The result is 5. The str() func-
tion converts the result back to a string, so you can concatenate it with the
second string, 'in a year.', to create the final message. These evaluation
steps would look something like Figure 1-4.
>>> 42 == '42'
False
>>> 42 == 42.0
True
>>> 42.0 == 0042.000
True
Python makes this distinction because strings are text, while integers and
floats are both numbers.
Python Basics 27
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
Summary
You can compute expressions with a calculator or type string concatena-
tions with a word processor. You can even do string replication easily by
copying and pasting text. But expressions, and their component values—
operators, variables, and function calls—are the basic building blocks
that make programs. Once you know how to handle these elements, you
will be able to instruct Python to operate on large amounts of data for you.
It is good to remember the different types of operators (+, -, *, /, //, %,
and ** for math operations, and + and * for string operations) and the three
data types (integers, floating-point numbers, and strings) introduced in this
chapter.
A few different functions were introduced as well. The print() and input()
functions handle simple text output (to the screen) and input (from the key-
board). The len() function takes a string and evaluates to an int of the num-
ber of characters in the string. The str(), int(), and float() functions will
evaluate to the string, integer, or floating-point number form of the value
they are passed.
In the next chapter, you will learn how to tell Python to make intelli-
gent decisions about what code to run, what code to skip, and what code to
repeat based on the values it has. This is known as flow control, and it allows
you to write programs that make intelligent decisions.
Practice Questions
1. Which of the following are operators, and which are values?
*
'hello'
-88.8
-
/
+
5
28 Chapter 1