Python
Python is a computer language that resembles Basic. It tries to be even easier to learn than Basic, though in some ways it’s harder.
Python is considered to be modern; Basic is considered to be old-fashioned. Many colleges teach students to program in Python instead of Basic.
Python was invented by a Dutchman, Guido van Rossum, in December 1989, as a hobby, to keep himself busy while his office was closed for Christmas vacation. He called it “Python” to honor the British comedy group Monty Python’s Flying Circus. In October 2000 he invented an improved version, Python 2. In December 2008, he invented a further improvement, Python 3.
This chapter explains the current version, Python 3.10.2, which is a slight improvement on Python 3.
In your Python program, you can put these commands —
Command What the computer will do Page
break break out of the “while” loop, stop repeating that loop 541
elif age<100: do the indented lines when earlier conditions false and age<100 537
else: do the indented lines when “if” conditions are false 536
for x in range(20): repeat the indented lines, for x being 0 through 19 (less than 20) 539
if age<18: do the indented lines if age<18 536
if age==18: do the indented lines if age is 18 537
if age!=18: do the indented lines if age is not 18 537
while True: do the indented lines repeatedly 538
x=2 make x be 2 532
x+=2 make x increase by 2 533
x-=2 make x decrease by 2 533
#Zoo is fishy ignore this comment 532
and these functions (which have parentheses):
Function Value Page
eval(input('What number? ')) whatever number the human will input 535
input('What is your name? ') whatever name the human will input 534
int(input('What number? ') whatever integer the human will input 535
float(input('What number? ') the number the human will input, with decimal 535
print('I love you') ‘I love you’ will print onto the computer’s screen 530
print(2+2) 4 will print onto the computer’s screen 530
range(20) the numbers less than 20 (0 through 19) 539
Fun
Let’s have fun programming in Python! If you have any difficulty, phone me at 603-666-6644 (day or night) for free help.
Get Python
Here’s how to copy Python (version 3.10.2) from the Internet to a Windows 10 or 11 computer, free (using Microsoft Edge).
Go to Python.org. You see this menu bar:
About Downloads Documentation Community Success Stories News Events
Tap “Downloads” then “Python 3.10.2” (or “Download Python 3.10.2”) then “Open file” then “Install Now” then “Yes”. The computer will say “Installing” then “Setup was successful.” Tap “Close”. Close the Microsoft Edge window (by clicking its X button).
Start Python
To start Python (version 3.10.2), do this:
Windows 10 In the search box (which is next to the Windows Start button), type “idle” then press Enter.
Windows 11 While you’re viewing the Start menu, type “idle” then press Enter.
You see the Python Shell window, which is also called Python’s Integrated DeveLopment Environment (IDLE).
Math
In the Python Shell window, you see this Python prompt:
>>>
That prompt imitates 3 right-arrows. It points to the writing box. The writing box is a big box, right of that prompt, and consumes most of the Pytho Shell window.
In the writing box, you can type any Python command. For example, you can type 4+2, so the writing box shows this:
4+2
Try doing that: type 4+2.
After typing 4+2, press the Enter key. The Enter key makes the computer read what you typed and reply to it. The computer will reply by typing the answer, 6, like this:
6
So the writing box looks like this:
4+2
6
Below that, the computer shows the Python prompt again, so you can give another command.
If you want to subtract 3 from 7, type 7-3, so the writing box looks like this:
7-3
When you press the Enter key at the end of that line, the computer will reply:
4
You can use decimal points and negative numbers. For example, if you type -26.3+1, the computer will say:
25.3
Multiplication To multiply, use an asterisk. So to multiply 2 by 6, type this:
2*6
The computer will say:
12
Division To divide, use a slash. So to divide 8 by 4, type this:
8/4
Instead of saying the answer is 2, the computer will say —
2.0
because whenever the computer divides, its answer includes a decimal point.
If you try to divide by 0 (by giving a command such as 3/0 or 0/0), the computer will refuse: it will say “ZeroDivisionError”.
Last digit might be wrong To divide 5 by 3, type this:
5/3
The computer will say:
1.6666666666666667
In that example, the computer gave the right answer, rounded to 17 digits. But in other calculations that have a decimal answer, the computer might accidentally say the last digit wrong. For example, suppose you say to divide 7 by 3, like this:
7/3
The computer will accidentally say:
2.3333333333333335
In that answer, the 5 should be 3 instead. Moral: when Python makes the computer
give a long decimal answer, don’t trust its last digit!
(I hope Python’s future versions hide that error, by showing just the 16
reliable digits and hiding the 17th digit.)
To see an even scarier example, type this:
.1+.2
The answer should be simply .3, but Python makes the computer say this:
.30000000000000004
The last digit, the 17th, should be 0, not 4.
Avoid commas Do not put commas in big numbers. To write four million, do not write 4,000,000; instead, write 4000000.
E notation If the computer’s answer is tiny (less than .0001) or “a huge number containing a decimal point” (at least 10000000000000000.0), the computer will put an e in the answer. The e means “move the decimal point”.
For example, suppose the computer says the answer to a problem is:
1.3586281902638497e+18
The e means “move the decimal point”. The plus sign means, “toward the right”. Altogether, the e+18 means “move the decimal point toward the right, 18 places.” So look at 1.3586281902638497 and move the decimal point toward the right, 18 places; you get —
1358628190263849700.
which has the same meaning as:
1358628190263849700.0
So when the computer says the answer is 1.3586281902638497e+18, the computer really means the answer is 1358628190263849700.0, approximately. Since you can’t trust the computer’s last digit (the 7) and the zeros that belong after it, the exact answer might be 1358628190263849700.2 or 1358628190263849700.29 or 1358628190263849800.0 or some similar number, but the computer says just an approximation.
Suppose your computer says the answer to a problem is:
9.23e-06
After the e, the minus sign means, “towards the left”. So look at 9.23 and move the decimal point towards the left, 6 places. You get:
.00000923
So when the computer says the answer is 9.23e-06, the computer really means the answer is:
.00000923
You’ll see e notation rarely: the computer uses it just if an answer involves decimals and tinier than .0001 or huge (at least 10 quadrillion). But when the computer does use e notation, remember to move the decimal point!
The highest number The highest number the computer can handle well is about 1e308, which is 1 followed by 308 zeros then a decimal point. If you try to go much higher, the computer will gripe by saying —
inf
which means “infinity”.
The tiniest decimal The tiniest decimal the computer can handle well is about 1e-323, which is a decimal point followed by 323 digits (322 zeros then 1). If you try to go much tinier, the computer will give up and say just:
0.0
Order of operations What does “2 plus 3 times 4” mean? The answer depends on whom you ask.
To a clerk, it means “start with 2 plus 3, then multiply by 4”; that makes 5 times 4, which is 20. But to a scientist, “2 plus 3 times 4” means something different: it means “2 plus three fours”, which is 2+4+4+4, which is 14.
Since computers were invented by scientists, computers think like scientists. If you type —
2+3*4
the computer will think you mean “2 plus three fours”, so it will do 2+4+4+4 and say this answer:
14
The computer will not print the clerk’s answer, which is 20. So if you’re a clerk, tough luck!
Scientists and computers follow this rule: do multiplication and division before addition and subtraction. So if you type —
2+3*4
the computer begins by hunting for multiplication and division. When it finds the multiplication sign between the 3 and the 4, it multiplies 3 by 4 and gets 12, like this:
2+3*4
12
So the problem becomes 2+12, which is 14, which the computer prints.
For another example, suppose you type:
10-2*3+72/9*5
The computer begins by doing all the multiplications and divisions. So it does 2*3 (which is 6) and does 72/9*5 (which is 8.0*5, which is 40.0), like this:
10-2*3+72/9*5
6 40.0
So the problem becomes 10-6+40.0, which is 44.0, which is the answer the computer says:
44.0
You can use parentheses the same way as in algebra. For example, if you type —
5-(1+1)
the computer will compute 5-2 and say:
3
You can put parentheses inside parentheses. If you type —
10-(5-(1+1))
the computer will compute 10-(5-2), which is 10-3, and will say:
7
Strings
Let’s make the computer fall in love. Let’s make it say, ‘I love you’.
To do that, type ‘I love you’, beginning and ending with a single-quote mark (which is the same mark as an apostrophe), so your screen looks like this:
'I love you'
At the end of that typing, when you press the Enter key, the computer will obey your command: it will say:
'I love you'
You can change the computer’s personality. For example, if you give this command —
'I hate you'
the computer will reply:
'I hate you'
Notice that to make the computer say a message, you must put the message between single-quote marks. The single-quote marks make the computer copy the message without worrying about what the message means. For example, if you misspell ‘I love you’ and type —
'aieee luf ya'
the computer will still copy the message (without worrying about what it means); the computer will say:
'aieee luf ya'
Jargon The word ‘joy’ consists of 3 characters: j and o and y. Programmers say that the word ‘joy’ is a string of 3 characters.
A string is any collection of characters,
such as ‘joy’ or ‘I love you’ or ‘aieee luf ya’ or
‘76 trombones’ or ‘GO AWAY!!!’ or
‘xypw exr///746’. The computer will say whatever string you wish, but remember
to
put the string in single-quote
marks.
Strings versus numbers The computer can handle two types of expressions: strings and numbers. Put strings (such as ‘joy’ and ‘I love you’) in single-quote marks. Numbers (such as 4+2) do not go in single-quote marks.
Accidents Suppose you accidentally put the number 2+2 in single-quote marks, like this:
'2+2'
The single-quote marks make the computer think ‘2+2’ is a string instead of a number. Since the computer thinks ‘2+2’ is a string, it copies the string without analyzing what it means; the computer will say:
'2+2'
It will not say 4.
Suppose you want the computer to say the word ‘love’ but you accidentally forget to put the string ‘love’ in single-quote marks. You accidentally type this instead:
love
Since you forget to type the single-quote marks, the computer will try to figure out what you mean but will get confused, since it doesn’t know the meaning of love. Whenever the computer gets confused, it gripes by saying you have a “NameError” or “SyntaxError”.
String arithmetic You can add strings. For example, ‘fat’+‘her’ is ‘father’. So if you type —
'fat'+'her'
the computer will say:
'father'
You can multiply a string by a number. For example, ‘fat’ multiplied by 3 is ‘fatfatfat’. So if you type —
'fat'*3
the computer will say:
'fatfatfat'
If you prefer, write the number before the string, like this:
3*'fat'
The computer will still say:
'fatfatfat'
If you say print, the computer will print onto your screen more briefly.
For example, if you say —
print('I love you')
The computer will print this onto your screen:
I love you
The computer will not print single-quote marks around that reply.
After the word print, you must type a parenthesis. If you forget to type the parenthesis and put a blank space instead, the computer will say “SyntaxError: Missing parentheses”.
If you say —
print('love',2+2,'you')
the computer prints the results of ‘love’ and 2+2 and ‘you’, all on the same line of your screen but separated by spaces, like this:
love 4 you
Yes, the computer produces love 4 you.
This command makes the computer do 6+2, 6-2, 6*2, and 6/2, all at once:
print(6+2,6-2,6*2,6/2)
That makes the computer print the four answers, all on the same line:
8 4 12 3.0
The computer puts spaces between the answers.
Create a program
Here’s how to create a Python program.
At the top of the Python Shell window, you see this menu:
File Edit Shell Debug Options Window Help
Click “File” then “New File”.
You see the program window, called “untitled”. The program window is empty: it doesn’t contain any >>> prompt.
The program window partly covers up the Python Shell window. To make programming easier, drag the word “untitled” toward the right; as you do so, the entire program window moves toward the right. Keep dragging toward the right until the program window no longer overlaps the Python Shell window. (If your screen isn’t wide enough to accomplish that, just drag as far as possible.)
In the program window, type your program. For example, let’s type a program that makes the computer say:
make your nose
touch your toes
To do that, type this program:
print('make your nose')
print('touch your toes')
At the end of each line, press the Enter key.
When you’ve done all that, tap “File” (at the top of the program window) then “Save”. Invent a name for your program, such as Joe; type the name then press the Enter key. That makes the computer copy the program to drive C. (If you’re using Python 3.10.2, the program will be in drive C’s Python310 folder. If you named the program Joe, the program’s name will actually be Joe.py, because the computer automatically puts “.py” at the end of the program’s name. The “.py” means “written in Python”.)
To run the program, tap the F5 key. (Exception: if the
“F5” is blue or tiny or on a new computer by Lenovo, HP, Microsoft, or Toshiba,
tap that key
while holding down the Fn key, which is left of the Space bar.) Then, in
the Python Shell window, you see the result of the program running, so you see:
make your nose
touch you toes
That writing is called the program’s output, since it’s what the program puts out.
Above the output, you see
“==== RESTART”. Above and below the output, you see the >>> prompt, so
you can give another Python command.
If you want to edit the program you wrote, tap in the program window (which is to the right of the Python Shell window or at least peeks out behind the the Python Shell window) or do this in the Program Shell window:
Tap “File” then your program’s name (such as “Joe”) then “Open”.
You see your program again. Make whatever changes you wish, then save the program again (by tapping “File” then “Save”), then run the program (by tapping the F5 key).
To see an old program you created, go to the Python Shell window then tap “File” then “Open” then double-tap the program’s name. You see the program’s lines. To run the program, tap the F5 key.
Warning: in a normal program, you must say print. For example, to make a program say the answer to 2+2, you can’t type just 2+2; instead the program must say:
print(2+2)
Saying just 2+2 is okay next to the >>> prompt, which means you’re in interactive mode, not in a program.
Polite versus fast To run a Python program, you must save it first. I showed you the polite way to do Python: save the program (by clicking “File” then “Save”) then run the program (by tapping the F5 key).
Here’s the faster way to run a Python program: tap the F5 key (which means you want to run the program), then watch the computer yell at you (for not saving the program first), then press the Enter key (which means you agree to save it). That’s impolite (so you get yelled at), but it’s faster than tapping “File” then “Save”.
Finish
When you finish using Python, close all windows (by clicking their X buttons).
Tricky printing
Printing can be tricky! Here are the tricks.
Indenting Suppose you want the computer to print this letter onto your screen:
Dear Joan,
Thank you for the beautiful
necktie. Just one problem--
I do not wear neckties!
Love,
Fred-the-Hippie
This program prints it:
print('Dear Joan,')
print(' Thank you for the beautiful')
print('necktie. Just one problem—')
print('I do not wear neckties!')
print(' Love,')
print(' Fred-the-Hippie')
In the program, each line contains 2 single-quote marks.
To
make the computer indent a line, put blank spaces AFTER the first single-quote mark.
Blank lines Life consists sometimes of joy, sometimes of sorrow, and sometimes of a numb emptiness. To express those feelings, run this program:
Program What the computer will do
print('joy') print ‘joy’
print() print a blank empty line, under ‘joy’
print('sorrow') print “sorrow”
Altogether, the computer will print:
joy
sorrow
Apostrophe An apostrophe is this symbol:
'
Many words contain apostrophes:
can't don't won't ain't I'll I'd I've I'm
Jack's O'Doole gov't '60s it's let's Qur'an
To put an apostrophe in a string’s middle, use one of these tricks:
Backslash trick Type a backslash before the apostrophe.
Double-quote trick Enclose the string in double-quote marks instead of single-quote marks.
For example, suppose you want the computer to say:
We've gone to Jack's house
This does not work:
print('We've gone to Jack's house')
Instead, you must use the backslash trick (putting a backslash before each apostrophe) —
print('We\'ve gone to Jack\'s house')
or the double-quote trick (putting the string in double-quote marks instead of single-quote marks):
print("We've gone to Jack's house")
If you use the backslash trick, make sure you type a backslash (\), not a forward slash (/). The backslash key is above the Enter key.
New line In a string, \n means “create a new line”. For example, if you type —
print('Love\nDeath')
the computer will print the word Love, then create a new line (by pressing the Enter key), then print the word Death, so you see this:
Love
Death
That’s how to make one print statement print 2 lines.
Separator If you say —
print('he','art','be','at')
the computer will print the 4 words and put blank spaces between them, like this:
he art be at
If instead you say —
print('he','art','be','at',sep='!')
the computer will print the 4 words and separate them with exclamation points instead of spaces, so you see this:
he!art!be!at
That’s because sep=‘!’ means “the separator is an exclamation point”.
If instead you say —
print('he','art','be','at',sep='')
The computer will print those 4 words and separate them with nothing, so you see this:
heartbeat
If instead you say —
print('the boy','the dog','the car',sep=' who chased ')
the computer will print:
the boy who chased the dog who chased the car
End In your program, if you say —
print('fat')
print('her')
the computer will print ‘fat’ and ‘her’ on separate lines, like this:
fat
her
That’s because, at the end of printing ‘fat’, the computer presses the Enter key.
Suppose you say this instead:
print('fat',end='!')
print('her')
The end=‘!’ means:
At the end of printing the line, print an exclamation point instead of pressing the Enter key.
So after printing ‘fat’, the computer will print an exclamation point instead of pressing the Enter key. The computer will print:
fat!her
Suppose you say this instead:
print('fat',end=' ')
print('her')
The end=‘ ’ means:
At the end of printing the line, press the space bar instead of the Enter key.
So after printing ‘fat’, the computer will press the space bar instead of the Enter key. The computer will print:
fat her
Suppose you say this instead:
print('fat',end='')
print('her')
The end=‘’ means:
At the end of printing the line, do nothing —don’t press the Enter key.
So after printing ‘fat’, the computer won’t press the Enter key; instead, the computer will just obey the next command, which makes the computer print ‘her’, so ‘her’ appears next to ‘fat’, like this:
father
Lines that aren’t commands
Usually, each line you type is a command. Here’s how to change that.
Semicolon To type two commands on one line, put a semicolon between the commands:
2+3; 7+1
The computer will say:
5
8
Backslash To type just part of a command on one line, put a backslash at the end of that part. Type the rest of the command on the line below.
For example, instead of typing —
3+6+200
you can type:
3+6+\
200
(The computer automatically indents the second line for you.) The computer will say the answer:
209
Instead of typing —
print('I love you')
you can type:
print('I lo\
ve you')
(Since you put the backslash in the middle of a string, the computer does not indent the second line.) The computer will say:
I love you
If you want to type a command that’s too long to fit on your screen, put a backslash at the end of the command’s first part; underneath, type the rest of the command.
Don’t put a backslash in the middle of a computer word (such as “print”). Don’t put a backslash in the middle of a number (such as 57).
Comment Occasionally, jot a note to remind yourself what your program does. Slip the note into your program by putting a hashtag (the symbol “#”) before it:
#This program is another dumb example, written by Russ.
#It was written on Halloween, under a full moon.
print('I love you') #because I want to date someone
When you run the program,
the computer ignores
everything that’s to the right of a hashtag. So the computer ignores the top two lines; in the bottom
line, the computer ignores the “because…”. The program makes the
computer print just this:
I love you
Everything to the right of a hashtag is called a comment. While the computer runs the program, it ignores the comments. But the comments remain part of the program; they appear in the right-hand window with the rest of the program. Though the comments appear in the program, they don’t affect the run.
Variables
You can name a number. For example, you can make Joan be the name for the number 7, by typing this:
Joan=7
Then Joan+2 is 9, so if you type —
Joan+2
the computer will reply:
9
The name can be short (like Joan) or long (like
PopeFrancisTheGreat) or
very short (like x) or technical (like TemperatureOfBasementFloor)
or include digits (like LeaderOfThe3Musketeers)
or disgusting (like number_of_times_we_vomited).
When you invent a name, you face these restrictions:
The name must consist of just letters, digits, and underscores. (So no periods, apostrophes, special characters, or blank spaces.)
The name must not begin with a digit.
The name must not be one of these keywords (which are also called reserved words): and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield.
To avoid confusion, the name shouldn’t be a Python function such as “print”.
Capitalization makes a difference.
If you say x=5, the computer will know x is the name for 5 but won’t know what X is yet. If you say Y=8, the computer will know Y is the name for 8 but won’t know what y is yet.
Some companies (such as Google) prohibit employees from using capital letters in names, except in special circumstances. If you work at one of those companies, make a name be:
x (not X)
joan (not Joan)
pope_francis_the_great (not PopeFrancisTheGreat)
leader_of_the_3_musketeers (not LeaderOfThe3Musketeers)
You can name any number. For example, you can say:
x=-34.1
Then x is -34.1, so if you type —
x*2
the computer will multiply -34.1 by 2 and say:
-68.2
You can name any string. For example, you can say:
y='go'
y*3
Then the computer will multiply ‘go’ by 3 and say:
'gogogo'
Beginners are usually too lazy to type long names, so beginners use names that are short (such as x). But when you become a pro and write a long, fancy program containing hundreds of lines and hundreds of names, you should use long names to help you remember each name’s purpose. A name can be as long as you wish. In this book, I’ll use short names in short programs (so you can type those programs quickly) but long names in long programs (so you can keep track of which name is which).
Jargon
A name (for a number or a string) is also called an identifier. It’s also called a variable.
For example, suppose you say:
Joan=7
That line makes Joan be a name, an identifier, a variable, whose value is 7. Since that line assigns 7 to Joan, that line is called an assignment statement. That line defines Joan to be 7.
If a variable (such as Joan) stands for a number, it’s called a numeric variable. If a variable stands for a string instead, it’s called a string variable.
Restart
When you run a program, the computer begins by doing a restart, which makes it forget any names you invented previously, so the program can start fresh.
After the program has run, the computer still remembers the names in the program. For example, if your program said Joan=7, the computer knows Joan is 7 even after the program has finished running, so if you say —
Joan
The computer will say:
7
A variable is a box
When you say Joan=7, here’s what happens inside the computer.
The computer’s random-access memory (RAM) consists of electronic boxes. The line Joan=7 makes the computer create a box named Joan and put 7 into it, like this:
box Joan 7
Then when the computer encounters print(x+2), the computer prints what’s in box Joan, plus 2; so the computer prints 9.
Variable from variables
One variable can define another. For example, suppose you type:
n=6
d=n+1
n*d
The top line says n is 6. The next line says d is n+1, which is 6+1, which is 7; so d is 7. The bottom line says to print n*d, which is 6*7, which is 42; so the computer will print:
42
Change a value
A value can change:
k=4
k=9
k*2
The top line says k’s value is 4. The next line changes k’s value to 9, so the bottom line prints 18.
When you run that program, here’s what happens inside the computer’s RAM. The top line (k=4) makes the computer put 4 into box k:
box k 4
The next line (k = 9) puts 9 into box k. The 9 replaces the 4:
box k 9
That’s why k*2 prints 18.
Self-changing variable A variable can change itself. Look at this program:
x=7
x=x+2
print(x)
The top line (x=7) says x starts by being 7. The next line (x=x+2) means: the new x is “what x was before, plus 2”. So the new x is 7+2, which is 9. The bottom line prints:
9
Let’s examine that program more closely. The top line (x=7) puts 7 into box x:
box x 7
When the computer sees the next line (x=x+2), it examines the equation’s right side and sees the x+2. Since x is 7, the x+2 is 7+2, which is 9. So the line “x=x+2” means x=9. The computer puts 9 into box x:
box x 9
The program’s bottom line prints 9.
Instead of typing —
x=x+2
you can type this shortcut:
x+=2
You can pronounce “x+=2” this way:
x gets added this amount: 2
Here’s another weirdo:
b=6
b+=1
print(b*2)
The second line (b+=1) says the new b gets added this amount: 1. So the new b is 6+1, which is 7. The bottom line prints:
14
In that program, the top line says b is 6; but the next line increases b, by adding 1; so b becomes 7. Programmers say that b has been increased or incremented. In the second line, the “1” is called the increase or the increment.
The opposite of “increment” is decrement:
j=500
j-=1
print(j)
The top line says j starts at 500; but the next line decreases j by subtracting 1, so the new j is 500-1, which is 499. The bottom line prints:
499
In that program, j was decreased (or decremented). In the second line, the “1” is called the decrease (or decrement).
Hassles
Variables can cause hassles.
Undefined variable If you type —
Joan
the computer tries to say Joan’s value (a number or string). If the computer fails (because you forgot to write a line such as Joan=7), the computer says “NameError”.
What’s before the equal sign? When writing an equation (such as x=47), put this before the equal sign: the name of just one box (such as x). So before the equal sign, put one variable:
Allowed: d=n+1 (d is one variable)
Not allowed: d-n=1 (d-n is two variables)
Not allowed: 1=d-n (1 is not a variable)
The variable on the equation’s left side is the only one that changes. For example, the statement d=n+1 changes the value of d but not n. The statement b=c changes the value of b but not c:
b=1
c=7
b=c
b+c
The third line changes b, to make it equal c; so b becomes 7. Since both b and c are now 7, the bottom line prints 14.
“b=c” versus “c=b” Saying “b=c” has a different effect from “c=b”. That’s because “b=c” changes the value of b (but not c); saying “c=b” changes the value of c (but not b).
Compare these programs:
b=1 b=1
c=7 c=7
b=c c=b
print(b+c) print(b+c)
In the left program, the third line changes b to 7, so both b and c are 7. The bottom line prints 14.
In the right program, the third line changes c to 1, so both b and c are 1. The bottom line prints 2.
While you run those programs, here’s what happens inside the computer’s RAM. For both programs, the second and third lines do this:
box b 1
box c 7
In the left program, the third line makes the number in box b become 7 (so both boxes contain 7, and the bottom line prints 14). In the right program, the third line makes the number in box c become 1 (so both boxes contain 1, and the bottom line prints 2).
When to use variables
Here’s a practical example of when to use variables.
Suppose you’re selling something that costs $1297.43, and you want to do these calculations:
multiply $1297.43 by 2
multiply $1297.43 by .05
add $1297.43 to $483.19
divide $1297.43 by 37
To do those four calculations, you could run this program:
print(1297.43*2,1297.43*.05,1297.43+483.19,1297.43/37)
But that program’s silly, since it contains the number 1297.43 four times. This program’s briefer, because it uses a variable:
c=1297.43
print(c*2,c*.05,c+483.19,c/37)
So whenever you need to use a number several times, turn the number into a variable, which will make your program briefer.
Paranoid If you’re paranoid, you’ll love this program:
t='They're laughing at you!'
print(t)
print(t)
print(t)
The top line says t stands for the string ‘They’re laughing at you!’ The later lines make the computer print:
They're laughing at you!
They're laughing at you!
They're laughing at you!
Nursery rhymes The computer can recite nursery rhymes:
p='Peas porridge'
print(p,'hot!')
print(p,'cold!')
print(p,'in the pot,')
print('Nine days old!')
The top line says p stands for ‘Peas porridge’. The later lines make the computer print:
Peas porridge hot!
Peas porridge cold!
Peas porridge in the pot,
Nine days old!
This program prints a fancier rhyme:
h='Hickory, dickory, dock!'
m='THE MOUSE (squeak! squeak!)'
c='THE CLOCK (tick! tock!)'
print(h)
print(m,'ran up',c)
print(c,'struck one')
print(m,'ran down')
print(h)
Lines 1-3 define h, m, and c. The later lines make the computer print:
Hickory, dickory, dock!
THE MOUSE (squeak! squeak!) ran up THE CLOCK (tick! tock!)
THE CLOCK (tick! tock!) struck one
THE MOUSE (squeak! squeak!) ran down
Hickory, dickory, dock!
Input
Humans ask questions; so to turn the computer into a human, you must make it ask questions too. To make the computer ask a question, use the word “input”.
This program makes the computer ask for your name:
n=input('What is your name? ')
print('I adore anyone whose name is',n)
The top
line says n is the answer to the question
‘What is your name?’ When you run the program and the computer
sees that line, the computer asks ‘What is your name?’ then waits for you to
answer the question; your answer will be called n. For example, if you answer
Maria, then n is ‘Maria’. The bottom line makes the computer print:
I adore anyone whose name is Maria
When you run that program, here’s the whole conversation that occurs between the computer and you; I’ve underlined the part typed by you.…
Computer asks for your name: What is your name? Maria
Computer praises your name: I adore anyone whose name is Maria
Go ahead, type that program and run it, but be careful:
when you type the input
line, leave a space after the question mark.
Just for fun, run that program again and pretend you’re somebody else.…
Computer asks for your name: What is your name? Bud
Computer praises your name: I adore anyone whose name is Bud
When the computer asks for your name, if you say something weird, the computer gives you a weird reply.…
Computer asks: What is your name? none of your business!
Computer replies: I adore anyone whose name is none of your business!
That program begins by making the computer ask:
What is your name?
You can make the computer say this instead:
Enter your name:
To do so, change the program’s top line to this:
n=input('Enter your name: ')
The program’s bottom line makes the computer reply like this:
I adore anyone whose name is Maria
You can make the computer add an exclamation point, like this:
I adore anyone whose name is Maria!
To do that, change the program’s bottom line to this:
print('I adore anyone whose name is',n+'!')
The +‘!’ means:
add an exclamation point, with no space before the exclamation point
College admissions
This program prints a letter, admitting you to the college of your choice:
c=input('What college would you like to enter? ')
print('Congratulations!')
print('You have just been admitted to',c)
print('because it fits your personality.')
print('I hope you go to',c+'.')
print(' Respectfully yours,')
print(' The Dean of Admissions')
When the computer sees the input line, the computer asks ‘What college would you like to enter?’ and waits for you to answer. Your answer will be called c. If you’d like to be admitted to Harvard, you’ll be pleased.…
Computer asks you: What college would you like to enter? Harvard
Computer admits you: Congratulations!
You have just been admitted to Harvard
because it fits your personality.
I hope you go to Harvard.
Respectfully yours,
The Dean of Admissions
The program’s 5th line includes these symbols:
+'.'
Those symbols mean:
add a period, with no space before the period
You can choose any college you wish:
Computer asks you: What college would you like to enter? Hell
Computer admits you: Congratulations!
You have just been admitted to Hell
because it fits your personality.
I hope you go to Hell.
Respectfully yours,
The Dean of Admissions
That program consists of three parts:
1. The computer begins by asking you a question (‘What college would you like to enter?’). The computer’s question is called the prompt, because it prompts you to answer.
2. Your answer (the college’s name) is called your input, because it’s information that you’re putting into the computer.
3. The computer’s reply (the admission letter) is called the computer’s output, because it’s the final answer that the computer puts out.
Input versus print
The word input is the opposite of the word print.
The word print makes the computer print information out. The word input makes the computer take information in.
What the computer prints out is called the output. What the computer takes in is called your input.
Input and Output are collectively called I/O, so the input and print statements are called I/O statements.
Once upon a time
Let’s make the computer write a story, by filling in the blanks:
Once upon a time, there was a youngster named ____________
your name
who had a friend named ____________.
friend’s name
____________ wanted to ________________ ____________,
your name verb (such as “pat”) friend’s name
but ____________ didn’t want to ________________ ____________!
friend’s name verb (such as “pat”) your name
Will ____________ ________________ ____________?
your name verb (such as “pat”) friend’s name
Will ____________ ________________ ____________?
friend’s name verb (such as “pat”) your name
To find out, come back and see the next exciting episode
of ____________ and ____________!
your name friend’s name
To write the story, the computer must ask for your name, your friend’s name, and a verb. To make the computer ask, your program must say input:
y=input('What is your name? ')
f=input('What is the name of your friend? ')
v=input('In 1 word, say something you can do to your friend? ')
Then make the computer print the story:
print('Here is my story....')
print('Once upon a time, there was a youngster named',y)
print('who had a friend named',f+'.')
print(y,'wanted to',v,f+',')
print('but',f,'did not want to',v,y+'!')
print('Will',y,v,f+'?')
print('Will',f,v,y+'?')
print('To find out, come back and see the next exciting episode')
print('of',y,'and',f+'!')
Here’s a sample run:
What is your name? Dracula
What is the name of your friend? Madonna
In 1 word, say something you can do to your friend? bite
Here is my story....
Once upon a time, there was a youngster named Dracula
who had a friend named Madonna.
Dracula wanted to bite Madonna,
but Madonna did not want to bite Dracula!
Will Dracula bite Madonna?
Will Madonna bite Dracula?
To find out, come back and see the next exciting episode
of Dracula and Madonna!
Here’s another run:
What is your name? Superman
What is the name of your friend? King Kong
In 1 word, say something you can do to your friend? tickle
Here is my story....
Once upon a time, there was a youngster named Superman
Who had a friend named King Kong.
Superman wanted to tickle King Kong,
but King Kong did not want to tickle Superman!
Will Superman tickle King Kong?
Will King Kong tickle Superman?
To find out, come back and see the next exciting episode
of Superman and King Kong!
Try it: put in your own name, the name of your friend, and something you’d like to do to your friend.
Numeric input
To let you input a number (instead of a string), your program should say “eval(input” instead of just “input”.
For example, this program lets you input a number and makes the computer double it:
n=eval(input('What number will you give me? '))
print('That number doubled is',n*2)
The top line says f is the answer, evaluated as a number, to the question ‘What number will you give me?’ When you run the program and the computer sees that line, the computer asks ‘What number will you give me?’ then waits for you to answer the question; your number will be called n. For example, if you say 3, then n is 3. The bottom line makes the computer print:
That number doubled is 6
When you run that program, here’s the whole conversation that occurs between the computer and you; I’ve underlined the part typed by you.…
Computer asks for a number: What number will you give me? 3
Computer doubles it: That number doubled is 6
Go ahead, type that program and run it, but be careful:
at the end of the eval line,
type TWO parentheses.
In that program, the eval tells the computer you’ll input a number.
If you leave out the eval, the computer will assume you’ll input a string instead of a number. Then if you input 3, the computer will assume you mean the string ‘3’, so the computer will double it (by repeating it) and say 33.
If you say int instead of eval, the computer will assume you’ll input an integer (a number that has no decimal point). Then if you input a number containing a decimal point, the computer will say “ValueError”.
If you say float instead of eval, the computer will assume you’ll input a floating-point number (a number that has a decimal point). Then if you input 3, the computer will assume you mean 3.0, so the computer will double it and say 6.0 (instead of just 6).
This program makes the computer predict your future:
print('I predict what will happen to you in the year 2030!')
y=eval(input('In what year were you born? '))
print('In the year 2030, you will turn',2030-y,'years old.')
Here’s a sample run:
I predict what will happen to you in the year 2030!
In what year were you born? 1972
In the year 2030, you will turn 58 years old.
Suppose you’re selling tickets to a play. Each ticket costs $2.79. (You decided $2.79 would be a nifty price, because the cast has 279 people.) This program finds the price of multiple tickets:
t=eval(input('How many tickets? '))
print('The total price is $',t*2.79)
This program tells you how much the “oil crisis” costs you, when you drive your car:
m=eval(input('How many miles do you want to drive? '))
p=eval(input('How many pennies does a gallon of gas cost? '))
r=eval(input('How many miles-per-gallon does your car get? '))
print('The gas for your trip will cost $',m*p/(r*100))
Here’s a sample run:
How many miles do you want to drive? 400
How many pennies does a gallon of gas cost? 257.9
How many miles-per-gallon does your car get? 31
The gas for your trip will cost $ 33.277419354838706
So the gas will cost a hair less than $33.28.
Conversion
This program converts feet to inches:
f=eval(input('How many feet? '))
print(f,'feet =',f*12,'inches')
Here’s a sample run:
How many feet? 2
2 feet = 24 inches
Trying to convert to the metric system? This program converts inches to centimeters:
i=eval(input('How many inches? '))
print(i,'inches =',i*2.54,'centimeters')
Nice day today, isn’t it? This program converts the temperature from Celsius to Fahrenheit:
c=eval(input('How many degrees Celsius? '))
print(c,'degrees Celsius =',c*1.8+32,'degrees Fahrenheit')
Here’s a sample run:
How many degrees Celsius? 20
20 degrees Celsius = 68.0 degrees Fahrenheit
See, you can write the Guide yourself! Just hunt through any old math or science book, find any old formula (such as f=c*1.8+32), and turn it into a program.
If
Let’s write a program so if the human is less than 18 years old, the computer will say:
You are still a minor.
Here’s the program:
age=eval(input('How old are you? '))
if age<18: print('You are still a minor')
The top line makes the computer ask ‘How old are you?’ and
wait for the human to type an age. Since the symbol for
“less than” is “<”, the bottom line says: if the age is less
than 18, print ‘You are still a minor’.
Go ahead! Run that program! The computer begins the conversation by asking:
How old are you?
Try saying you’re 12 years old, by typing a 12, so the screen looks like this:
How old are you? 12
When you finish typing the 12 and press the Enter key at the end of it, the computer will reply:
You are still a minor
Try running that program again, but this time try saying you’re 50 years old instead of 12, so the screen looks like this:
How old are you? 50
When you finish typing the 50 and press the Enter key at the end of it, the computer will not say “You are still a minor”. Instead, the computer will say nothing — since we didn’t teach the computer how to respond to adults yet!
In that program, the bottom line says:
if age<18: print('You are still a minor')
That line begins with the word “if”. Whenever you say “if”, you must also write a colon (the symbol “:”).
What comes between “if” and the colon is called the condition. In that example, the condition is “age<18”. If the condition is true (if age is really less than 18), the computer does the action, which comes after the colon and is:
print('You are still a minor')
Else
Let’s teach the computer how to respond to adults.
Here’s how to program the computer so if the age is less than 18, the computer will say “You are still a minor”, but if the age is not less than 18 the computer will say “You are an adult” instead:
age=eval(input('How old are you? '))
if age<18: print('You are still a minor')
else: print('You are an adult')
In programs, the word “else” means “otherwise”. That program’s 2nd and 3rd lines mean: if the age is less than 18, then print ‘You are still a minor’; otherwise (if the age is not less than 18), print ‘You are an adult’. So the computer will print ‘You are still a minor’ or else print ‘You are an adult’, depending on whether the age is less than 18.
Try running that program! If you say you’re 50 years old, so the screen looks like this —
How old are you? 50
the computer will reply by saying:
You are an adult
Multi-line
If the age is less than 18, here’s how to make the computer print “You are still a minor” and also print “Ah, the joys of youth”:
if age<18: print('You are still a minor'); print('Ah, the joys of youth')
Type that correctly: put a colon after “if age<18” but a semicolon between the two print statements.
Here’s a more sophisticated way to say the same thing:
if age<18:
print('You are still a minor')
print('Ah, the joys of youth')
That sophisticated way (in which you type 3 short lines instead of a single long line) is called a multi-line “if” (or a block “if”).
Here’s how to type that multi-line “if”:
Type the top line (which begins with “if” and ends with a colon). After you type the colon, press the Enter key.
When the computer sees you typed a colon and then pressed the Enter key, the computer knows you’re trying to create a multi-line, so the computer automatically indents the next line for you. When you finish typing that line (which says to print ‘You are still a minor’), press the Enter key again. The computer automatically indents the next line for you.
The computer will indent every line you type, until you begin a line by pressing the Backspace key, which tells the computer to stop indenting.
Pressing the Backspace key makes the computer unindent that line.
The indented lines are called the block. The line above them, which ends in a colon, is called the block’s header.
You can also create a multi-line “else”, so your program looks like this:
age=eval(input('How old are you? '))
if age<18:
print('You are still a minor')
print('Ah, the joys of youth')
else:
print('You are an adult')
print('We can have adult fun')
That means: if the age is less than 18, print You are still a minor’ and ‘Ah, the joys of youth’; otherwise (if age not under 18) print ‘You are an adult’ and ‘We can have adult fun’.
Elif
Let’s say this:
If age is under 18, print “You are a minor”.
If age is not under 18 but is under 100, print “You are a typical adult”.
If age is not under 100 but is under 120, print “You are a centenarian”.
If age is not under 120, print “You are a liar”.
Here’s another way to say the same thing, in English:
If age is under 18, print “You are a minor”.
Otherwise, if age is under 100, print “You are a typical adult”.
Otherwise, if age is under 120, print “You are a centenarian”.
Otherwise, print “You are a liar”.
The Python word for “otherwise” is “else”, and the Python word for “otherwise if” is “elif” (which is short for “else if”), so the Python program is:
if age<18: print('You are a minor')
elif age<100: print('You are a typical adult')
elif age<120: print('You are a centenarian')
else: print('You are a liar')
Double equal sign
Suppose you want to say:
If age is 25
Here’s how to say that:
if age==25:
Python doesn’t let the “if” condition have a simple equal sign (=); instead you must type a double equal sign (==). If you accidentally type a single equal sign there, the computer will say “SyntaxError”.
Therapist Let’s turn your computer into a therapist!
To make the computer ask the patient, “How are you?”, begin the program like this:
feeling=input('How are you? ')
Make the computer continue the conversation by responding this way:
If the patient says “fine”, print “That’s good!”
If the patient says “lousy” instead, print “Too bad!”
If the patient says anything else instead, print “I feel the same way!”
Here’s how:
if feeling=='fine': print('That\'s good!')
elif feeling=='lousy': print('Too bad!')
else: print('I feel the same way!')
Here’s a complete program:
feeling=input('How are you? ')
if feeling=='fine': print('That\'s good!')
elif feeling=='lousy': print('Too bad!')
else: print('I feel the same way!')
print('I hope you enjoyed your therapy. Now you owe $50.')
The top line makes the computer ask the patient, “How are you?” The next several lines makes the computer analyze the patient’s answer and print ‘That’s good!’ or ‘Too bad!’ or else ‘I feel the same way!’ Regardless of what the patient and computer said, that program’s bottom line always makes the computer end the conversation by printing:
I hope you enjoyed your therapy. Now you owe $50.
In that program, try changing the strings to make the computer print smarter remarks, become a better therapist, and charge even more money.
Fancy “if” conditions
Different relations You can make the “if” clause very fancy:
“if” clause Meaning
if b<4 If b is less than 4
if b>4 If b is greater than 4
if b<=4 If b is less than or equal to 4
if b>=4 If b is greater than or equal to 4
if b==4 If b is 4
if b=='fine' If b is the word ‘fine’
if b!=4 If b does not equal 4
if b!='fine' If b does not equal the word ‘fine’
if b<'fine' If b is a word that comes before ‘fine’ in dictionary
if b>'fine' If b is a word that comes after ‘fine’ in dictionary
In the “if” clause, the symbols <, >, <=, >=, ==, and != are called relations.
Or The computer understands the word “or”. For example, here’s how to say, “If x is either 7 or 8, print the word wonderful”:
if x==7 or x==8: print('wonderful')
That example is composed of two conditions: the first condition is “x==7”; the second condition is “x==8”. Those two conditions combine, to form “x==7 or x==8”, which is called a compound condition.
If you use the word “or”, put it between two conditions.
Right: if x==7 or x==8: print('wonderful')
Right because “x==7” and “x==8” are conditions.
Wrong: if x==7 or 8: print('wonderful')
Wrong because “8” is not a condition.
And The computer understands the word “and”. Here’s how to say, “If p is more than 5 and less than 10, print tuna fish”:
if p>5 and p<10: print('tuna fish')
Here’s how to say, “If s is at least 60 and less than 65, print you almost failed”:
if s>=60 and s<65: print('you almost failed')
Here’s how to say, “If n is a number from 1 to 10, print that’s good”:
if n>=1 AND n<=10: print('that's good')
Loops
You can make the computer repeat, again and again. Something repeated is called a loop. Here’s how to create a loop.
While True
This program makes the computer print the word '“love” once:
print('love')
This fancier program makes the computer print the word “love” three times:
print('love')
print('love')
print('love')
When you run that program, the computer will print:
love
love
love
Let’s make the computer print the word “love” many times. To do that, we must make the computer do this line many times:
print('love')
To make the computer do the line many times, say “while True” above the line, so the program looks like this:
while True:
print('love')
Here’s how to type that program:
Delete any lines you typed previously, so you can start fresh.
Type the top line (which begins with “while” and ends with a colon). After you type the colon, press the Enter key.
When the computer sees you typed a colon and then pressed the Enter key, the computer knows you’re trying to create a multi-line, so the computer automatically indents the next line for you. When you finish typing that line (which says to print ‘love’), press the Enter key again. (The computer will automatically indent any extra lines you type, until you begin a line by pressing the Backspace key, which tells the computer to stop indenting.)
When you run that program, the computer will print “love” many times, so it will print:
love
love
love
love
love
love
etc.
The computer will print “love” on every line of the Python Shell window.
But even when that window is full of “love”, the computer won’t stop: the computer will try to print even more loves onto your window! The computer will lose control of itself and try to devote its entire life to making love! The computer’s mind will spin round and round, always circling back to the thought of making love again!
Since the computer’s thinking keeps circling back to the same thought, the computer is said to be in a loop. In that program, the “while True” means “do repeatedly what’s indented”. The “while True” and the indented lines underneath form a loop, called a “while loop”.
To stop the computer’s lovemaking madness, you must give the computer a “jolt” that will put it out of its misery and get it out of the loop. To jolt the computer out of the program, abort the program. To abort the program, do this: while holding down the Control key (which says “Ctrl” on it), tap the C key. That makes the computer stop running your program; it will break out of your program; it will abort your program and say “KeyboardInterrupt”.
In that program, since the computer tries to go round and round the loop forever, the loop is called infinite. The only way to stop an infinite loop is to abort it.
Cats and dogs Run this program:
while True:
print('cat')
print('dog')
The computer will repeatedly print ‘cat’ and ‘dog’, so the screen will look like this:
cat
dog
cat
dog
cat
dog
cat
dog
etc.
Yes, on the screen it will be raining cats and dogs! The computer will keep printing “cat” and “dog” until you abort the program.
Interactive mode Instead of creating that program (which requires you to press the F5 key to run), you can create the cats and dogs by typing in interactive mode, at the >>> prompt, like this:
while True:
print('cat')
print('dog')
When you create the blank line under ‘dog’ (by pressing the Enter key again), the computer performs the while loop and prints lots of cats and dogs, until you abort. Here’s why:
In interactive mode, a blank line means “perform the loop now”.
Conversions This program, which you saw before, converts feet to inches:
f=eval(input('How many feet? '))
print(f,'feet =',f*12,'inches')
Here’s a sample run:
How many feet? 2
2 feet = 24 inches
Suppose you want to:
convert 2 feet to inches
and also convert 7 feet to inches
and also convert 1000 feet to inches
and also convert 59.2 feet to inches
and also convert 3 feet to inches
and also convert 5280 feet to inches
and also convert other quantities of feet to inches
To do all that, you can run that conversion program many times: each time you want to run that conversion program, say “run” (by pressing the F5 key). But instead of pressing the F5 key so many times, you can make the computer rerun the program for you automatically! To do that, begin your program by by typing:
while True:
That means: automatically do, repeatedly, the indented lines underneath. Type those indented lines, so the program becomes like this:
while True:
f=eval(input('How many feet? '))
print(f,'feet =',f*12,'inches')
When you run that program (by pressing the F5 key once), the computer will repeatedly convert feet to inches, each time asking you ‘How many feet?’ The computer will keep converting feet to inches until you abort the program.
Counting Suppose you want the computer to count, starting at 3, like this:
3
4
5
6
7
8
etc.
This program does it, by a special technique:
c=3
while True:
print(c)
c+=1
In that program, c is called the counter, because it helps the computer count.
The top line says c starts at 3. The “while” loop says to repeatedly do this:
print c, then increase c by adding 1 to it
So the computer prints c (which is 3), then increases c (so c becomes 4), then repeats the indented lines again, so the computer prints the new c (which is 4), then increases c again (so c becomes 5), then repeats the indented lines again, so the computer prints the new c (which is 5), then increases c again (so c becomes 6), etc. The computer repeatedly prints c and increases it. Altogether, the computer prints:
3
4
5
6
7
8
9
10
11
etc.
The program’s an infinite loop: the computer will print 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, and so on, forever, unless you abort it.
Here’s the general procedure to make the computer count:
Start c at some value (such as 3).
Then write a “while” loop.
In the “while” loop, make the computer use c (such as by saying to print c), and increase c (by saying c+=1).
To read the printing more easily, say end=‘ ’:
c=3
while True:
print(c,end=' ')
c+=1
That makes the computer print horizontally:
3 4 5 6 7 8 etc.
This program makes the computer count, starting at 1:
c=1
while True:
print(c,end=' ')
c+=1
The computer will print 1, 2, 3, 4, etc.
This program makes the computer count, starting at 0:
c=0
while True:
print(c,end=' ')
c+=1
The computer will print 0, 1, 2, 3, 4, etc.
For
Let’s make the computer print every number from 0 to 19, like this:
0
1
2
3
4
5
6
7
etc.
19
Here’s the program:
for x in range(20):
print(x)
The top line says x will be every number under 20; so x will be 0, then 1, then 2, etc. The line underneath, which is indented, says what to do about each x; it says to print each x.
The computer will do the indented line repeatedly, so the computer will repeatedly print(x). To begin, x will be 0, so the computer will print:
0
The next time the computer prints x, the x will be 1, so the computer will print:
1
The computer will print every number from 0 up to 19. It will not print 20.
How to start at 1 If you want to print every number from 1 to 20, say this instead:
for x in range(1,21):
print(x)
That makes the computer start at 1 (instead of 0) and print the numbers under 21, like this:
1
2
3
4
5
etc.
20
Interactive mode Instead of creating that program (which requires you to press the F5 key to run), you can type in interactive mode, at the >>> prompt, like this:
>>> for x in range(1,21):
print(x)
When you create the blank line under print(x) (by pressing the Enter key again), the computer performs the loop and prints the numbers under 21, starting at 1.
When men meet women Let’s make the computer print these lyrics:
I saw 2 men
meet 2 women.
Tra-la-la!
I saw 3 men
meet 3 women.
Tra-la-la!
I saw 4 men
meet 4 women.
Tra-la-la!
I saw 5 men
meet 5 women.
Tra-la-la!
They all had a party!
Ha-ha-ha!
To do that, type these lines —
The first line of each verse: print('I saw',x,'men')
The second line of each verse: print('meet',x,'women.')
The third line of each verse: print('Tra-la-la!')
Blank line under each verse: print()
after making x be every number from 2 up to 5 (so x starts at 2 but stays less than 6):
for x in range(2,6):
print('I saw',x,'men')
print('meet',x,'women.')
print('Tra-la-la!')
print()
At the end of the song, print the closing couplet:
for x in range(2,6):
print('I saw',x,'men')
print('meet',x,'women.')
print('Tra-la-la!')
print()
print('They all had a party!')
print('Ha-ha-ha!') x
(The computer automatically indents every line under “for”, until you begin a line by pressing the Backspace key, which tells the computer to stop indenting.) That program makes the computer print the entire song.
Here’s an analysis:
for x in range(2,6):
The computer will do the print('I saw',x,'men')
indented lines repeatedly, print('meet',x,'women.')
for x=2, x=3, x=4, and x=5. print('Tra-la-la!')
print()
Then the computer will print('They all had a party!')
print this couplet once. print('Ha-ha-ha!')
Since the computer does the indented lines repeatedly, those lines form a loop. Here’s the general rule: the statements indented under “for” form a loop. The computer goes round and round the loop, for x=2, x=3, x=4, and x=5. Altogether, it goes around the loop 4 times, which is a finite number. Therefore, the loop is finite.
If you don’t like the letter x, choose a different letter. For example, you can choose the letter i:
for i in range(2,6):
print('I saw',i,'men')
print('meet',i,'women.')
print('Tra-la-la!')
print()
print('They all had a party!')
print('Ha-ha-ha!')
When using the word “for”, most programmers prefer the letter i; most programmers say “for i” instead of “for x”. Saying “for i” is an “old tradition”. Following that tradition, the rest of this book says “for i” (instead of “for x”), except in situations where some other letter feels more natural.
Print the squares To find the square of a number, multiply the number by itself. The square of 3 is “3 times 3”, which is 9. The square of 4 is “4 times 4”, which is 16.
Let’s make the computer print the square of 3, 4, 5, etc., up to 20, like this:
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49
etc.
The square of 20 is 400
To do that, type this line —
print('The square of',i,'is',i*i)
and make i be every number from 3 up to 20 (so below 21), like this:
for i in range(3,21):
print('The square of',i,'is',i*i)
Count how many copies This program, which you saw before, prints “love” on every line of your screen:
while True:
print('love')
That program prints “love” again and again, until you abort the program by pressing Ctrl with C.
But what if you want to print “love” just 20 times? This program prints “love” 20 times —
for i in range(20):
print('love')
because it makes i be 0 then 1 then 2 then 3, etc., up to 19.
As you can see, “for” resembles “while” but is more powerful: “for” makes the computer count!
Count to midnight This program makes the computer count to midnight:
for i in range(1,12):
print(i)
print('midnight')
The computer will print:
1
2
3
4
5
6
7
8
9
10
11
midnight
At the end of the indented line, let’s say end=‘ ’, like this:
for i in range(1,12):
print(i,end=' ')
print('midnight')
That makes the computer print each item on the same line and separated by spaces, like this:
1 2 3 4 5 6 7 8 9 10 11 midnight
If you want the computer to press the Enter key before “midnight”, say \n:
for i in range(1,12):
print(i,end=' ')
print('\nmidnight')
That extra print line makes the computer press the Enter key just before “midnight”, so the computer will print “midnight” on a separate line, like this:
1 2 3 4 5 6 7 8 9 10 11
midnight
Let’s make the computer count to midnight 3 times, like this:
1 2 3 4 5 6 7 8 9 10 11
midnight
1 2 3 4 5 6 7 8 9 10 11
midnight
1 2 3 4 5 6 7 8 9 10 11
midnight
To do that, indent the entire program under the word “for”:
for j in range(3):
for i in range(1,12):
print(i,end=' ')
print('\nmidnight')
That version contains a loop inside a loop: the loop that says “for i” is inside the loop that says “for j”. The j loop is called the outer loop; the i loop is called the inner loop. The inner loop’s variable must differ from the outer loop’s. Since we called the inner loop’s variable “i”, the outer loop’s variable must not be called “i”; so I picked the letter j instead.
Programmers often think of the outer loop as a bird’s nest, and the inner loop as an egg inside the nest. So programmers say the inner loop is nested in the outer loop; the inner loop is a nested loop.
Step size The “for” statement can be varied.
If you say —
for i in range(5,18,3):
the i will start at 5, stay under 18, and keep increasing by 3.
So i will be 5,
then 8 (because i increased by 3),
then 11 (because i increased by 3 again),
then 14 (because i increased by 3 again),
then 17 (because i increased by 3 again),
then stop (because i must stay under 18).
In that example:
The 5 is called the start value.
The 18 is called the stop value.
The 3 is called the increase (or increment or step size).
The i is called the counter (or index or
loop-control variable).
Although 18 is the stop
value, 17 is the
last value
(or terminal value).
Programmers usually say “for i”, instead of “for x”, because the letter i reminds them of the word index.
If you say —
for i in range(17,4,-3):
the i will start at 17, not get to 4, and keep decreasing by 3.
So i will be 17,
then 14 (because i decreased by 3),
then 11 (because i decreased by 3 again),
then 8 (because i decreased by 3 again),
then 5 (because i decreased by 3 again),
then stop (because i must not get to 4 or beyond).
In that example, 3 is called the decrease (or decrement); -3 is the step size.
To count down, you must say a negative step size, such as -3 or -1. So to count every number from 17 down to 5, give this instruction:
for i in range(17,4,-1):
This program prints a rocket countdown:
for i in range(10,0,-1):
print(i)
print('Blast off!')
The computer will start at 10, count down (because the step size is -1), and stop the loop before saying 0; so the computer will print:
10
9
8
7
6
5
4
3
2
1
Blast off!
Suppose you want i to be 6.0, then 6.1, then 6.2, etc., up to 8.0. Python doesn’t let the range contain decimal points, so use this trick: make j be 60, then 61, then 62, etc., up to 80, then make i be a tenth of j, like this:
for j in range(60,81)
i=j/10
print(i)
Break
If you’re stuck in jail, you hope to break out. Similarly, if a computer is stuck in a loop (doing the same thing again and again), the computer hopes to break out.
To let the computer break out of a loop, say “break”. Saying “break” lets the computer stop looping; it lets the computer break free from the loop and skip ahead to the rest of your program.
For example, suppose you say:
while True:
print('eat')
break
print('sandwiches under')
print('the trees')
The “while” tells the computer to obey the indented lines repeatedly, to form a loop. The first indented line makes the computer print:
eat
But the next line says “break”, which makes the computer break out of the loop, stop looping, do no more indented lines, and so not print ‘sandwiches under’; the computer will skip ahead to the next unindented line, which prints:
the trees
So the program makes the computer print just this:
eat
the trees
Guessing game This program plays a guessing game, where the human tries to guess the computer’s favorite color, which is pink:
while True:
if 'pink'==input('What is my favorite color? '): break
print('No, that is not my favorite color. Try again!')
print('Congratulations! You discovered my favorite color.')
Here’s what the 2nd line means. If ‘pink’ matches the human’s reply to the question ‘What is my favorite color?’, break out of the loop, so the computer skips ahead to unindented line, which prints:
Congratulations! You discovered my favorite color.
But if ‘pink’ does not match the human’s reply, the computer will continue looping, by saying:
No, that is not my favorite color. Try again!
Here’s another way to program the guessing game:
while True:
print('You have not guessed my favorite color yet!')
if 'pink'==input('What is my favorite color? '): break
print('Congratulations! You discovered my favorite color.')
That program’s loop makes the computer do this repeatedly: say ‘You have not guessed my favorite color yet!’ and then ask ‘What is my favorite color?’ The computer will repeat the indented lines again and again, until the guess is ‘pink’. When the guess is “pink”, the computer breaks out of the loop and proceeds to the bottom line, which prints ‘Congratulations!’.
Sex This program makes the computer discuss human sexuality:
while True:
sex=input('Are you male or female? ')
if sex=='male':
print('So is Frankenstein!')
break
if sex=='female':
print('So is Mary Poppins!')
break
print('Please say male or female!')
The 2nd line makes the computer ask, ‘Are you male or female?’ If the human claims to be “male”, the computer prints ‘So is Frankenstein!’ and stops looping. If the human says “female” instead, the computer prints ‘So is Mary Poppins!’ and stops looping. If the human says anything else (such as “not sure” or “super-male” or “macho” or “none of your business”), the computer prints ‘Please say male or female!’ and then does the loop again, so the computer asks again, ‘Are you male or female?’
That program’s bottom line is called an error handler (or error-handling routine or error trap), since its only purpose is to handle human error (a human who says neither “male” nor “female”). The error handler prints a gripe message (‘Please say male or female!’) and then lets the human try again (by having the human do the loop again).
Here’s how to accomplish the same goal without indenting so much:
while True:
sex=input('Are you male or female? ')
if sex=='male' or sex=='female': break
print('Please say male or female!')
if sex=='male': print('So is Frankenstein!')
else: print('So is Mary Poppins!')
That “while” loop says:
Ask the human ‘Are you male or female?’ and call the answer “sex”.
If the sex is male or female, that’s fine, so break out of the loop; otherwise, print ‘Please say male o female!’ and do the loop again.
Let’s extend that program’s conversation. If the human says “female”, let’s make the computer say “So is Mary Poppins!”, then ask “Do you like her?”, then continue the conversation this way:
If human says “yes”, make computer say “I like her too. She is my mother.”
If human says “no”, make computer say “I hate her too. She owes me a dime.”
If human says neither “yes” nor “no”, make computer handle that error.
To accomplish all that, put the shaded lines into the program:
while True:
sex=input('Are you male or female? ')
if sex=='male' or sex=='female': break
print('Please say male or female!')
if sex=='male': print('So is Frankenstein!')
else:
print('So is Mary Poppins!')
while True:
opinion=input('Do you like her? ')
if opinion=='yes' or opinion=='no': break
print('Please say yes or no!')
if opinion='yes': print('I like her too. She is my mother.')
else: print('Neither do I. She still owes me a dime.')
Rules Here are the rules about saying “break”:
The “break” command is legal just if the computer’s in a loop.
You can say “break” if the computer’s in a “while” loop or a “for” loop.
If the computer’s in nested loops (a loop inside a loop), the “break” command makes the computer break out of the inner loop but not the outer loop.
Data structures
You can combine numbers and strings, to build a data structure. Here’s how.
Lists
Here’s a list:
[‘love’,‘death’,666,‘giggle’,3.14]
That list contains 5 items: ‘love’ and ‘death’ and 666 and ‘giggle’ and 3.14.
In a list, put commas between the items.
Begin the list with an open bracket (the symbol “[”).
End the list with a closed bracket (the symbol “]”).
So the entire list is enclosed in brackets (the symbols “[]”).
If you say —
['love','death',666,'giggle',3.14]
or say —
print(['love','death',666,'giggle',3.14])
the computer will say the list:
['love', 'death', 666, 'giggle', 3.14]
If you say —
[5+3,70+20]
The computer will do the math and say:
[8, 90]
A list is also called an array.
Variable A variable can be a list. For example, you can say:
x=['love','death',666,'giggle',3.14]
Adding You can add lists together. If you say —
['dog','cat']+['mouse','cheese']
The computer will add the list [‘dog’,‘cat’] to the list [‘mouse’,‘cheese’] and say:
['dog', 'cat', 'mouse', 'cheese']
For The “for” statement can use a list. If you say —
for i in [18,21,100]:
the i will be 18 then 21 then 100. If you say —
for i in ['Joe','Fred','Mary']:
the i will be ‘Joe’ then ‘Fred’ then ‘Mary’.
Let’s make the computer print this message:
We love meat
We love potatoes
We love lettuce
We love tomatoes
This program does that:
for i in ['meat','potatoes','lettuce','tomatoes']:
print('We love',i)
You can also write the program this way:
x=['meat','potatoes','lettuce','tomatoes']
for i in x:
print('We love',i)
Subscripts Suppose you say:
x=['Joe','Fred','Mary']
That list contains 3 items: ‘Joe’, ‘Fred’, and ‘Mary’.
In x’s list, the starting item (which is ‘Joe’) is called x0 (which is pronounced “x subscripted by zero” or “x sub 0” or just “x 0”). The next item (which is ‘Fred’) is called x1 (which is pronounced “x subscripted by one” or “x sub 1” or just “x 1”). The next item is called x2. So the 3 numbers in the list are called x0, x1, and x2.
To make the computer say what x2 is, type this:
x[2]
The computer will say:
'Mary'
Notice this jargon:
In a symbol such as x2, the lowered number (the 2) is called the subscript.
To create a subscript, use brackets. For example, to create x2, type x[2].
You can change what’s in a list. For example, if you want to change x2 to ‘Alice’, say:
x[2]='Alice'
Suppose you say:
x=['Joe','Fred','Mary']
x[2]='Alice'
The x starts as [‘Joe’,‘Fred’,‘Mary’], but ‘Mary’ changes to ‘Alice’; so if you say —
x
the computer will say:
['Joe', 'Fred', 'Alice']
Too long If you want to type a list that’s too long to fit on one line, do this:
Type part of the list on one line. Type a backslash at the end of that part. Type the rest of the list below. Type a backslash at the end of each line (except the list’s bottom line). The backslash means: the rest of the list continues below.
List in a list A list can contain another list. For example, look at this list:
x=['Joe','Fred',['dog','cat']]
In that list, x[0] is ‘Joe’, x[1] is ‘Fred’, and x[2] is the list [‘dog’, ‘cat’]. Since ‘dog’ is the starting item of the list x[2], ‘dog’ is x[2][0]. Since ‘cat’ is the next item of the list x[2], ‘cat’ is x[2][1].
Blanks in a list You can create a list that’s full of blanks, then fill the blanks later.
To create a list that has 100 blank items, say:
x=[None]*100
The “None” means “blank”. Those 100 blank items are called x0, x1, x2, etc., up through x99.
After creating that x, you can give a command such as:
x[57]='fun'
That command is legal just after you’ve created x.
If you try giving that command without creating x previously,
the computer will say “NameError”.
If you try talking about x200 even though you created up through just x99,
the computer will say “IndexError”.
Dictionaries
Suppose Jack is great, Jim is jolly, Sue is sweet, and Mary is smart.
To store that info, create a dictionary called d, like this:
d={'Jack':'great', 'Jim':'jolly', 'Sue':'sweet', 'Mary':'smart'}
When you type that, put the dictionary in braces, which are the symbols “{}” and require you to press the Shift key.
Then if you want to use that dictionary to look up Sue, type:
d['Sue']
The computer will use the dictionary, look up Sue, discover Sue is sweet, and say:
'sweet'
Instead of the letter d, you can use any variable name you wish.
Here’s how to put a dictionary into a program:
d={'Jack':'great', 'Jim':'jolly', 'Sue':'sweet', 'Mary':'smart'}
name=input('What name should I look up? ')
if name in d: print(name,'is',d[name])
else: print('Sorry, I do not know about',name)
The top line creates the dictionary. The next line makes the computer ask “What name should I look up?” and wait for the human to type a name. If the human typed a name (such as “Sue”) that’s in the dictionary, the program’s third line makes the computer print a message such as:
Sue is sweet
But if the human typed a name (such as “Alice”) that’s not in the dictionary, the program’s bottom line makes the computer print a message such as:
Sorry, I do not know about Alice
Besides storing comments such as “sweet”, you can make the dictionary store people’s addresses, phone numberd, social-security numbers, birthdays, debts, sexual orientiations, and methods by which they’d like to kill you when they discover you’ve stored that private data.
A dictionary is also called a lookup table.
Let’s make the computer translate English colors to French, by using this lookup table:
English French
white blanc
yellow jaune
red rouge
blue bleu
black noir
That lookup table becomes our multilingual dictionary. Here’s the program:
d={'white':'blanc', 'yellow':'jaune', 'red':'rouge', 'blue':'bleu', 'black':'noir'}
EnglishColor=input('What color should I translate? ')
if EnglishColor in d: print('In French it is',d[EnglishColor])
else: print('Sorry, I do not know the French for',EnglishColor)
Too long If you want to type a dictionary (lookup table) that’s too long to fit on one line, do this:
Type part of the dictionary on one line. Type a backslash at the end of that part. Type the rest of the dictionary below. Type a backslash at the end of each line (except the dictionary’s bottom line). The backslash means: the rest of the dictionary continues below.