You can drive a tractor
PHOT 110: Introduction to programming
LECTURE 03
Michaël Barbier, Spring semester (2023-2024)
if
code-block is executed when the condition is True
else
code-block is executed when the condition is False
elif
keyword acts as a else if
elif
statements can follow an if
, with an optional else
if
code-block is executed when the condition is True
if
code-block is executed when the condition is True
if
code-block is executed when the condition is True
else
code-block is executed when the condition is False
if
code-block is executed when the condition is True
else
code-block is executed when the condition is False
elif
keyword acts as a else if
if
code-block is executed when the condition is True
Repeats code-block until the condition is False
A while
loop is used when:
Repeats code-block until the condition is False
A while
loop is used when:
Repeats code-block until the condition is False
Can get in an infinite loop !
Ctrl
+ c
len()
function: len(a_list)
# Printing the first and then the second element
a_list = ["First", False, 34, 23.4]
print(a_list)
print(f"The length of the list = {len(a_list)}")
a_list.append("extra_element")
print(a_list)
print(f"The length of the adapted list = {len(a_list)}")
['First', False, 34, 23.4]
The length of the list = 4
['First', False, 34, 23.4, 'extra_element']
The length of the adapted list = 5
the_list.append(the_element)
a_list[element_index]
a_list[element_index]
a_list[start:stop_exclusive]
a_list[start:stop_exclusive]
a_list[start:stop_exclusive]
a_list[start:stop_exclusive:step]
for
loop can be used when:
for
loop can be used when:
range
is a sequence type (like list
) for integer numbersrange(start, stop_exclusive, step)
for
loopfor
loop can be used when:
for
loop can be used when:
# Load library for sine and cosine
import math
# Algorithm parameters in MKS units
v0 = 6
angle_in_degrees = 37
g = 9.81
x = 0; y = 1.20; t = 0
# Calculate initial velocity in x
# and y directions
angle = angle_in_degrees * math.pi/180
vx = v0 * math.cos(angle)
vy = v0 * math.sin(angle)
# Initiate values at time t = 0
x_values = list([x])
y_values = list([y])
t_values = list([t])
dt = 0.1
while (y >= 0) and (t < 10):
# update velocities (vx, vy), coords
# (x, y), and time t
vy = vy - g*dt
y = y + vy*dt
x = x + vx*dt
t = t + dt
x_values.append(x)
y_values.append(y)
t_values.append(t)
print(f't = {t:.2f}: ({x:.2f},{y:.2f})')
t = 0.10: (0.48,1.46)
t = 0.20: (0.96,1.63)
t = 0.30: (1.44,1.69)
t = 0.40: (1.92,1.66)
t = 0.50: (2.40,1.53)
t = 0.60: (2.88,1.31)
t = 0.70: (3.35,0.98)
t = 0.80: (3.83,0.56)
t = 0.90: (4.31,0.04)
t = 1.00: (4.79,-0.58)
Comparison with exact trajectory obtained before
while
/for
loopsfor
loop: iterating over list elementsLecture 03: while, for, lists, and iterators