for loop in Python
number of enemies is 8
for i in range(a, b, x):
print(i)
a: start of range (inclusive)
b: end of range (exclusive)
x: the step (i.e., how much to add to i in each iteration of the loop. You can even go backwards.
You can use in-place operators to increase or decrease a variable by any amount.
+=
-=
Notes:
-The body of a for-loop must be indented, otherwise you’ll get a syntax error.
-Every line in the body of the loop must be indented in the same way; we use the “4 spaces” convention. Pressing the <tab> key should automatically insert 4 spaces.
-Whitespace matters in Python.</tab>
example:
for i in range(0, 10):
print(i)
output: 2 variables
0
1
2
3
4
5
6
7
8
9
example: 3 variables
for i in range(3, 0, -1)
print(i)
output:
3
2
1
example: in-place operators:
number_of_enemies = 10
number_of_enemies += 2
number_of_enemies = 10
number_of_enemies -= 2
def sum_of_numbers(start, end):
total = 0
for i in range(start, end):
total += i
return total
While Loop
(…continuing)
A loop that continues while a condition remains True.
Hardcoded example:
While 1:
print (“1 evaluates to True”)
prints:
#1 evaluates to True
While Loop Condition as a Comparison or Variable Example (more common than hardcoded):
num = 0
while num < 3:
num += 1
print(num)
prints:
# 1
# 2
# 3
# loop stops when num >= 3
continue vs break
continue: use to skip to the next iteration in a loop
example: calculate square roots but skip the negative numbers.
numbers = [16, -4, -9, 36, 0, 49]
for number in numbers:
if number < 0:
continue # Skip negatives to avoid complex numbers
print(f”The square root of {number} is {number ** 0.5}.”)
break: exit the loop entirely
Example:
for n in range(42):
print(f”{n} * {n} = {n * n}”)
if n * n > 150:
break
This code would loop from 0 all the way to 41, but it will exit before it gets to 41. Once n*n is greater than 150, the break statement executes, stopping the loop.
Practice Problem: We need a timer to countdown the start of PvP matches in Fantasy Quest.
def countdown_to_start():
for i in range(10, 0, -1):
if i == 1:
print(f”{i}…Fight!”)
else:
print(f”{i}…”)
In loops, Python returns the last value in the running accumulation
Example:
def sum_of_numbers(start, end):
total = 0
for i in range(start, end):
total += i
return total
total = 0
total += i
So
0+0=0
0+1=1
1+2=3
3+3=6
6+4=10
python returns 10 (as in 6+4=10). It just returns the last value in the running accumulation.
List
Some languages call lists arrays, but in python, we call just call them lists.
Strings, numbers, and boolean values can be stored in lists.
Examples:
inventory= [“Iron Breastplate”, “Healing Potion”, “Leather Scraps”]
flower_types = [
“daffodil”,
“rose”,
“chrysanthemum”
*You can declare the list using multiple lines if wanted. This is advised if there are so many that it’s hard to read all items on the same line of code.
Counting in Programming
We start counting at 0 as opposed to 1.
Example:
names = [“Bob”, “Lane”, “Alice”, “Breanna”]
Q: Which index refers to the second in a list?
A: 1
How to access items in a list
Example: Access the “Leather Scraps” item in the below list.
def get_leather_scraps():
inventory = [
“Healing Potion”,
“Leather Scraps”,
“Iron Helmet”,
“Bread”,
“Shortsword”,
]
item_index = 1
return inventory[item_index]
Give an example of when Python will return an error code of IndexError
If you try to access a list with fewer than 2 items using inventory[1]
Python evaluates “and” from left to right. Give an example of when this is something that you need to keep in mind.
Example:
Technically both of the following options work, but option 2 is safer. Why?
Option 1: if inventory[1] == “Iron Ore” and len(inventory) >= 2:
Option 2: if len(inventory) >= 2 and inventory[1] == “Iron Ore”:
In Python, and evaluates left to right and short-circuits. Your first version evaluates inventory[1] first. If the list is shorter than 2, that access raises IndexError before Python ever checks len(inventory) >= 2. So it can crash.
The safe version puts the length check first: len(inventory) >= 2 and inventory[1] == “Iron Ore”. If the list is too short, the second part isn’t evaluated at all, preventing the out-of-range access.
So it’s about avoiding an exception by guarding the index access.
Condition Flow
The sequence structure of checks.
Example:
Full solution code: if len(inventory) >= 2 and inventory[1] == “Iron Ore”:
Condition flow:
First check length.
Then, only if safe, check the value.
Then, perform the assignment.
appending in python
Fill a list with values using a loop.
It’s common to create an empty list and then fill it with values using a loop.
Example:
cards = []
cards.append(“nvidia”)
cards.append(“amd”)
When to use if, while, or break
You use if when you want to execute code only if a certain condition is met.
A while loop is used when you want to repeat a block of code as long as a certain condition remains true. It’s often used when you don’t know in advance how many times you’ll need to repeat something.
The break statement allows you to immediately exit a loop (either for or while) even if the loop’s normal termination condition hasn’t been met. You use break when you find what you’re looking for or hit a critical condition that means there’s no point in continuing the loop.
No-Index Syntax
output:
If you only need to access the value of an item in a list–and don’t need to update the item, you can do the following.
That is, you can use the no-index syntax when you don’t need to know the index, just the value.
“to not need the index” means you never use the numeric position (0, 1, 2, …) of each element during the loop.
example:
trees = [‘oak’, ‘pine’, ‘maple’]
for tree in trees:
print(tree)
oak
pine
maple
Practice Question: If you don’t need the index, which method of writing-for-loops is considered more “clean”?
for item in items
for i in range(0, len(items))
for item in items
When do you use the no-index syntax vs index syntax?
Use the no-index system when you just read/process each value.
Examples:
Q: You need to log each username as-is. Do you need the index?
A: No, use
for users in users
Q: When appending doubled values to a new list (i.e., not mutating the original), which do you use?
a) for n in nums
b) for i in range(len(nums))
A: a
Use the index syntax when you need the numeric position (0, 1, 2, …) of each element during the loop to:
-modify items by index
-skip/replace based on position
-look ahead/behind using i
Examples:
Q: You must prefix each username with its position like “O:alice”. Which of the following loop styles is correct?
a) for users in users
b) for i, user in enumerate(users)
A: b
Q: You need to double every number in a list in place(i.e., mutate the list). Which loop?
a) for n in nums
b) for i in range(len(nums))
A: b
Why does indentation matter in python?
In Python, indentation defines block scope. A return inside the loop’s block ends the function immediately during the first iteration that reaches it.
Conceptually:
Inside loop block = “do this each iteration”
After loop block = “do this once when the loop is done”
Example:
Inputs: [1, 200, 300, 4, 5]
def find_max(nums):
max_so_far = float(“-inf”)
for num in nums:
if num > max_so_far:
max_so_far = num
return max_so_far
output: 300
BUT
def find_max(nums):
max_so_far = float(“-inf”)
for num in nums:
if num > max_so_far:
max_so_far = num
return max_so_far
output: 1 BECAUSE return max_so_far is inside the loop’s block and ends the function during the first iteration (1) that reaches it.
%
modulo operator. % can be used to find the remainder of a division operation.
Divide by 2 using the modulo to determine if a number is even or odd.
If you get zero, it’s even (i.e., no remainder).
If you get a number that is not zero, it’s odd (i.e., it has a remainder).
Example:
8 % 3
output=2
Because 3 goes into 8 two times (equaling 6) and 8-6 is 2. So, there is a remainder of 2.
Slicing Lists
get all items from the start up to (but not including) the index noted in stop
Syntax:
my_list[ start : stop : step ]
start: where to start the slice. Inclusive so the first number is included.
stop: where to stop the slice. Exclusive so the last number is not included.
step: increment. If negative, the list is returned in reverse order.
Syntax to Omit Sections:
my_list[ : stop]
ex//numbers[ : 3] means get all items from start up to but not including index 3
my_list[start: ]
ex// numbers[3: ] means get all items from index 3 to the end.
my_list[ : :step]
ex//
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[ : : 2]
output: [0, 2, 4, 6, 8]
Other examples:
del strongholds[0]
#Deletes the item at index 0 (the first element).
After this, all remaining items shift left by one index.
del strongholds[-2:]
#Slices from the second-to-last element to the end.
With a positive (default) step, [-2:] means “take the last two elements.”
Deleting that slice removes both final items, regardless of list length.
Delete the slice that would read the list backward from the last item down to (but not including) index 2.
del strongholds[-1 : 2 : -1]
“True” vs True
“False” vs False
With “” is a string.
Without “” is a boolean value.
Tuples
Tuples are collections of data that are ordered and unchangeable. You can think of a tuple as a List with a fixed size. Tuples are created with round brackets:
my_tuple = (“this is a tuple”, 45, True)
print(my_tuple[0])
# this is a tuple
print(my_tuple[1])
# 45
print(my_tuple[2])
# True
While it’s typically considered bad practice to store items of different types in a List, it’s not a problem with Tuples. Because they have a fixed size, it’s easy to keep track of which indexes store which types of data.
Tuples are often used to store very small groups (like 2 or 3 items) of data. For example, you might use a tuple to store a dog’s name and age.
dog = (“Fido”, 4)
There is a special case for creating single-item tuples. You must include a comma so Python knows it’s a tuple and not regular parentheses:
dog = (“Fido”,)
Because Tuples hold their data, multiple tuples can be stored within a list. Similar to storing other data in lists, each tuple within the list is separated by a comma. When accessing a list of tuples, the first index selects which tuple you want to access, the second selects a value within that tuple.
my_tuples = [
(“this is the first tuple in the list”, 45, True),
(“this is the second tuple in the list”, 21, False)
]
print(my_tuples[0][0]) # this is the first tuple in the list
print(my_tuples[0][1]) # 45
print(my_tuples[1][0]) # this is the second tuple in the list
print(my_tuples[1][2]) # False
Tuple Unpacking
You can easily assign the values of a tuple to variables using unpacking.
dog = (“Fido”, 4)
dog_name, dog_age = dog
print(dog_name)
# Fido
print(dog_age)
# 4
Exponent
**
Addition
+
Division
/