Foundations
Conditionals
Make Decisions
You're building a login system. If the password matches, show the dashboard. Otherwise, show "Invalid password". Programs need to take different paths based on conditions - that's what conditionals do.
Simple if
Execute code only when a condition is true.
x =
if x > 5:
print("x > 5")
if x > 20:
print("x > 20")
x =
if x > 5:
print("x > 5")
if x > 20:
print("x > 20")
x =
if x > 5:
print("x > 5")
if x > 20:
print("x > 20")
The code inside if only runs when the condition is true.
Find the maximum in a list
Scan through all elements, keep track of the largest one found.
nums = [23, 45, 12, 67, 34, 89, 41]
print("nums=" + str(nums))
max = nums[0]
for i in range(1, len(nums)):
if nums[i] > max:
max = nums[i]
Compare each element to our current max. If bigger, update max. This is the find maximum pattern.
Find the minimum in a list
Same idea, but track the smallest.
nums = [23, 45, 12, 67, 34, 89, 41]
print("nums=" + str(nums))
min = nums[0]
for i in range(1, len(nums)):
if nums[i] < min:
min = nums[i]
Same pattern, opposite comparison: update when you find something smaller.
First N Fibonacci numbers
Generate a variable-length Fibonacci sequence.
n =
fib = [0] * n
fib[0] = 0
fib[1] = 1
for i in range(2, n):
fib[i] = fib[i - 1] + fib[i - 2]
print("fib=" + str(fib))
n =
fib = [0] * n
fib[0] = 0
fib[1] = 1
for i in range(2, n):
fib[i] = fib[i - 1] + fib[i - 2]
print("fib=" + str(fib))
n =
fib = [0] * n
fib[0] = 0
fib[1] = 1
for i in range(2, n):
fib[i] = fib[i - 1] + fib[i - 2]
print("fib=" + str(fib))
The user specifies how many Fibonacci numbers they want. The condition i < n controls how many iterations run.
Search for a value in list
Check if a specific number exists.
nums = [23, 45, 12, 67, 34, 89, 41]
target =
print("nums=" + str(nums))
found = 0
position = -1
for i in range(len(nums)):
if nums[i] == target:
found = 1
position = i
nums = [23, 45, 12, 67, 34, 89, 41]
target =
print("nums=" + str(nums))
found = 0
position = -1
for i in range(len(nums)):
if nums[i] == target:
found = 1
position = i
nums = [23, 45, 12, 67, 34, 89, 41]
target =
print("nums=" + str(nums))
found = 0
position = -1
for i in range(len(nums)):
if nums[i] == target:
found = 1
position = i
Loop through, check each element against the target. When found, we can stop early or record the position.