Author: | Carlos Santos |
Learning Line: | Programming |
Course: | PR1: Introduction to Programming |
Week: | 4 |
Competencies: | Students will be able to effectively define and use variables, programming flow control. |
BoKS: | 3bK2, The student understands the principles of data related software like Python, R, Scala and/or Java and knows how to write (basic) scripts. |
Learning Goals: | Variables and Data Types In-code Comments |
Flow Control – while loop
If statements help you choose is a set of instructions are performed. There is a similar structure, that not only checks if a set of instructions are performed, but, also repeats them while a specific condition is True.
A while loop used a simple condition to determine if a set of instructions are executed, and while that condition is True, it keeps repeating the instructions.
a = 0 # declare a variable a and set it to 0 while a < 10: # repeat the following operations while a is less than 10 print("a current value is "+str(a)) # print value of a a = a + 1 # increment the value of a print("a final value is "+str(a)) # exit the loop and print the final value of a
Explanation: The while loop repeats lines 3 and 4, while the condition (a is less than 10) remains True.
There are a few important things to keep in mind:
- while loops are only executed if the condition is True to start with;
- while create a new scope, and it repeats the execution of this scope while the condition remains True;
- typically while loops manipulate the condition inside of its scope;
- if the condition its always True the loops will continue indefinitely, until it is interrupted externally (for example by forcing application to exit)
Lets make a simple command line application, that accepts commands, until an “exit” command is typed, by the user.
command = "" while command.lower() != "exit": command = input(">").lower() if command == "hi": print("Hello") elif command == "name": print("Robot") print("Bye")
Lets elaborate on this concept to introduce a few more concepts. During a loop you can exit by calling the break
command.
forces the script to abort what it was doing and forces to exit the loop without checking the condition.break
command = "" while command.lower() != "exit": command = input(">").lower() if command == "hi": print("Hello") elif command == "name": print("Robot") elif command == "quit" or command == "bye": break print("Bye")
There is another command called continue
which forces the script to restart the loop in the current state (including the condition) and ignoring the follow up code.
command = "" while command.lower() != "exit": command = input(">").lower() if command == "hi": print("Hello") elif command == "name": print("Robot") elif command == "quit" or command == "bye": break elif command == "?": print("Please type a command.") continue print("DEAD CODE: because this line is preceded by a continue") print("Bye")
For Loop
Of the loop types listed above, Python only implements the last: collection-based iteration. At first blush, that may seem like a raw deal, but rest assured that Python’s implementation of definite iteration is so versatile that you won’t end up feeling cheated!
Shortly, you’ll dig into the guts of Python’s for
loop in detail. But for now, let’s start with a quick prototype and example, just to get acquainted.
Python’s for
loop looks like this:
for <var> in <iterable>: <statement(s)>
<iterable>
is a collection of objects—for example, a list or tuple. The <statement(s)>
in the loop body are denoted by indentation, as with all Python control structures, and are executed once for each item in <iterable>
. The loop variable <var>
takes on the value of the next element in <iterable>
each time through the loop.
Here is a representative example:
>>> a = ['foo', 'bar', 'baz'] >>> for i in a: print(i) foo bar baz
The range()
Function
For example, if you wanted to iterate through the values from 0
to 4
, you could simply do this:
>>> for n in (0, 1, 2, 3, 4): print(n) 0 1 2 3 4
This solution isn’t too bad when there are just a few numbers. But if the number range were much larger, it would become tedious pretty quickly.
Happily, Python provides a better option—the built-in range()
function, which returns an iterable that yields a sequence of integers.
range(<end>)
returns an iterable that yields integers starting with 0
, up to but not including <end>
:
>>> for n in range(4): print(n) 0 1 2 3 4
Range is actually mode elaborate than that. range(<begin>, <end>, <stride>)
returns an iterable that yields integers starting with <begin>
, up to but not including <end>
. If specified, <stride>
indicates an amount to skip between values (analogous to the stride value used for string and list slicing):
range(<end>)
returns an iterable that yields integers starting with 0
, up to but not including <end>
:
>>> for n in range(10,5,-2): print(n) 10 8 6