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
Goals:
if statements to control whether a block of code is executedif statement (more properly called a conditional statement) controls whether some block of code is executed or notif and ends with a colon# 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!!')
input() statement inside a int() function to convert the returned string into an integer that we can use with the > operator.else to execute a block of code when an if condition is not trueif statements can stand alone (as in the first example), or they can be combined with an else statement.else statement allows us to run an alternative code block when the if condition is false.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')
elif to specify additional testselif is short for "else if"elif statement must come after the if statement and before and else statement (if one is used)elif statements, the else statementis a "catch all" and is executed if none of the if or elif statements are truetemp = 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.')
if, elif and else statements matters. The following code scrambles the order of the conditional checks.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!!')
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")
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)
```
Classify a number.
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]
Example: Finding the max or min of a list
max_value is initially assigned to the first element in the listmax_value, the max_value is assigned to that elementRun 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_valuesy_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
count. The statement count += 1 is shorthand for count = count + 1n_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")
found to be False (since the number is not found before we start looking).found variable to True.break command. This command exits the for loop immediatelynumbers = [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)
Write a program that detects peaks in a time series.
y made at times ty[0] and y[-1] should not be considered as being local peaks since it is not possible to compare their values to both neighbors.y and t values, just print them outBefore 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
Write a guessing game program.
if statements to control whether a block of code is executed based on some conditionelse or elif statements to provide additional testsThis tutorial is a modified adaptation of "Python for Physicists"