- Home
- Al Sweigart
Automate the Boring Stuff with Python Page 2
Automate the Boring Stuff with Python Read online
Page 2
For example, enter the following into the interactive shell next to the >>> prompt:
>>> print('Hello world!')
After you type that line and press ENTER, the interactive shell should display this in response:
>>> print('Hello world!') Hello world!
How to Find Help
Solving programming problems on your own is easier than you might think. If you’re not convinced, then let’s cause an error on purpose: Enter '42' + 3 into the interactive shell. You don’t need to know what this instruction means right now, but the result should look like this:
>>> '42' + 3 ➊ Traceback (most recent call last): File "
The error message ➋ appeared here because Python couldn’t understand your instruction. The traceback part ➊ of the error message shows the specific instruction and line number that Python had trouble with. If you’re not sure what to make of a particular error message, search online for the exact error message. Enter “TypeError: Can’t convert ‘int’ object to str implicitly” (including the quotes) into your favorite search engine, and you should see tons of links explaining what the error message means and what causes it, as shown in Figure 2.
Figure 2. The Google results for an error message can be very helpful.
You’ll often find that someone else had the same question as you and that some other helpful person has already answered it. No one person can know everything about programming, so an everyday part of any software developer’s job is looking up answers to technical questions.
Asking Smart Programming Questions
If you can’t find the answer by searching online, try asking people in a web forum such as Stack Overlow (http://stackoverflow.com/) or the “learn programming” subreddit at http://reddit.com/r/learnprogramming/. But keep in mind there are smart ways to ask programming questions that help others help you. Be sure to read the Frequently Asked Questions sections these websites have about the proper way to post questions.
When asking programming questions, remember to do the following:
Explain what you are trying to do, not just what you did. This lets your helper know if you are on the wrong track.
Specify the point at which the error happens. Does it occur at the very start of the program or only after you do a certain action?
Copy and paste the entire error message and your code to http://pastebin.com/ or http://gist.github.com/.
These websites make it easy to share large amounts of code with people over the Web, without the risk of losing any text formatting. You can then put the URL of the posted code in your email or forum post. For example, here some pieces of code I’ve posted: http://pastebin.com/SzP2DbFx/ and https://gist.github.com/asweigart/6912168/.
Explain what you’ve already tried to do to solve your problem. This tells people you’ve already put in some work to figure things out on your own.
List the version of Python you’re using. (There are some key differences between version 2 Python interpreters and version 3 Python interpreters.) Also, say which operating system and version you’re running.
If the error came up after you made a change to your code, explain exactly what you changed.
Say whether you’re able to reproduce the error every time you run the program or whether it happens only after you perform certain actions. Explain what those actions are, if so.
Always follow good online etiquette as well. For example, don’t post your questions in all caps or make unreasonable demands of the people trying to help you.
Summary
For most people, their computer is just an appliance instead of a tool. But by learning how to program, you’ll gain access to one of the most powerful tools of the modern world, and you’ll have fun along the way. Programming isn’t brain surgery—it’s fine for amateurs to experiment and make mistakes.
I love helping people discover Python. I write programming tutorials on my blog at http://inventwithpython.com/blog/, and you can contact me with questions at [email protected].
This book will start you off from zero programming knowledge, but you may have questions beyond its scope. Remember that asking effective questions and knowing how to find answers are invaluable tools on your programming journey.
Let’s begin!
Part I. Python Programming Basics
Chapter 1. Python Basics
The Python programming language has a wide range of syntactical constructions, standard library functions, and interactive development environment features. Fortunately, you can ignore most of that; you just need to learn enough to write some handy little programs.
You will, however, have to learn some basic programming concepts before you can do anything. Like a wizard-in-training, you might think these concepts seem arcane and tedious, but with some knowledge and practice, you’ll be able to command your computer like a magic wand to perform incredible feats.
This chapter has a few examples that encourage you to type into the interactive shell, which lets you execute Python instructions one at a time and shows you the results instantly. Using the interactive shell is great for learning what basic Python instructions do, so give it a try as you follow along. You’ll remember the things you do much better than the things you only read.
Entering Expressions into the Interactive Shell
You run the interactive shell by launching IDLE, which you installed with Python in the introduction. On Windows, open the Start menu, select All Programs ▸ Python 3.3, and then select IDLE (Python GUI). On OS X, select Applications ▸ MacPython 3.3 ▸ IDLE. On Ubuntu, open a new Terminal window and enter idle3.
A window with the >>> prompt should appear; that’s the interactive shell. Enter 2 + 2 at the prompt to have Python do some simple math.
>>> 2 + 2 4
The IDLE window should now show some text like this:
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> 2 + 2 4 >>>
In Python, 2 + 2 is called an expression, which is the most basic kind of programming instruction in the language. Expressions consist of values (such as 2) and operators (such as +), and they can always evaluate (that is, reduce) down to a single value. That means you can use expressions anywhere in Python code that you could also use a value.
In the previous example, 2 + 2 is evaluated down to a single value, 4. A single value with no operators is also considered an expression, though it evaluates only to itself, as shown here:
>>> 2 2
Errors are Okay!
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.
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.
Table 1-1. Math Operators from Highest to Lowest Precedence
Operator
Operation
Example
Evaluates to...
**
Exponent
2 ** 3
8
%
Modulus/remainder
22 % 8
6
//
Integer division/floored quotient
22 // 8
2
/
Division
22 / 8
2.75
*
Multiplication
3 * 5
15
/> -
Subtraction
5 - 2
3
+
Addition
2 + 2
4
The order of operations (also called precedence) of Python math operators is similar to that of mathematics. The ** operator is evaluated first; the *, /, //, and % operators are evaluated next, from left to right; and the + and - operators are evaluated last (also from left to right). You can use parentheses to override the usual precedence if you need to. Enter the following expressions into the interactive shell:
>>> 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.
Figure 1-1. Evaluating an expression reduces it to a single value.
These rules for putting operators and values together to form expressions 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 "
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.
The Integer, Floating-Point, and String Data Types
Remember that expressions are just values combined with operators, and they always evaluate down to a single value. A data type is a category for values, and every value belongs to exactly one data type. The most 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 indicates 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.
Table 1-2. Common Data Types
Data type
Examples
Integers
-2, -1, 0, 1, 2, 3, 4, 5
Floating-point numbers
-1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25
Strings
'a', 'aa', 'aaa', 'Hello!', '11 cats'
Python programs can also have text values called strings, or strs (pronounced “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:
>>> 'Hello world! SyntaxError: EOL while scanning string literal
String Concatenation and Replication
The meaning of an operator may change based on the data types of the values next to it. For example, + is the addition operator when it operates on two integers or floating-point values. However, when + is used on two string values, it joins the strings as the string concatenation operator. Enter the following into the interactive shell:
>>> 'Alice' + 'Bob' 'AliceBob'
The expression evaluates down to a single, new string value that combines 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 "
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 when talking about the str(), int(), and float() functions.)
The * operator is used for multiplication when it operates on two integer 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 multiplication) or one string value and one integer value (for string replication). Otherwise, Python will just display an error message.
>>> 'Alice' * 'Bob' Traceback (most recent call last): File "
It makes sense that Python wouldn’t understand these expressions: You can’t multiply two words, and it’s hard to replicate an arbitrary string a fractional number of times.
Storing Values in Variables
A variable is like a box in the computer’s memory where you can store a single value. If you want to use the result of an evaluated expression later in your program, you can save it inside a variable.
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.
Think of a variable as a labeled box that a value is placed in, as in Figure 1-2.
Figure 1-2. spam = 42 is like telling the program, “The variable spam now has the integer value 42 in it.”
For example, enter the following into the interactive shell:
➊ >>> spam = 40 >>> spam 40 >>> eggs = 2 ➋ >>> spam + eggs 42 >>> spam + eggs + spam 82 ➌ >>> spam = spam + 2 >>> spam 42
A variable is initialized (or created) the first time a value is stored in it ➊. After that, you can use it in expressions with other variables and values ➋. When a variable is assigned a new value ➌, the old value is forgotten, which is why spam evaluated to 42 instead of 40 at the end of the example. This is called overwriting the variable. Enter the following code into the interactive shell to try overwriting a string:
>>> spam = 'Hello' >>> spam 'Hello' >>> spam = 'Goodbye' >>> spam 'Goodbye'
Just like the box in Figure 1-3, the spam variable in this example stores 'Hello' until you replace it with 'Goodbye'.
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:
It can be only one word.
It can use only letters, numbers, and the underscore (_) character.
It
can’t begin with a number.
Table 1-3. Valid and Invalid Variable Names
Valid variable names
Invalid variable names
balance
current-balance (hyphens are not allowed)
currentBalance
current balance (spaces are not allowed)
current_balance
4account (can’t begin with a number)
_spam
42 (can’t begin with a number)
SPAM
total_$um (special characters like $ are not allowed)
account4
'hello' (special characters like ' are not allowed)
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.