04 Introduction to Python II — Flow control
24 Jan 2019We are continuing from
the previous lesson in the "work directory"
~/PHY494/04_python
. We will use ipython
and your text editor.
Flow control
Flow control is essential for any programming language.
- loops:
for
andwhile
- conditionals:
if ... elif ... else
- exceptions:
try ... except
(will be discussed another time)
Loops
Computers are excellent at repeating instructions. Looping constructs are used to repeat a block of code for a fixed number of iterations or until a given condition is met.
The for
loop
Example: Convert all the measured temperatures from Fahrenheit to Kelvin, using a for loop.
Create a python program temperatures.py
and run it1
to yield
288.76111111111106
298.8722222222222
310.26111111111106
309.31666666666666
311.65
316.4833333333333
Conversion complete
Note:
for VARIABLE in SEQUENCE
is the for-loop in Python.- The body of the for loop is executed for each element in
SEQUENCE
andVARIABLE
is set to this element. - White-space indentation demarcates a block: Convention: Use 4 spaces for each indentation level (not TABS)
Activity: for loop
- create
temperature.py
as above and run it - modify
temperature.py
so that the results are stored in a new listtemp_Kelvin
Loops with range()
The range() "function" provides "standard" (as in e.g., C) for-loop behavior:
range(stop)
iterates through 0, 1, 2, …, stop-1
and gives 0 1 ... 5 6
whereas range(start, stop, step)
iterates through start, start+step,
start+2*step, … with the last element less than stop:
yielding 1 3 5
.
Activity: range()
Add code to temperature2.py
(below) to print a
table of the temperature in F and in K side by side by iterating
through the lists temperatures
and temp_Kelvin
simultaneously. (Hint: You can use len()
and range()
2)
The while
loop
The
while loop
(see also the
while loop in the Python Tutorial)
iterates until a condition is False
.
Example: The program countup.py
will run until t
has exceeded a preset
value tmax
:
Example: The program fibonacci.py
will compute the
Fibonacci series
up to Fmax
:
Before running fibonacci.py
, let's try to anticipate what the code
will do. We will then run the code. If we get the expected results
then, great!, otherwise: try to figure out why.
Anticipating results and comparing to the run afterwards is the scientific method applied to programming. It is essential if you want to become a good programmer.
Conditionals
Any programming language needs to be able to make decisions. Python has the if statement.
Example: Consider an implementation of the Heaviside step function
as heaviside.py
Activity: Step function
Run heaviside.py
for various values of x
(at least -3, 0, 3) and
test the output against the mathematical definition.
Activity: Guessing game I
Write a program that takes a number guess
as input and compares it to a
preset number number
. Tell the player if their guess was "too low",
"too high", or that they "guessed the number". You can start with the
code below:
BONUS: If you want to enhance this code you can try to generate a random number using the random.randint() function. (You will learn more about importing modules and functions later in this lesson.)
Activity: Guessing game II
Perform this activity using pair programming3.
Enhance the simple guessing game from the previous exercise so that the player can guess repeatedly. Count the number of guesses and print them once the player guesses correctly.
You can use the following incomplete code as a starting point:
Footnotes
-
Remember, in
ipython
you can also run the program with%run temperatures.py
. ↩ -
If you already know how to solve the problem with
len()
,range()
, and indexing, try to figure out how to do it more elegantly with the zip() function ↩ -
We will try a software engineering technique called pair programming (borrowed from agile/extreme programming)
- Split into teams of 2. (Be nice. Introduce yourselves.)
- Sit next to each other at one desk.
- Decide whose laptop you are going to use.
- Flip a coin to decide who will start out as the navigator and who will be the driver.
- Roles:
- driver: keyboard & types
- navigator reads code, provides directions, catches bugs
- Both constantly talk to each other: comment on what you're typing, comment on what is being typed
- Switch roles every ~5 minutes