control_flow.asciidoc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. [[control_flow]]
  2. == Control Flow
  3. In the programs we have seen till now, there has always been a series of statements faithfully
  4. executed by Python in exact top-down order. What if you wanted to change the flow of how it works?
  5. For example, you want the program to take some decisions and do different things depending on
  6. different situations, such as printing 'Good Morning' or 'Good Evening' depending on the time of
  7. the day?
  8. As you might have guessed, this is achieved using control flow statements. There are three control
  9. flow statements in Python - +if+, +for+ and +while+.
  10. === The +if+ statement
  11. The +if+ statement is used to check a condition: *if* the condition is true, we run a block of
  12. statements (called the _if-block_), *else* we process another block of statements (called the
  13. _else-block_). The *else* clause is optional.
  14. Example (save as +if.py+):
  15. [source,python]
  16. --------------------------------------------------
  17. include::programs/if.py[]
  18. --------------------------------------------------
  19. Output:
  20. --------------------------------------------------
  21. include::programs/if.txt[]
  22. --------------------------------------------------
  23. .How It Works
  24. In this program, we take guesses from the user and check if it is the number that we have. We set
  25. the variable +number+ to any integer we want, say `23`. Then, we take the user's guess using the
  26. `raw_input()` function. Functions are just reusable pieces of programs. We'll read more about them
  27. in the <<functions,next chapter>>.
  28. We supply a string to the built-in `raw_input` function which prints it to the screen and waits for
  29. input from the user. Once we enter something and press kbd:[enter] key, the `raw_input()` function
  30. returns what we entered, as a string. We then convert this string to an integer using `int` and
  31. then store it in the variable `guess`. Actually, the `int` is a class but all you need to know
  32. right now is that you can use it to convert a string to an integer (assuming the string contains a
  33. valid integer in the text).
  34. Next, we compare the guess of the user with the number we have chosen. If they are equal, we print
  35. a success message. Notice that we use indentation levels to tell Python which statements belong to
  36. which block. This is why indentation is so important in Python. I hope you are sticking to the
  37. "consistent indentation" rule. Are you?
  38. Notice how the `if` statement contains a colon at the end - we are indicating to Python that a
  39. block of statements follows.
  40. Then, we check if the guess is less than the number, and if so, we inform the user that they must
  41. guess a little higher than that. What we have used here is the `elif` clause which actually
  42. combines two related `if else-if else` statements into one combined `if-elif-else` statement. This
  43. makes the program easier and reduces the amount of indentation required.
  44. The `elif` and `else` statements must also have a colon at the end of the logical line followed by
  45. their corresponding block of statements (with proper indentation, of course)
  46. You can have another `if` statement inside the if-block of an `if` statement and so on - this is
  47. called a nested `if` statement.
  48. Remember that the `elif` and `else` parts are optional. A minimal valid `if` statement is:
  49. [source,python]
  50. --------------------------------------------------
  51. if True:
  52. print 'Yes, it is true'
  53. --------------------------------------------------
  54. After Python has finished executing the complete `if` statement along with the associated `elif`
  55. and `else` clauses, it moves on to the next statement in the block containing the `if`
  56. statement. In this case, it is the main block (where execution of the program starts), and the next
  57. statement is the `print 'Done'` statement. After this, Python sees the ends of the program and
  58. simply finishes up.
  59. Even though this is a very simple program, I have been pointing out a lot of things that you should
  60. notice. All these are pretty straightforward (and surprisingly simple for those of you from C/C++
  61. backgrounds). You will need to become aware of all these things initially, but after some practice
  62. you will become comfortable with them, and it will all feel 'natural' to you.
  63. .Note for C/C++ Programmers
  64. [NOTE]
  65. There is no `switch` statement in Python. You can use an `if..elif..else` statement to do the same
  66. thing (and in some cases, use a <<dictionary,dictionary>> to do it quickly)
  67. === The while Statement
  68. The `while` statement allows you to repeatedly execute a block of statements as long as a condition
  69. is true. A `while` statement is an example of what is called a *looping* statement. A `while`
  70. statement can have an optional `else` clause.
  71. Example (save as `while.py`):
  72. [source,python]
  73. --------------------------------------------------
  74. include::programs/while.py[]
  75. --------------------------------------------------
  76. Output:
  77. --------------------------------------------------
  78. include::programs/while.txt[]
  79. --------------------------------------------------
  80. .How It Works
  81. In this program, we are still playing the guessing game, but the advantage is that the user is
  82. allowed to keep guessing until he guesses correctly - there is no need to repeatedly run the
  83. program for each guess, as we have done in the previous section. This aptly demonstrates the use of
  84. the `while` statement.
  85. We move the `raw_input` and `if` statements to inside the `while` loop and set the variable
  86. `running` to `True` before the while loop. First, we check if the variable `running` is `True` and
  87. then proceed to execute the corresponding *while-block*. After this block is executed, the
  88. condition is again checked which in this case is the `running` variable. If it is true, we execute
  89. the while-block again, else we continue to execute the optional else-block and then continue to the
  90. next statement.
  91. The `else` block is executed when the `while` loop condition becomes `False` - this may even be the
  92. first time that the condition is checked. If there is an `else` clause for a `while` loop, it is
  93. always executed unless you break out of the loop with a `break` statement.
  94. The `True` and `False` are called Boolean types and you can consider them to be equivalent to the
  95. value `1` and `0` respectively.
  96. .Note for C/C++ Programmers
  97. [NOTE]
  98. Remember that you can have an `else` clause for the `while` loop.
  99. === The +for+ loop
  100. The `for..in` statement is another looping statement which *iterates* over a sequence of objects
  101. i.e. go through each item in a sequence. We will see more about <<sequence,sequences>> in detail in
  102. later chapters. What you need to know right now is that a sequence is just an ordered collection of
  103. items.
  104. Example (save as `for.py`):
  105. [source,python]
  106. --------------------------------------------------
  107. include::programs/for.py[]
  108. --------------------------------------------------
  109. Output:
  110. --------------------------------------------------
  111. include::programs/for.txt[]
  112. --------------------------------------------------
  113. .How It Works
  114. In this program, we are printing a *sequence* of numbers. We generate this sequence of numbers
  115. using the built-in `range` function.
  116. What we do here is supply it two numbers and `range` returns a sequence of numbers starting from
  117. the first number and up to the second number. For example, `range(1,5)` gives the sequence `[1, 2,
  118. 3, 4]`. By default, `range` takes a step count of 1. If we supply a third number to `range`, then
  119. that becomes the step count. For example, `range(1,5,2)` gives `[1,3]`. Remember that the range
  120. extends *up to* the second number i.e. it does *not* include the second number.
  121. Note that `range()` generates a sequence of numbers all at once, so this is safe to use only for
  122. small ranges. If you want a long range but generated only one number at a time, then use
  123. `xrange()`. Lists are explained in the <<data_structures,data structures chapter>>.
  124. The `for` loop then iterates over this range - `for i in range(1,5)` is equivalent to `for i in [1,
  125. 2, 3, 4]` which is like assigning each number (or object) in the sequence to i, one at a time, and
  126. then executing the block of statements for each value of `i`. In this case, we just print the
  127. value in the block of statements.
  128. Remember that the `else` part is optional. When included, it is always executed once after the
  129. `for` loop is over unless a <<the_break_statement,break>> statement is encountered.
  130. Remember that the `for..in` loop works for any sequence. Here, we have a list of numbers generated
  131. by the built-in `range` function, but in general we can use any kind of sequence of any kind of
  132. objects! We will explore this idea in detail in later chapters.
  133. .Note for C/C++/Java/C# Programmers
  134. [NOTE]
  135. --
  136. The Python `for` loop is radically different from the C/C++ `for` loop. C# programmers will note
  137. that the `for` loop in Python is similar to the `foreach` loop in C#. Java programmers will note
  138. that the same is similar to `for (int i : IntArray)` in Java 1.5.
  139. In C/C++, if you want to write `for (int i = 0; i < 5; i++)`, then in Python you write just `for i
  140. in range(0,5)`. As you can see, the `for` loop is simpler, more expressive and less error prone in
  141. Python.
  142. --
  143. [[the_break_statement]]
  144. === The break Statement
  145. The `break` statement is used to *break* out of a loop statement i.e. stop the execution of a
  146. looping statement, even if the loop condition has not become `False` or the sequence of items has
  147. not been completely iterated over.
  148. An important note is that if you *break* out of a `for` or `while` loop, any corresponding loop
  149. `else` block is **not** executed.
  150. Example (save as `break.py`):
  151. [source,python]
  152. --------------------------------------------------
  153. include::programs/break.py[]
  154. --------------------------------------------------
  155. Output:
  156. --------------------------------------------------
  157. include::programs/break.txt[]
  158. --------------------------------------------------
  159. .How It Works
  160. In this program, we repeatedly take the user's input and print the length of each input each
  161. time. We are providing a special condition to stop the program by checking if the user input is
  162. `'quit'`. We stop the program by *breaking* out of the loop and reach the end of the program.
  163. The length of the input string can be found out using the built-in `len` function.
  164. Remember that the `break` statement can be used with the `for` loop as well.
  165. .Swaroop's Poetic Python
  166. **************************************************
  167. The input I have used here is a mini poem I have written:
  168. [verse]
  169. Programming is fun
  170. When the work is done
  171. if you wanna make your work also fun:
  172. use Python!
  173. **************************************************
  174. [[the_continue_statement]]
  175. === The +continue+ Statement
  176. The `continue` statement is used to tell Python to skip the rest of the statements in the current
  177. loop block and to *continue* to the next iteration of the loop.
  178. Example (save as `continue.py`):
  179. [source,python]
  180. --------------------------------------------------
  181. include::programs/continue.py[]
  182. --------------------------------------------------
  183. Output:
  184. --------------------------------------------------
  185. include::programs/continue.txt[]
  186. --------------------------------------------------
  187. .How It Works
  188. In this program, we accept input from the user, but we process the input string only if it is at
  189. least 3 characters long. So, we use the built-in `len` function to get the length and if the length
  190. is less than 3, we skip the rest of the statements in the block by using the `continue`
  191. statement. Otherwise, the rest of the statements in the loop are executed, doing any kind of
  192. processing we want to do here.
  193. Note that the `continue` statement works with the `for` loop as well.
  194. === Summary
  195. We have seen how to use the three control flow statements - `if`, `while` and `for` along with
  196. their associated `break` and `continue` statements. These are some of the most commonly used parts
  197. of Python and hence, becoming comfortable with them is essential.
  198. Next, we will see how to create and use functions.