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)
A data structure that allows you to associate keys with values.
Dict
These keys are used to create a dictionary
{}
Dict {} Syntax
students = {
“Hermoine”: “Gryffindor”,
“Harry”: “Gryffindor”,
“Ron”: “Gryffindor”,
“Draco”: “Slytherin”,
}
print(students[“Hermoine”])
print(students[“Harry”])
print(students[“Ron”])
print(students[“Draco”])
Parameter that enables results to seperate by a comma (or whatever other character/s are used)
sep=”, “
Sep Syntax
for student in students:
print(student, students[student], sep=”, “)
This keyword is used to define a null value, or no value at all.
None
None Syntax
students = [
{“name”: “Hermoine”, “house”: “Gryffindor”, “patronus”: “Otter”},
{“name”: “Harry”, “house”: “Gryffindor”, “patronus”: “Stag”},
{“name”: “Ron”, “house”: “Gryffindor”, “patronus”: “Jack Russell terrier”},
{“name”: “Draco”, “house”: “Slytherin”, “patronus”: None},
]