115 lines
2.5 KiB
Python
115 lines
2.5 KiB
Python
"""
|
|
In this example, we are covering control flow in python
|
|
|
|
|
|
Control flow at its lowest level lets us control the execution of code depending on data
|
|
"""
|
|
|
|
|
|
"""
|
|
If statements are the most basic form of control flow, and allow us to conditionally execute code depending on a boolean
|
|
expression
|
|
"""
|
|
|
|
age = 18
|
|
|
|
if age >= 18:
|
|
# When the age is greater or equal to 18, this code is run
|
|
print("You are an adult")
|
|
elif age >= 13:
|
|
# Otherwise, when the age is greater or equal to 13, this code is run
|
|
# you can chain multiple of these 'elif' conditions if you want
|
|
print("You are a teenager")
|
|
else:
|
|
# And if neither of the above run, this else block is run
|
|
print("You are a literal child")
|
|
|
|
|
|
|
|
|
|
bank_balance = 10000
|
|
age = 27
|
|
|
|
|
|
# Below, write the code for a bank to check if you are entitled to a mortgage
|
|
# For sake of example, lets say you can get a mortgage when both:
|
|
# a) You are above 25 years old
|
|
# b) You have over 50,000 in the bank
|
|
# You can just print "Entitled" or "Not Entitled"
|
|
|
|
|
|
|
|
|
|
# ^ Your code above here ^
|
|
|
|
|
|
|
|
"""
|
|
While loops are another critical part of control flow
|
|
|
|
they allow you to execute a block of code for as along as a boolean expression holds true
|
|
"""
|
|
|
|
|
|
"""
|
|
The below code keeps on doubling a number until it passes a million
|
|
"""
|
|
|
|
number = 1
|
|
doubles_needed = 0
|
|
|
|
while number < 1000000:
|
|
# Double the number
|
|
number = number * 2
|
|
doubles_needed = doubles_needed + 1
|
|
|
|
print("You needed to double", doubles_needed, "times to reach a million")
|
|
|
|
|
|
# Exercise:
|
|
# Below, write the code to perform an integer multiplication without using the python multiplication symbol *
|
|
# You can use the fact that multiplication is a repeated addition to help you
|
|
|
|
number = 23
|
|
times = 4
|
|
result = 0
|
|
|
|
# ^ Write your code above ^
|
|
|
|
|
|
"""
|
|
For loops are the final bit of control flow we are covering today
|
|
|
|
technically, we do not need them as you can do anything that needs a for loop with a while loop
|
|
"""
|
|
|
|
vegetables = ["Carrot", "Lettuce", "Broccoli", "Cauliflower"]
|
|
|
|
|
|
for vegetable in vegetables:
|
|
print(vegetable)
|
|
|
|
|
|
# The above loop can be written as
|
|
|
|
index = 0
|
|
while index < len(vegetables):
|
|
vegetable = vegetables[index]
|
|
print(vegetable)
|
|
|
|
index = index + 1
|
|
|
|
# But obviously, the for loop looks much nicer
|
|
|
|
|
|
|
|
# For this next exercise, I will provide you with a list of numbers
|
|
# I want you to create a for loop to square each one, and add it to a new list
|
|
# You will need a for loop and the list.append() method
|
|
|
|
|
|
numbers = [11, 75, 41, 26, 52, 39]
|
|
squared = []
|
|
|
|
|
|
|