1.3. Python Basics II: Loopy Logic#

Reference: Chapter 2 of Computational Nuclear Engineering and Radiological Science Using Python, R. McClarren (2018)

1.3.1. Learning Objectives#

After studying this notebook, completing the activities, and asking questions in class, you should be able to:

  • Write and execute an if statement.

  • Write and execute a while loop.

  • Distinguish between when to use an if statement vs. a while loop.

1.3.2. If Statements#

Sometimes you want to execute code differently based on the value of a certain variable. This is most commonly done in if - else constructs. Here’s an example

instructors_opinion = input("What is your opinion of student? ") #'Not annoying'
grade = ''
if (instructors_opinion == 'annoying'):
    grade = 'F+'
elif (instructors_opinion == 'Not annoying'):
    grade = 'B+'
else:
    grade = 'A'
print(grade)
What is your opinion of student?  good
A

What this codes says is that if the value of instructors_opinion is “annoying”, the grade will be “F+”, else if (elif in python-speak) instructors_opinion is “Not annoying” the grade will be “B+”, and anything else will be a grade of “A”. In the example I typed in “Not Annoying” and the if statement and the elif statement require that the string exactly match, so it executed the else part of the code. (Note: This example came from the textbook. Prof. Dowling uses an objective grading scale in this class!)

It is important to remember that when you want to check equality between two things you need to use == and not a single equals sign. A single equals sign is what you use when you want to assign something to a variable.

Home Activity

Rerun the code above. Find input values that cause the program to output “F+”, “B+”, and “A”.

# Add your solution here

Class Activity

Create a small Python program that asks for the student’s weighted final grade (input) and them prints the letter grade per the scale in the class syllabus (output).

# Add your solution here

Branching statements are most powerful when combined with iteration, as we will now explore.

1.3.3. Iteration with While Loops#

Iteration executes a piece of code repeatedly, based on some criteria. In this example we will try to find a good approximation to pi.

#this code finds a decent approximation to pi
import math 
converged = 0
guess = 3.141
iteration = 0
eps = 1.0e-6 #this is my tolerance for approximating pi
converged = math.fabs(guess - math.pi) < eps #0 if false, 1 if true
while (converged == 0):
    guess = guess + eps/2
    converged = math.fabs(guess - math.pi) < eps
    iteration += 1 #same as iteration = iteration + 1
print("Our approximation of pi is", guess)
print("It took us", iteration,"guesses to approximate pi")
Our approximation of pi is 3.1415920000000828
It took us 1184 guesses to approximate pi

In this code, as long as converged == 0 the code in the while block (the indented code below while (converged == 0):) will execute over and over. When the value of our guess is within \(10^{-6}\) of \(\pi\) in absolute value, converged will become 1 and the while loop will stop at the bottom of the code block.

I did something tricky, but useful in this example. In python when a conditional expression like a > b is true it evaulates to an integer of 1, and evaluates to an integer of 0 when false. We will make use of this trick later on and it is good to see it now to help you get accustomed to it.

Home Activity

Copy the pi estimation code to below. Then set the convergence tolerance to 1E-8. How many times more iterations does to take to acheive two addition digits of precision?

# Copy code to here
# Add your solution here

1.3.4. For Loops#

While loops are great and all we really need for iteration, but they are cumbersome if we want to execute a block of code a set number of times. In this case we have to define a counting variable and increment it by hand:

#Some code that counts to ten
count = 1
while (count <= 10):
    print(count)
    count=count+1 #we can also write  count += 1
1
2
3
4
5
6
7
8
9
10

The for loop is built for such a situation.

We will typically specify for loops with the range function. Range takes 3 input parameters: range(start, stop[, step]).

  • start parameter: number, self explanatory.

  • stop parameter: the range function goes to this number before stopping.

  • step parameter: in brackets because it is optional. If you don’t define it assumes you want to count by 1 (i.e., step by 1).

#the list command tells python to explicitly write out the range
print(list(range(1,10))) 
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Also, if you just give range one parameter, it treats that as stop and assumes you want to start at 0:

#These should be the same
print(list(range(0,10)))
print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#Here's something using the step
print(list(range(0,10,2)))
[0, 2, 4, 6, 8]

Home Activity

Print a list of odd numbers that starts at 1 and stops before reaching 9.

# Add your solution here

With the range command we can have a for loop assign a variable a value in the range, in order, each time the code block of the for loop executes:

for i in range(10):
    print(i+1)
1
2
3
4
5
6
7
8
9
10
#for loop count from 10 to 0
for i in range(10,-1,-1):
    print(i)
10
9
8
7
6
5
4
3
2
1
0
#for loop count from 0 to 10
for i in range(11):
    # but prints numbers from 10 to 0
    print(10-i)
10
9
8
7
6
5
4
3
2
1
0

Let’s say we want to add a number to itself 7 times. We could use a for loop:

# for loop version
number = 10
sum = 0
for i in range(7):
    sum += number
print(sum)
70

Home Activity

Write a while loop that does the same thing: add a number (10) to itself 7 times.

# Add your solution here

You can always write a while loop that does the same thing as a for loop. But often we prefer a for loop because the syntax is easier to write, understand, and debug.