πŸ““ About This Tutorial

This webpage is a static view of an interactive Jupyter Notebook tutorial. To get the full interactive experience where you can run Python code, modify examples and complete exercises, click the "Open in Colab" button. This will access the Google Colab notebook from a GitHub repository github.com/dchappell2/Computational-Physics and open it in Google Colab. You will need a Google account if you want to open it in Colab.

Note: You can download a pdf of the lecture slides for this chapter here: Chapter 6 slides

Chapter 6 - If Statements

Goals:

6.0 Use if statements to control whether a block of code is executed

# prompt user to enter the temperature in F
temp = int(input("Enter a temperature in F:  "))

# See if the temp is greater than 90 F or not
if temp > 90:
    print(temp,'is too hot!!')

6.2 Use else to execute a block of code when an if condition is not true

Let's extend our code above to make it more general. We'll add a print statement if the if condition fails (i.e. if the temperature is less than or equal to 90 F). Again, try running the code for a few input temperatures and see if the output makes sense.

# prompt user to enter the temperature in F
temp = int(input("Enter a temperature in F:  "))

# See if the temp is greater than 90 F or not
if temp > 90:
    print(temp,'is too hot!!')
else:
    print(temp,'is not too hot')

6.3 Use elif to specify additional tests

πŸ”† Example: Temperature classification

temp = int(input("Enter a temperature in F:  "))        # temperature in F

# Classify temperature. Temp divisions:  32, 60, 90
if temp > 90:
    print(temp,'is too hot!!  Spend the day at the beach.')
elif temp > 60:
    print(temp,'is nice. Go outside and play.')
elif temp > 32:
    print(temp,'is chilly. Wear a jacket')
else:
    print(temp,'is too cold!!  Stay inside and code Python.')

βœ… Skill Check 1

temp = int(input("Enter a temperature in F:  "))        # temperature in F

if temp > 40:      # if temperature is > 40, print the following
    print(temp,'is chilly')
elif temp > 70:    # else if temperature is > 70, print the following
    print(temp,'is nice')
elif temp > 90:    # else if temperature is > 90, print the following
    print(temp,'is too hot!!')
else:              # otherwise, print the following
    print(temp,'is too cold!!')

🟩

6.5 Comparison (i.e. relational) and Boolean operators

In addition to > and <, Python offers the following comparison (i.e. relational) operators:

#    ==   Equality operator          x == y     True if x equal y
#    !=   Not equal                  x != y     True if x is not equal to y
#    >    Greater than               x > y      True if x is greater than y
#    <    Less than                  x < y      True if x is less than y
#    >=   Greater than or equal to   x >= y     True if x is greater than or equal to y
#    <=   Less than or equal to      x <= y     True if x is less than or equal to y
#    is   same object (identity)     a is b     True if a and b are the same object (not just numerically equal)
#    in   membership                 a in b     True if a is in b

These comparisons result in True/False states, which can be further combined with the following Booelan operators:

#    and    logical AND      x and y     True if BOTH x and y are True
#    or     logical OR       x or y      True if EITHER x or y are True
#    not    logical NOT      not x       True if x is False

Each of these comparisons results in a True or False Boolean. Run the following:

2 > 1

Try this one:

(1>2) or (2<3)

And one more:

not (1<2)

Here are some examples of using comparisons in if statements:

A = [0, 10, 20, 40, 100]
x = 10

if x >= A[0] and x < A[2]:
    print("first condition is true")

if x == A[1]:
    print("second condition is true")

if x in A:
    print("third condition is true")

if not(999 in A):
    print("fourth condition is true")

βœ… Skill Check 2

Determine whether each of the following conditions produces True or False without executing the code. Create a Text Cell to type your answers.

```

4 > 3

2-1 == 3-2

(46 > 55) or 2>1

(2>1) and (3>1) and (4>1) and (4>5)

```

βœ… Skill Check 3

Classify a number.

βœ… Skill Check 4

The x and y coordinates for 8 points are given in the code cell below.

```

( 2, 8) quadrant I

(-4, 2) quadrant II

(-2, 0) x axis

```

x = [2, -4, -2, -5, 1, -6,  3, -2]
y = [8,  2,  0,  4, 9, -3, -3,  0]

6.6 Coding Patterns: If statements used inside loops

πŸ”† The Update (or Replacement) Pattern updates old information with new

Example: Finding the max or min of a list

Run the following Code Cell to try it out.

vlist = [3, 7, 9, -5, 27, -2, 12]  # define a list of numbers

max_v = vlist[0]                   # initialize max_value to the first element of the list

for v in vlist:                    # loop over numbers in the list
    if v > max_v:                  # check if the current number is greater than max_val
        max_v = v                  # if the condition is true, update max_val to current number

print("maximum value = ", max_v)   # print out the max value in the list

A second example loops through a Python list to calculate the difference between consecutive pairs of elements.

y_values = [0, 1, 5, 4, 2, 0]    # define a list of numbers

y_old = y_values[0]              # initialize old time to the first element
y_new = y_values[0]              # initialize new time to the first element

for y in y_values[1:]:           # loop over times, starting with 2nd element
    y_old = y_new                # current "old" time = previous "new" time
    y_new = y                    # current "new" time = current time in the loop

    diff = y_new - y_old         # Calc difference between new and old
    print("diff = ",diff)        # display difference

πŸ”† The Count Pattern counts how many times a feature is found

n_cats = [0,1,5,0,1,1,3,4,10]    # number of cats owned

count = 0                        # initialize count

threshold = 3                    # threshhold = minimum number of cats to sesarch for
for cats in n_cats:              # loop over numbers in the list
    if cats >= threshold:        # check if the current number is greater than max_val
        count += 1               # if the condition is true, update max_val to current number

print(count," people in the list own at least",threshold,"cats")

βœ… Skill Check 5

πŸ”† The Search Pattern loops through a list until a feature is found

numbers = [3,5,9,11,15,19,24]   # define a list of numbers
target = 15                     # target = number to search for in list

found = False                   # found = Boolean variable that equals false until a match is found
for nbr in numbers:             # loop over numbers in the list
    if nbr == target:           # check if the current number is equal to target
        found = True            # if the condition is met, set found to True
        break                   # exit the loop and stop searching

if found:
    print("numbers list contains",target)
else:
    print("numbers list does not contain",target)

βœ… Skill Check 6

Write a program that detects peaks in a time series.

Before you start coding, think about which design pattern(s) are relevant to this problem. Which will you use?

Enter your answer here:

y = [0, 0.2, 0.5, 1.2, 2.4, 2.0, 0.4, 0.1, 0.2, 0.7, 1.3, 0.9, 0.2]   # y measurements
t = [0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12]   # times

βœ… Skill Check 7

Write a guessing game program.

Key Points

This tutorial is a modified adaptation of "Python for Physicists"

Β© Software Carpentry