- Home
- Al Sweigart
Automate the Boring Stuff with Python Page 3
Automate the Boring Stuff with Python Read online
Page 3
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 importantly: 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 documentation (inspired by the Monty Python “Spam” sketch), but in your programs, a descriptive name will help make your code more readable.
Your First Program
While the interactive shell is good for running Python instructions one at a time, to write entire Python programs, you’ll type the instructions into the file editor. The file editor is similar to text editors such as Notepad or TextMate, but it has some specific features for typing in source code. To open the file editor in IDLE, select File▸New Window.
The window that appears should contain a cursor awaiting your input, but it’s different from the interactive shell, which runs Python instructions as soon as you press ENTER. The file editor lets you type in many instructions, save the file, and run the program. Here’s how you can tell the difference between the two:
The interactive shell window will always be the one with the >>> prompt.
The file editor window will not have the >>> prompt.
Now it’s time to create your first program! When the file editor window opens, type the following into it:
➊ # This program says hello and asks for my name. ➋ print('Hello world!') print('What is your name?') # ask for their name ➌ myName = input() ➍ print('It is good to meet you, ' + myName) ➎ print('The length of your name is:') print(len(myName)) ➏ 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 File▸Save 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 ⌘-S on OS X to save your file.
Once you’ve saved, let’s run our program. Select Run▸Run 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:
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. >>> ================================ RESTART ================================ >>> Hello world! What is your name? Al It is good to meet you, Al The length of your name is: 2 What is your age? 4 You will be 5 in a year. >>>
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 program exits.)
You can close the file editor by clicking the X at the top of the window. To reload a saved program, select File▸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.
Dissecting Your Program
With your new program open in the file editor, let’s take a quick tour of the Python instructions it uses by looking at what each line of code does.
Comments
The following line is called a comment.
➊ # This program says hello and asks for my name.
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 temporarily 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.
The print() Function
The print() function displays the string value inside the parentheses on the screen.
➋ 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 function. 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.
When writing a function name, the opening and closing parentheses at the end identify it as the name of a function. This is why in this book you’ll see print() rather than print. Chapter 2 describes functions in more detail.
The input() Function
The input() function waits for the user to type some text on the keyboard and press ENTER.
➌ 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.
You can think of the input() function call as an expression that evaluates to whatever string the user typed in. If the user entered 'Al', then the expression would evaluate to myName = 'Al'.
Printing the User’s Name
The following call to print() actually contains the expression 'It is good to meet you, ' + myName between the parentheses.
➍ print('It is good to meet you, ' + myName)
Remember that expressions can always evaluate to a single value. If 'Al' is the value stored in myName on the previous line, then this expression evaluates to 'It is good to meet you, Al'. This single string value is then passed to print(), which prints it on the screen.
The len() Function
You can pass the len() function a string value (or a variable containing a string), and the function evaluates to the integer value of the number of characters in that string.
➎ print('The length of your name is:') print(len(myName))
Enter the following into the interactive shell to try this:
>>> len('hello') 5 >>> len('My very energetic monster just scarfed nachos.') 46 >>> len('') 0
Just like those examples, len(myName) evaluates to an integer. It is then passed to print() to be displayed on the screen. Notice that print() allows you to pass it either integer values or string values. But notice the error that shows up when you type the following into the interactive shell:
>>> print('I am ' + 29 + ' years old.') Traceback (most recent call last): File "
The print() function isn’t causing that error, but rather it’s the expression you tried to pass to print(). You get the same error message if you type the expression into the interacti
ve shell on its own.
>>> 'I am ' + 29 + ' years old.' Traceback (most recent call last): File "
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.
The str(), int(), and float() Functions
If you want to concatenate an integer such as 29 with a string to pass to print(), you’ll need to get the value '29', which is the string form of 29. The str() function can be passed an integer value and will evaluate to a string value version of it, as follows:
>>> str(29) '29' >>> print('I am ' + str(29) + ' years old.') I am 29 years old.
Because str(29) evaluates to '29', the expression 'I am ' + str(29) + ' years old.' evaluates to 'I am ' + '29' + ' years old.', which in turn evaluates to 'I am 29 years old.'. This is the value that is passed to the print() function.
The str(), int(), and float() functions will evaluate to the string, integer, and floating-point forms of the value you pass, respectively. Try converting some values in the interactive shell with these functions, and watch what happens.
>>> 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
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.
>>> spam = input() 101 >>> spam '101'
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.
>>> spam = int(spam) >>> spam 101
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 integer, Python will display an error message.
>>> int('99.99') Traceback (most recent call last): File "
The int() function is also useful if you need to round a floating-point number down.
>>> 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.
➏ print('What is your age?') # ask for their age myAge = input() print('You will be ' + str(int(myAge) + 1) + ' in a year.')
The myAge variable contains the value returned from input(). Because the input() function always returns a string (even if the user typed in a number), 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 converted to an integer, so you can add one to it. The result is 5. The str() function 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.
Text and Number Equivalence
Although the string value of a number is considered a completely different value from the integer or floating-point version, an integer can be equal to a floating point.
>>> 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.
Figure 1-4. The evaluation steps, if 4 was stored in myAge
Summary
You can compute expressions with a calculator or type string concatenations 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 keyboard). The len() function takes a string and evaluates to an int of the number 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 intelligent 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
Q:
1. Which of the following are operators, and which are values?
* 'hello' -88.8 - / + 5
Q:
2. Which of the following is a variable, and which is a string?
spam 'spam'
Q:
3. Name three data types.
Q:
4. What is an expression made up of? What do all expressions do?
Q:
5. This chapter introduced assignment statements, like spam = 10. What is the difference between an expression and a statement?
Q:
6. What does the variable bacon contain after the following code runs?
bacon = 20 bacon + 1
Q:
7. What should the following two expressions evaluate to?
'spam' + 'spamspam' 'spam' * 3
Q:
8. Why is eggs a valid variable name while 100 is invalid?
Q:
9. What three functions can be used to get the integer, floating-point number, or string version of a value?
Q:
10. Why does this expression cause an error? How can you fix it?
'I have eaten ' + 99 + ' burritos.'
Extra credit: Search online for the Python documentation for the len() function. It will be on a web page titled “Built-in Functions.” Skim the list of other functions Python has, look up what the round() function does, and experiment with it in the interactive shell.
Chapter 2. Flow Control
So you know the basics of individual instructions and that a program is just a series of instructions. But the real strength of programming isn’t just running (or executing) one instruction after another like a weekend errand list. Based on how the expressions evaluate, the program can decide to skip instructions, repeat them, or choose one of several instructions to run. In fact, you almost never want your programs to start from the first line of code and simply execute every line, straight to the end. Flow control statements can de
cide which Python instructions to execute under which conditions.
These flow control statements directly correspond to the symbols in a flowchart, so I’ll provide flowchart versions of the code discussed in this chapter. Figure 2-1 shows a flowchart for what to do if it’s raining. Follow the path made by the arrows from Start to End.
Figure 2-1. A flowchart to tell you what to do if it is raining
In a flowchart, there is usually more than one way to go from the start to the end. The same is true for lines of code in a computer program. Flowcharts represent these branching points with diamonds, while the other steps are represented with rectangles. The starting and ending steps are represented with rounded rectangles.
But before you learn about flow control statements, you first need to learn how to represent those yes and no options, and you need to understand how to write those branching points as Python code. To that end, let’s explore Boolean values, comparison operators, and Boolean operators.
Boolean Values
While the integer, floating-point, and string data types have an unlimited number of possible values, the Boolean data type has only two values: True and False. (Boolean is capitalized because the data type is named after mathematician George Boole.) When typed as Python code, the Boolean values True and False lack the quotes you place around strings, and they always start with a capital T or F, with the rest of the word in lowercase. Enter the following into the interactive shell. (Some of these instructions are intentionally incorrect, and they’ll cause error messages to appear.)