A Wikibookian believes this page should be split into smaller pages with a narrower subtopic. You can help by splitting this big page into smaller ones. Please make sure to follow thenaming policy. Dividing books into smaller sections can provide more focus and allow each one to do one thing well, which benefits everyone. |
The following sections will introduce various concepts in computer programming. There are some simplifications in the explanations below. Don't take anything too literally.
The purpose of programming is to tell the computer what to do. Computers are better at doing some things than you are, like a chef is better at cooking than you are. It's easier to tell a chef to cook you a meal than to cook it yourself. The more precise you are in your request, the more your meal will turn out how you like it. In most scenarios like this in real life, small amounts of ambiguity and misinterpretation are acceptable. Perhaps the chef will boil your potato before mashing it instead of baking it. With computers, however, ambiguity is rarely acceptable. Programs are so complex that if the computer just guessed at the meaning of ambiguous or vague requests, it might cause problems so subtle that you'd never find them. Programming languages, therefore, have been designed to accept only completely clear and unambiguous statements. The program might still have problems, but the blame is then squarely on you, not on the computer's guess. Much of the difficulty in programming comes from having to be perfectly precise and detailed about everything instead of just giving high-level instructions.
Some languages require total and complete detail about everything. C and C++ are such languages, and are calledlow-level languages. Other languages will make all sorts of assumptions, and this lets the programmer specify less detail. Python and Basic are such languages, and are calledhigh-level languages. In general, high-level languages are easier to program but give you less control. Control is sometimes important, for example if you want your program to run as quickly as possible. Most of the time total control and speed aren't necessary, and as computers get faster high-level languages become more popular. Here we will deal exclusively with high-level languages. Low-level languages are generally similar except there's often more lines of code to write to accomplish the same thing.
Most programming languages have the concept of a statement. Astatement is a command that the programmer gives to the computer. For example:
print "Hi there!"
This command has a verb ("print") and other details (what to print). In this case, the commandprint means "show on the screen," not "print on the printer." The programmer either gives the statement directly to the computer (by typing it while running a special program), or creates a text file with the command in it. You could create a file called "hi.txt" using a program like Notepad, put the above command in it, and give the file to the computer. (The details of how to do all this are language- and system-specific, so they won't be covered here. This is just an introduction to the concepts.)
If you have more than one command in the file, each will be performed in order, top to bottom. So the file could contain:
print "Hi there!" print "Strange things are afoot..."
The computer will perform each of these commands sequentially. It's invaluable to be able to "play computer" when programming. Ask yourself, "If I were the computer, what would I do with these statements?" If you're not sure what the answer is, then you are very likely to write incorrect programs. Stop and check the manual for the programming language you're using.
In the above case, the computer will look at the first statement, determine that it's aprint statement, look at what needs to be printed, and display that text on the computer screen. It'll look like this:
Hi there!
Note that the quotation marks aren't there. Their purpose in the program is to tell the computer where the text begins and ends, just like in English prose. The computer will then continue to the next statement, perform its command, and the screen will look like this:
Hi there! Strange things are afoot...
When the computer gets to the end of the text file, it stops and waits for further instructions. There are many different kinds of statements, depending on which programming language is being used. For example, there could be abeep statement that causes the computer to output a beep on its speaker, or awindow statement that causes a new window to pop up.
Also, the way statements are written will vary depending on the programming language. The programming language Python uses statements that look like the above. In C you would write:
puts("Hi there!"); puts("Strange things are afoot...");Note a few differences:
These differences are fairly superficial. The set of rules like the first two is called a programming language'ssyntax. The set of verbs is called itslibrary.
All computer languages have syntax, rules to create proper statements, just like natural languages do. For example, most sentences are ended with a full stop or a period. Likewise it is common for statements in source code to be ended with a semicolon, but many languages do not have this requirement so it is important to know the syntax of the language you are programming in. For example, if you wanted the computer to display two different things you could write:
print "I have a dog. His name is Bort."
or you could write:
print "I have a dog. " + "His name is Bort."
The second example has two strings, each enclosed in quotation marks. There's a plus (+) sign in between them, which means, "Attach the two strings together, turning them into a single string." (Attaching two strings is calledconcatenation.) The two above statements will display the same thing:
I have a dog. His name is Bort.
In the above examples there's no reason why you'd use a+ and two strings when you could just use a single string, as in the first example, but below there will be cases where concatenation of strings is necessary. The languages Python and Java use plus (+) for string concatenation, Perl and PHP use the period (.), and Visual Basic uses ampersand (&). Again, these differences are superficial; what's important is the concept of string concatenation and of language syntax to do things like concatenation. Separate in your mind an underlying concept and a particular language's way of expressing that concept.
When programs are compiled, or converted into an executable program, they are analyzed by a parser, the equivalent of a proofreader, to determine if the syntax is correct. Assuming the program's source code is syntactically correct, the compiler will continue to analyze the source code to determine if there are any semantical errors.
Semantics refers to the meaning or logic of a computer program. Two syntactically correct statements can make perfect sense by themselves, but they may not make sense when placed next to each other. Sometimes these flaws in logic can be detected by the compiler, what is known as a compile-time error, but typically these errors surface when the program is executed, known as run-time errors.
Observe the following conversation:
Alice: Terrible news. Carl's wife was in a car accident.Bob: Oh, that is terrible. Send some nice flowers and get everyone to sign a card.Alice: Sure. Oh, and Dan called in sick again.Bob: Not again. Send him a pink slip.
The conversation makes perfect, logical sense. This conversation shows a good, consistent use of semantics.
Now observe this conversation:
Alice: Terrible news. Carl's wife was in a car accident.Bob: Not again. Send him a pink slip.Alice: Sure. Oh, and Dan called in sick again.Bob: Oh, that is terrible. Send some nice flowers and get everyone to sign a card.
Although this conversation contains the exact same sentences as the previous one, it has a very different meaning. A human may be able to bend the rules of grammar and structure to determine the intended meaning of a conversation, but computers are not as flexible. Therefore, it is important to use proper syntax and use good semantics in order to properly convey to the computer what you want it to do. Understand though, that the first conversation could have been rearranged and still have the same meaning or different sentences could have been used to convey the same idea. In that sense there can be many different ways to write the same program.
Say you had a program that talked about your dog. It might look like this:
print "I have a dog. It is called Bort." print "Bort likes to eat dog food." print "My children and Bort get along very well." print "My dog Bort barks at my neighbor, whose name is also Bort."
You might go on like this for a while, asking the computer to display many such interesting things about your dog. If, one day, you changed your dog's name, or instead wanted to talk about your other dog, or gave this program to a friend and they wanted to change it to refer to their own dog, you'd have to go through the whole program and change every occurrence of "Bort" to the new name. You could use your text editor's search-and-replace feature to do this, but doing so is tedious and you might make mistakes. For example, you might accidentally replace the neighbor's name when you only intended to change the dog's name.
Programming languages solve this problem by allowing you to write the dog's name only once and then refer to it using a label. This is a bit like using pronouns in natural languages. So you could write:
dog = "Bort"
If you're "playing computer" and get to the above statement, you'll think, "Remember the string "Bort", and whenever the worddog is used, substitute the word "Bort"." This is called anassignment statement because you're assigning meaning to the worddog. A subsequent statement could say:
print dog
Note that there are no quotation marks here. You don't literally want to print the word "dog", you want the computer to remember the string it had previously associated with that word. It's a bit like the distinction between saying "He said his age" and "He said, 'his age'." In the first case it's a number and in the second it's the words "his age". The worddog is avariable. It's a symbol that the computer associates with something else, in this case the word "Bort". Our original program can now be written as:
print "I have a dog. It is called " + dog + "." print dog + " likes to eat dog food." print "My children and " + dog + " get along very well." print "My dog " + dog + " barks at my neighbor, whose name is Bort."
Note that string concatenation (using the plus sign) was necessary here, since sometimes we wanted to use quotation marks (to mean literal text) and sometimes we didn't (to refer to the variable). The computer will see a statement like:
print dog + " likes to eat dog food."
and first substitute the worddog with the string "Bort":
print "Bort" + " likes to eat dog food."
then concatenate the strings:
print "Bort likes to eat dog food."
then perform the statement, displaying this on the screen:
Bort likes to eat dog food.
Note also that the name of the neighbor was not replaced by a reference todog. The variabledog refers to the name of the dog. That's the whole point of using the variable: to keep track of a specific concept. You could have a different variable to keep track of the neighbor's name:
neighbor = "Bort"
and change the last line of our program to:
print "My dog " + dog + " barks at my neighbor, whose name is " + neighbor + "."
That way you can change the name of your dog or your neighbor easily at the top of the file and the rest of the program will run correctly. I removed the word "also" from the line since, now that we're using variables, I can no longer be sure that the two names are the same. I wouldn't want to change one of the two and have my program still display the word "also" there. Later we'll see a way of displaying the word "also" only if the two names are the same.
It's important to remember two things about variables. Firstly, a variable must be set before it is used. So you must write:
dog = "Bort" print dog
and not:
print dog (Wrong!) dog = "Bort"
Remember when "playing computer" that you must look at each statement individually and in order from top to bottom. In the second example above you would first get to the "print dog" statement and have no idea what the variabledog was referring to. Different languages react differently when they run into this problem. Some just assume the variable is an empty string (""), but most stop the program and report the error.
Secondly, when you're "playing computer" and see the second line of the correct program:
dog = "Bort" print dog
it's very important that you don't "go back up" to the first line to see whatdog refers to. The first line is long gone. You can only look at one line at a time, and always sequentially. The first line makes a note somewhere (in memory) thatdog refers to "Bort", but then the line itself is left behind and forgotten. The second line checks memory and gets the variable's meaning there, not from the first line directly. This may seem like a trivial distinction, but we'll use variables in more sophisticated ways later and it won't work to "go back up" to find where a variable was set; you'll need to think of the variable and its value as being stored in memory.
The wordvariable implies that variables can change, and indeed they can. You could write the following program:
dog = "Bort" print "My first dog was called " + dog + "." dog = "Milou" print "And my second dog was called " + dog + "."
The computer will see the first line, associate the string "Bort" with the variabledog, use that string in the second line, change the association of the variabledog to "Milou" in the third line, and use the new association in the fourth. In memory the variabledog can only be associated with one string. The third line above replaces the old association with the new. The second and fourth lines look into memory to see what that association is, and at each statement the value is different because the value in memory is different at that point in the program's execution. You'll see:
My first dog was called Bort. And my second dog was called Milou.
When the computer sees a mathematical expression, it performs the arithmetic automatically. For example, you can write:
print 5 + 6
Note again that there are no quotation marks. If there were, the computer would take that literally and print "5 + 6". The plus sign is called anoperator because it performs operations on other values. When the computer sees the above line, it will perform the arithmetic and get:
print 11
Executing the statement will just print the number:
11
Note that the following two statements will display the same thing:
print 11 print "11"
except that in the first case the computer knows it's a number, whereas in the second case it's just a string. Sometimes that distinction matters, but we can ignore it for now. The math can get pretty complicated:
print (5 + 12) * 9 / 14
The computer would perform the arithmetic step by step, just like you would in your head. It would first do the addition, since it's in parentheses:
print 17 * 9 / 14
Then the multiplication, since it's on the left:
print 153 / 14
Then the division:
print 10
And you'd see this if you ran the original line:
10
Note that 153 divided by 14 is actually something like 10.928, but the computer printed the round number below the real value. That's because there are two kinds of numbers most languages deal with: integers and reals.Integers are round numbers, like the ones above.Reals are numbers with a decimal point, like 10.928. When the computer sees an expression using entirely integers, it keeps using integers to do the math, even if the result really should be a real. Had we written:
print (5.0 + 12.0) * 9.0 / 14.0
then the computer would have performed the math using reals and we would have seen something like this printed:
10.9285714286
This is a quirky result of the historical development of computers. It can lead to bizarre results, like this line:
print 1 / 2
displaying "0" instead of the expected "0.5". There are times when the current behavior is desirable, but often it's not and you should keep the distinction between integers and reals in mind. Also note that the above rules about integers and reals apply to most commonly-used programming languages, but each language is free to make up its own rules for dealing with numbers, and you may one day use a language that does things differently, such as making "1 / 2" result in "0.5".
Variables can be used to refer to numbers as well as strings. You could write:
x = 5 print x
to print "5". Or you could write:
age = 33 print age * 2
to find out twice your age. Again here the first line creates in memory an association between the variable whose name isage with the number 33. The second line looks into memory, grabs the number associated withage, and performs the arithmetic. Note that the first line is not algebra. It's not an equation that makesage and the number 33 the same. It's anassignment of the value 33 to the variableage. The distinction is important when you see a line like:
x = x + 5
The above line is impossible in algebra. The value ofx cannot be equal to the value ofx plus five. But in a programming language, the line reads as, "Find the value of the variablex in memory, add 5 to it, then associate the result with the variablex." The fact thatx is used both in the math expression on the right of the equal sign and as the place to store the results is irrelevant. Its value is used in the math expressionbefore the result is stored back into the variable. Here's another example:
x = 5 y = x + 2 print x print y
You'll get:
5 7
But now if you write:
x = 5 y = x + 2 x = 10 print x print y
You'll get:
10 7
Go through each line and "play computer" to convince yourself of why the above would behave this way. Use a piece of paper to keep track of thex andy variables if you need to. If the above isn't clear, stop and re-read this section or the one on variables. This is a very common stumbling block for new programmers.
You might have noticed that we use the plus (+) symbol to mean both "string concatenation" and "numerical addition". This is fine and usually clear, but what should the computer do with a statement like this:
print "5" + 6
Should the numbers 5 and 6 be added to yield 11? Should the string "5" be concatenated with the string "6" to yield "56"? Should the computer stop and report an error? Each language deals with this ambiguity in different ways. In Python, the above line would be an error. You'd have to explicitly tell the computer which interpretation you wanted. In Java the "6" would be turned into a string, resulting in the string "56". In Perl, PHP, and Visual Basic the string concatenation operator is not plus, it's period for Perl and PHP and ampersand in Visual Basic, so it's always clear what needs to be done based on which operator is used.
Say we had a simple program that displayed your age:
age = 25 print "You are " + age + " years old."
If you ran this program it would display:
You are 25 years old.
Next year you could change the first line to "age = 26" and the program's output would update appropriately. In fact you could give this program to anyone and they could modify the first line so that the second line would print the right age. Once you turned 30 you might want to modify it like this:
age = 30 print "You are " + age + " years old." print "Your warranty has expired!"
That would work fine, except that if you now gave it to someone who was 25 they would not only have to modify the first line but remember to remove the third line. But why force a human to remove the third line? The computer should be able to automatically display or not display the third line depending on the value ofage. We can use an "if" statement to tell the computer to do just that:
age = 30 print "You are " + age + " years old." if age > 29: print "Your warranty has expired!"
Again let's "play computer": when you get to the third line, you look at the wordage, realize it's a variable, and get its value (30) from memory (it was stored there on line 1):
if 30 > 29:
This line says, "If 30 is greater than 29, perform the statements that are indented. If not, skip the indented statements." Since 30 is greater than 29, the indented statements are performed and the joke is displayed on the screen. If a friend changes the first line to "age = 25", the third line will compare 25 to 29, and since 25 is not greater than 29, the fourth line will be skipped.
This is aconditional. Whether the fourth line is run is conditional on the math expression on the third line. That expression could be more complex, such as:
if age >= 40 and age < 50: print "You are in your forties."
The>= symbol means "greater than or equal to". Here the "print" line won't get run unless the age is between 40 and 49. You can also put more than one indented statement:
if age >= 50 and age < 60: print "You are in your fifties." print "Mid-life crisis yet?"
If the person's age is between 50 and 59, both lines will be displayed; otherwise neither will. Now notice that if the age of the user is 1, the second line of our original program will display a grammatical error:
You are 1 years old.
That should be "year", not "years". We can use a conditional to fix this bug:
age = 25 if age == 1: print "You are " + age + " year old." if age != 1: print "You are " + age + " years old."
The== means "is equal to". There are two equal signs in order to differentiate it from an assignment statement, which uses a single equal sign (as in the first line of our program). This is related to what we wrote above about computer languages always wanting to be perfectly clear about what's intended. The!= means "not equal to". Think of the math symbol of the equal sign with a slash through it, then imagine the exclamation mark being that slash. Now if you setage to 1 you'll get this:
You are 1 year old.
Which is correct. If theage is not 1, then the first "print" will be skipped and the second will run, displaying the version of the text with a plural "years". It's fairly common to want to do one thing if a condition is true (such as "age == 1") and another if that condition is not true ("age != 1"). So computer languages have a shortcut to save you from having to retype a whole "if" statement with the inverse condition. You simply write this:
age = 25 if age == 1: print "You are " + age + " year old." else: print "You are " + age + " years old."
That means, "If age is 1, run the first print statement. If not (else), run the second print statement." Again you can have multiple statements in either the first section or the second:
age = 25 if age == 1: print "You are " + age + " year old." print "You're an infant!" else: print "You are " + age + " years old." print "You're not an infant."
Now you can give this program to someone else and they only need to change the first line to get a few lines of accurate text displayed about them. You can imagine that this can get arbitrarily complex, with very sophisticated conditions being tested. Consider this:
age = 25 if age == 1: print "You are " + age + " year old." print "You're an infant!" else: print "You are " + age + " years old." if age < 25: print "You're young." else: print "You're mature!"
This is called a "nestedif". The second "if" (the one that comparesage with 25) isnested (within) the first "if". Since it's indented, the second "if" will itself only be run if the first condition ("age == 1") is not true. Ifage is in fact 1, the first "print" will be run and the entire second section, including the second "if", will be skipped. So the program will display only one of "You're an infant!" or "You're young." or "You're mature!". You should "play computer" through this program with various values ofage, such as 1, 5, 25, and 30.
Conditionals are extremely useful. In our example, it would have been possible (though inconvenient) for each person to add or remove "print" statements as they modified the age in the first line, but in reality the value forage would have come from elsewhere, such as a form or a database, and the program would have to run as-is, unmodified, and display the correct text for any value ofage that it might get.
We can look at conditionals in C, again to show that basic concepts are available in different programming languages with only superficial differences:
if (age > 29) puts("Your warranty has expired!");Note these differences: there are parenthese around the condition; "print" was replaced with "puts", as before; the text to display is surrounded by parentheses; and there's a terminating semicolon at the end of the "puts" statement. If you wanted to display more than one line, you'd have to write it like this:
if (age >= 50 && age < 60) { puts("You are in your fifties."); puts("Mid-life crisis yet?"); }Note these two additional differences: the "and" has been replaced with "&&" in the condition; and there are braces around the pair of "puts" statements. In C (and languages derived from C, such as C++, Java, and C#), indentation is ignored, so the "if" statement will assume that only the very next statement will be conditionally run. If you want more than one statement, you have to group them with braces to tell the language that all of these are conditionally run. In our Python-like language above, indentation is used to tell which statements are under the control of the "if" and "else" lines.
In the above examples, the age was placed right in the source code,on line 1:
age = 25
This is calledhard-coding the age. Thehard comes from thefact that once the program is written that way, the age is always25. If the user wants to run the program with a different age,they need to change the source code. But that assumes that theyunderstand programming. Since most users don't understand programming,we'd really like to simply ask the user their age so that theynever need to see the source code at all.
We can use a line like this:
age = input()
Toinput something means to put it into the computer.Outputis the reverse, like theprint statements we've been using.
So our program now looks something like:
print "What is your age?" age = input() if age == 1: print "You are " + age + " year old." else: print "You are " + age + " years old."
When the user runs the program, instead of immediately seeingthe "You are ..." text, they'll first see this:
What is your age?
and the system will appear to stop. The user will then be ableto enter their age, press Enter, and the program will continueas it did before, with the variableage set to whatevernumber the user entered.
You may be curious about the set of parentheses after the wordinput. If you didn't have those, like this:
age = input
the wordinput would look a lot like a variable. Since computersalways want to be completely clear about what needs to be done, weadd parentheses to mean, "This isn't a variable, it's a command.Do something clever."input() is actually afunction.We'll cover functions later, but for now you can think of themas bits of code that do interesting things (like getting a numberfrom the keyboard) and making some value available as a result(for assignment toage in this case). When the computer sees thisline:
age = input()
It first sees the functioninput(), does the clever thing(gets a number from the keyboard), and replaces the function withthe value that it got:
age = 25
(if the user typed25). Then the assignment continues as itdid before, storing the value 25 into memory and associating it withthe wordage.
Say we wanted to write a program that asked the user how many timesthey wanted a phrase repeated. (Yes, it really is necessary to havethese silly examples. More realistic examples are often too complexto demonstate a single new concept.)
print "How many times?" count = input() if count == 1: print "Are we there yet?" if count == 2: print "Are we there yet?" print "Are we there yet?" if count == 3: print "Are we there yet?" print "Are we there yet?" print "Are we there yet?" if count == 4: print "Are we there yet?" print "Are we there yet?" print "Are we there yet?" print "Are we there yet?"
If you run this program, the user will be asked "How many times?" and thecomputer will wait for an answer. The user can then type a numberbetween 1 and 4 and the phrase "Are we there yet?" will be displayedthat many times. There are several problems with this program.Firstly, it can at most handle a count of 4. If the user wantsit displayed 5 times, the program must be extended to handle thatcase. Secondly, as the number of cases grows, it will be difficultto make sure that the program is correct. If you extend it allthe way to, say, 20 times, it's difficult to check using your texteditor that the case for 17 really has 17 lines in it. Perhapsyou made an error and only cut-and-pasted the line 16 times. We couldbe clever and rewrite it like this:
print "How many times?" count = input() if count >= 1: print "Are we there yet?" if count >= 2: print "Are we there yet?" if count >= 3: print "Are we there yet?" if count >= 4: print "Are we there yet?"
This is somewhat tricky, so it's important to follow the logiccarefully, as the computer would. Let's saycount is 3.The first "if" statement will check if 3 is greater than orequal to 1, and since it is, print the first phrase. Thenext "if" will compare count to 2, and print the second phrase.The same thing will happen whencount >= 3 is tested,since 3 is greater than or equal to 3. But the fourth testwill not work, since 3 is not greater than or equal to 4.So the fourth phrase will not be displayed. The phrase willhave been displayed 3 times (once for each of the first three"if" statements), which is what we wanted sincecount is 3.
This new way of writing the program is simpler to verify forcorrectness. We just need to make sure that each number insuccessive "if" statements is one more than the previous number.Since each "if" statement only prints a single line, we don'trisk mis-counting the number of "print" lines as in the firstexample. But it's still somewhat tedious to extend the programto handle higher values ofcount. You have to cut-and-pastetwo lines and remember to increase the number in the "if" statement.
We could make that a little easier with this new version:
print "How many times?" count = input() if count >= 1: print "Are we there yet?" count = count - 1 if count >= 1: print "Are we there yet?" count = count - 1 if count >= 1: print "Are we there yet?" count = count - 1 if count >= 1: print "Are we there yet?" count = count - 1
Now the program is more complicated, but each "if" statement isidentical. That makes cutting and pasting much easier—we cansimply hold down the Ctrl-V key and have a program that handlesvery large values ofcount. Here's how the new program works.The first "if" statement, as before, comparescount to 1and prints the phrase ifcount is greater than or equal to 1.But it also does something else: it decreases the value ofcount by one. This statement:
count = count - 1
does three things: it finds the value ofcount in memory, subtracts1 from it, and puts the result back into memory, replacing the oldvalue ofcount. So ifcount is 3, thecount on theright side is replaced with its value:
count = 3 - 1
then the arithmetic is done:
count = 2
and the new value is stored into memory as before, replacing the 3that was there. You may wonder why only thecount on theright side of the equal sign gets replaced with its value, andnot the left. Why doesn't the computer replace both words withthe value 3, like this:
3 = 3 - 1
Obviously this wouldn't be very useful. The assignment statementonly looks up the existing value of variables when they appearon the right of the equal (assignment) sign. The single variableon the left of the equal sign is used as-is to know what nameto associate with the result of the arithmetic on the right.
So after the first phrase is displayed,count is decreasedby one, and the next "if" is tested. It's the same test, comparingcount with 1. Say thatcount is 3 initially. Atthe first "if" we'll see the phrase displayed andcount will become2. At the second "if" we'll see the phrase andcount will become1. At the third "if" we'll see the phrase andcount will become0. At the fourth "if" the test "0 >= 1" will not be true, so thephrase won't get displayed andcount won't be decreased. Nomatter how many more "if" statements you have after that, thevalue ofcount will stay 0 and none of theprintstatements will run. You'll see the phrase three times, which iswhat we wanted sincecount was 3 originally.
Our program now has one final problem: no matter how many timeswe cut-and-paste these three lines, the user could always entera number that's higher than that. You could have pasted the"if" statement 500 times, and if the user enters "510", your programwill only display the phrase 500 times, once for each "if". Theprogram will end with the variable "count" set to 10, since there are10 more phrases to go, but the last 10 "if" statements won't be there.
We can fix this last problem with aloop, like this:
print "How many times?" count = input() while count >= 1: print "Are we there yet?" count = count - 1
That's the entire program. Specifically, this is awhile loop,because there are several different kinds. We removed all the "if"statements except one, and replaced the wordif with the wordwhile. It almost reads like an English sentence: "Whilecount is greater than or equal to 1, print this phrase anddecreasecount by one." Let's "play computer" withcountinitially set to 3. The computer will get to the "while" statement,compare 3 to 1, see that 3 is greater than or equal to 1, displaythe phrase, decreasecount by 1 (to 2), andloop back upto thewhile statement. Again the computer will comparecountto 1, and since 2 is greater than or equal to 1, it will print thestatement, decrease count to 1, loop back up, comparecount with 1,and since 1 is greater than or equal to 1, display the phrase anddecrease the variablecount to zero. It will then loop back upto the "while" statement, comparecount to 1, and since 0 isnotgreater than or equal to 1, the indented statement will not berun and the "while" loop will finish, moving on to the statementsthat follow. In this program there are no statements that follow,so the program will end. Each time through the loop is calledaniteration.
There are several different types of loops. Which one to use dependsboth on what's available in the programming language you're using andwhich makes the most sense for what you're trying to do. For example,in the example above, we could print the value ofcount in eachiteration, like this:
print "How many times?" count = input() while count >= 1: print "Are we there yet?"print count count = count - 1
Running the program would look something like this (if the usertyped "3" when asked):
How many times?3 (what the user types in) Are we there yet? 3 Are we there yet? 2 Are we there yet? 1
The numbers 3, 2, 1 are the values ofcount at each iteration.What if, instead, just wanted to count upwards? Or what if youdidn't want to modifycount, because you wanted to use itlater on in the program? You could use afor loop, like this:
print "How many times?" count = input()for i = 1 to count: print "Are we there yet?" print count
(Note: So far the language we've used for examples has beensimilar to the popular programming language Python. But Pythonhas no suchfor loop. The above syntax is based on thelanguage Basic.)
Thisfor loop means, "Run the indented statements once foreach value between 1 andcount, and set the variableito that value." If the user enters 3 you'll see this:
How many times?3 (what the user types in) Are we there yet? 1 Are we there yet? 2 Are we there yet? 3
The 1, 2, 3 are the values ofi at each iteration. Notethat we no longer need to decrease the value ofcount ineach iteration. The computer automatically increasesi by1 each iteration until it reachescount. In fact,countis unchanged after the loop finishes. This loop:
for i = 1 to count: print i
is essentially identical to this version:
i = 1 while i <= count: print count i = i + 1
Thefor loop is generally preferable towhile loopswhen you want to cover a range of numbers. It's shorter andeasier to read. Thewhile loop, though, is more flexiblesince you're doing all the work yourself. You could incrementi by 2 at each iteration to see only the odd numbers, oryou could double the value ofi to see all the powers oftwo:
print "What is the maximum?" maximum = input() i = 1 while i <= maximum: print i i = i * 2
What is the maximum?128 (what the user types in) 1 2 4 8 16 32 64 128
You can't do that with a simplefor loop. Incidentally, in afor loopthe starting and ending values (1 andcount in our example) can actually beany pair of numbers. You could do:
for i = 20 to 24: print i
to display the values 20, 21, 22, 23, and 24. The variableiis used here, but any variable could be used.i is a commonly-usedvariable forfor loops; it stands forindex. You couldalso use a variable name that makes more sense in your particularcontext, such as:
for year = 1992 to 2004: print "The year is " + year
Another type of loop is theforeach loop. That'ssimilar to thefor loop except that the variable doesn'tjust go through a numerical range, it's actually set to eachelement in a set of numbers:
foreach year in [1992, 1996, 2000, 2004]: print "The " + year + " Olympic Games."
That also reads almost like an English sentence: "For eachyear in the set 1992, 1996, 2000, 2004, print this statement."(Note: Python does have such afor loop, except thewordfor is used instead offoreach.)
There are a few other types of loops, but they're usuallyvariations on the above three types.