Lecture 2 - Loops Flashcards
A way to do something over and over again.
Loops
a type loop will repeat a block of code over and over again
While
While Syntax
i = 3
while i != 0:
print(“meow”)
When you get stuck in a loop that executes forever, you can press ________________ on your keyboard to break out of the loop.
Control + C
One cycle through a loop
Iteration
This loop iterates through a list of items.
For
Data type used to store multiple items in a single variable.
List
For Syntax
for i in [0, 1, 2]:
print(“meow”)
This function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
Range()
Range() Syntax
Range(start, stop, step)
This keyword explicitly tells Python to go to the next iteration of a loop.
Continue
This keyword tells Python to “break out” of a loop early before it has finished all of its iterations
Break
Continue & Break Syntax
while True:
n = int(input(“What’s n? “))
if n < 0:
continue
else:
break
This function returns the number of items in an object.
Len()
Len() Syntax
mylist = [“apple”, “banana”, “cherry”]
x = len(mylist)