Module 6: Loops and For Loops

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Notes of for loop

-For loop must always start with the for keyword -The for statement must end with a colon (:) -The entirety of the nested block of code within the for statement must be indented

Iteration

each cycle through the loop Ex: i=1 while i < 20 print(i) i=i+2

Using for loops with the range() function

-Can also use for loops to iterate through a sequence of numbers. -Use the range() function to generate the sequence of numbers

Using for loops with strings

-Also use a for loop to iterate through the items in a string -Strings are simply a sequence of individual character

Notes on the range function

-Start specifies the starting number in the sequence. It is optional. If it is not specified, 0 is used -Stop specifies the stopping number in the sequence. It is exclusive. The number is not included in the sequence -Step specifies how big of a hop to make when generating numbers for the sequence. It is also optional. If it is not specified 1 is used

Comprehensions

Allow us to create lists tuples and dictionaries in a concise manner. Comprehensions make our code more concise, but the syntax may take some time to get used to

Using the continue keyword

Allows us to skip the current iteration and move on to the next.

Loop

Block of code that repeats until a specified condition is reached

Using for loops with lists

Common uses of a for loop is to iterate through the items in a list We can do this manually with indexed print statements but we can achieve this with just one print statement with for loop

for key in fruit_price.keys(): print(key.capitalize())

Iterate through all the keys in dictionaries

for value in fruit_price.values(): discount_value = round(value * 0.8, 2) print(discount_value)

Iterate through all values for dictionaries

Range function

Special type of python object designed to work with loops Ex: range(1,20,2)

Using the break keyword

While iterating through a for loop we sometimes need to exit the loop early. We can use the break keyword to terminate the loop before it runs its course

Sequence

any object that is made up of a collection of other objects (strings, lists, dictionaries, arrays)

for loop syntax

for <var> in <container>: <code>

<var>

is a variable name that represents each element in a container

<code>

is the block of code that executes for each iteration through the container

<container>

is the container or sequence we iterate through

range(start, stop, step)

syntax for range function

For loop

used to iterate over the item of a sequence or container By iterating through sequences for loops allow us to repeat tasks a finite number of times


Ensembles d'études connexes

7th Grade Social Studies - Canada

View Set