08-control-flow.pd 13 KB

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