Before you update a variable, you have to initialize it. a common way to update a variable is by incrementing it, adding, or decrementing, subtracting.
if we want to increment a variable, or wrote something over and over again, we could write the code multiple times, but that would be bulky, inefficient and leave a lot of room for simple errors. So, we use iterations.
the simplest way to repeat is the while loop. while loops loop for as long as a condition is meed. for example
x = True
while x:
print("Hello")
in this code, the code will print “Hello” for as long as x = True. however, x will always be true, so the will print “Hello” indefinitely. this happened because there is no iteration variable to determine when the function should end. what if we make the loop the change the condition
x = 0
while x < 10:
x = x + 1
print(x)
Now the code will print “Hello” for as long as x is less then 10, but every time we loop, or for every iteration, x is getting bigger, so the loop will eventually stop once x is 10
Note: you can use the break keyword in a loop to break out of the loop immediately. YOu can use the continue keyword to skip to the next iteration
But what if we wanted the loop to iterate for a set amount of times - thats where for loops come in. let’s say we want to a loop to iterate for every item in a list. we would write that as
friends = ["Alyssa", "Brianna", "Cade", "Darius"]
for friend in friends:
print(f"{friend} is my friend")
This code will iterate the loop for every item in friends with friend being the name of the variable. What if we want the code to run through a range of numbers instead of a list. well, we can use the range function to generate a list of numbers from a given range.
for i in range(1, 10):
print(i)
this code will print every number from 1 to 10 with representing the number the iteration is working with.