loops Flashcards
what is a loop in python
In programming, this process of using an initialization, repetitions, and an ending condition is called a loop. In a loop, we perform a process of iteration (repeating tasks).
what is Definite iteration
Where the number of times the loop will be executed is defined in advance (usually based on the collection size).
What is Indefinite iteration
where the number of times the loop is executed depends on how many times a condition is met.
what is a for loop
a type of definite iteration. (When a program needs to iterate a set number of times)
In a for loop, we will know in advance how many times the loop will need to iterate because we will be working on a collection with a predefined length
what is a tempory variable
that is used to represent the value of the element in the collection the loop is currently on.
how to layout a for loop
for <temporary> in <collection>:</collection></temporary>
<action>
ingredients = ["milk", "sugar", "vanilla extract", "dough", "chocolate"]
for ingredient in ingredients:
print(ingredient)
In this example:
ingredient is the <temporary>.
ingredients is our <collection>.
print(ingredient) was the <action> performed on every iteration using the temporary variable of ingredient.
</action></collection></temporary></action>
what is the ( in ) used for in a ( for ) loop
An in keyword separates the temporary variable from the collection used for iteration.
what is <collection> in a for loop</collection>
A <collection> to loop over. In our examples, we will be using a list</collection>
does a tempory variable need to be defined before hand ?
A temporary variable’s name is arbitrary and does not need to be defined beforehand.
do we need to indent a for loop ?
If we ever forget to indent, we’ll get an IndentationError or unexpected behavior.
example for loop
sport_games = [“football”, “hockey”, “baseball”, “cricket”]
For sports in sport_games:
print(sports)
how to use the range directly in our for loops as the collection to perform iteration ?
for temp in range(6):
print(“Learning Loops!”)
Would output:
Learning Loops!
Learning Loops!
Learning Loops!
Learning Loops!
Learning Loops!
Learning Loops!
what is the structure of a while loop
The structure follows this pattern:
while <conditional>:</conditional>
<action>
Let’s examine this example, where we print the integers 0 through 3:
count = 0
while count <= 3:
# Loop Body
print(count)
count += 1
output: 0, 1, 2, 3
</action>
what does a ( while ) loop do
a while loop and is a form of indefinite iteration ( where the number of times the loop is executed depends on how many times a condition is met. )
A while loop performs a set of instructions as long as a given condition is true.
what does the str ( ) do
converts the variable from an integer to a string