Computational Methods in Physics ASU Physics PHY 494

04 Introduction to Python II — Flow control

We 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 and while
  • 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

# temperature conversion

temperatures = [60.1, 78.3, 98.8, 97.1, 101.3, 110.0]
for theta in temperatures:
   T = (theta - 32) * (5/9) + 273.15
   print(T)
   
print("Conversion complete")

and run it1

python temperatures.py

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 and VARIABLE is set to this element.
  • White-space indentation demarcates a block: Convention: Use 4 spaces for each indentation level (not TABS)
Activity: for loop
  1. create temperature.py as above and run it
  2. modify temperature.py so that the results are stored in a new list temp_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

for i in range(7):
    print(i)

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:

for i in range(1, 7, 2):
    print(i)

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)

# temperature conversion

temperatures = [60.1, 78.3, 98.8, 97.1, 101.3, 110.0]
temp_Kelvin = []
for theta in temperatures:
   T = (theta - 32) * (5/9) + 273.15
   temp_Kelvin.append(T)

# show T in F and K side by side
# ...

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:

# countup.py

tmax = 10.
t, dt = 0, 2.

while t <= tmax:
   print("time " + str(t))
   t += dt
print("Finished")

Example: The program fibonacci.py will compute the Fibonacci series

up to Fmax:

# fibonacci.py

Fmax = 100
a, b = 0, 1

while b < Fmax:
   print(b, end=' ')
   a, b = b, a+b
print()

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

# Heaviside step function

x = 3
theta = None
if x < 0:
   theta = 0.
elif x == 0:
   theta = 0.5
else:
   theta = 1.

print("Theta(" + str(x) + ") = " + str(theta))

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:

# guessinggame.py

number = 42   # secret number
guess = int(input("Guess the number: "))

# add more code here...

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.)

import random

number = random.randint(1, 1000)  # secret integer number between 1 and 1000

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:

# guess.py

import random

number = random.randint(1, 1000)  # secret integer number between 1 and 1000

n_guesses = 0
guess = int(input("Guess the number between 1 and 1000: "))

# add code
   
print("Congratulations, you guessed the number", number, "in", n_guesses, "guesses")

Footnotes

  1. Remember, in ipython you can also run the program with %run temperatures.py

  2. 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 

  3. We will try a software engineering technique called pair programming (borrowed from agile/extreme programming)

    1. Split into teams of 2. (Be nice. Introduce yourselves.)
    2. Sit next to each other at one desk.
    3. Decide whose laptop you are going to use.
    4. Flip a coin to decide who will start out as the navigator and who will be the driver.
    5. 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
    6. Switch roles every ~5 minutes