Lesson 8-10 Hacks
Hacks for lesson 8 through 10
What is Iteration?: a repeating portion of an algorithm, repeats a specified number of times or until a given condition is met
What is an Iteration Statement?: change the sequential flow of control by repeating a set of statements zero or more times, until a stopping condition is met
What does Repeat Until mean?: if the condition evaluates to true initially, the loop body is not executed at all, due to the condition being checked before the loop
- Define an Iteration
- Make your own example of an iteration with at least 4 steps and a stopping condition(Similar to mine that I did)
- Program a simple iteration.
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('Loop ended.')
for x in range(3):
print(x)
else:
print("Final x = %d" % (x))
def my_range(start, end, step):
while start <= end:
yield start
start += step
for x in my_range(1, 10, 2): # 1 is the starting value of the iteration and 10 is where it will end aka its max. The step is what the list will be printing/going for, for example when I change it to 2 it will start counting by twos from the starting value.
print(x)
- What is an iteration statement, in your own words?
- Create a descending list of numbers using for loop
- Using while loop, make a list of numbers which will form an output of 3,16,29,42,55,68,81
def mylist(start, end, step):
while start <= end:
yield start
start -= step
for x in mylist(3, 81, 4):
print(x)
- Use the list made bellow
- Make a variable to hold the minimum and set it to potential minimum value
- Loop
- Check each element to see if it is less than the minimum variable
- If the element is less than the minimum variable, update the minimum
- After all the elements of the list have been checked, display the minimum value
nums = ["10", "15", "20", "25", "30", "35"]
min_number = None
for number in nums:
if min_number is None or number < min_number:
min_number = number
print(min_number)