Professional Documents
Culture Documents
LISTS
27 28 By: JMI
LISTS LISTS
LISTS LISTS
LISTS LISTS
LISTS LISTS
nums = [ ]
if not nums: # could also say 'if nums == []'
print("empty")
35 By: JMI 36 By: JMI
LOOPS LOOPS
sample code:
ability to run the same code more than once without writing the same lines of code several times
# writing your first for loop using range
Loops will always run until a condition is met.
for num in range(5):
print( f"Value: {num}")
This loop is essentially counting to five and printing out each number, begins at 0 by default and
assign to temporary variable num
Each time through the loop is what we call an iteration.
above syntax suggests that the loop will run five times.
Every for loop begins with the keyword “for”. Then you define a temporary variable, sometimes
known as a counter or index.
Next is the “in” keyword, followed by the range ( ) function
Lastly, we have a colon : , to end the statement.
All for loops will follow this exact structure of keyword, variable, keyword, function, and colon.
37 By: JMI 38 By: JMI
LOOPS LOOPS
Continue Statement A while loop is generally used when you need to loop based on a condition rather than counting.
Once a continue statement is hit, the current iteration stops and goes back to the top of the loop.. Writing a “while” Loop
sample code: output: It allows us to break out of a loop at any point in time.
# using the continue statement within a foor loop 0
sample code:
for num in range(5): 1
# writing your first while loop
if num == 3: 2
health = 10
continue 4
while health > 0:
print(num) print(health)
Break Statement health -= 1 # forgetting this line will result in infinite loop
Output:
It allows us to break out of a loop at any point in time.
This will continue to print out the value of health until the condition is met. In this case, once health is no longer
sample code: output: greater than zero, the loop stops running. On the last line, we decrement health by one, so each iteration reduces
#breaking out of a loop using the 'break' keyword 0
health closer to zero.
for num in range(5): 1
if num == 3: 2 If we didn’t decrement health at any point in time, this would become an infinite loop (which is bad).
break for loops are generally used when you need to count or iterate over a collection of elements.
print(num) while loops are generally used when doing condition-based looping.
41 By: JMI 42 By: JMI