Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
For Loops | Loops
Introduction to Python Video Course
course content

Зміст курсу

Introduction to Python Video Course

Introduction to Python Video Course

1. Getting Started
2. Variables and Types
3. Conditional Statements
4. Other Data Types
5. Loops
6. Functions

For Loops

Welcome to the section dedicated to loops!

In this chapter, we'll dive into how loops serve as a key tool for automating repetitive tasks and are essential for efficiently handling lists and other iterable data types.

Join Alex as he demonstrates the use of for loops to simplify operations in our grocery store:

The usage of for loops in Python allows you to execute a block of code repeatedly for each item in a collection (iterable object). Here's what you need to know about for loops:

Syntax

Initiate a for loop with the for keyword, followed by a variable name such as item to represent each element in the sequence. This is followed by the in keyword and then the iterable object such as groceryItems. The code block within the loop is executed once for each element.

In this example, item acts as the iterator variable that sequentially accesses each element in the groceryItems list and executes the print() function for each one:

1234
groceryItems = ["milk", "eggs", "cheese", "butter"] for item in groceryItems: # Code to be executed print(item)
copy

Iteration refers to the process of executing a block of code repeatedly. Python supports two main types of iteration:

Definite Iteration

Where the number of iterations is known in advance. for loops are a classic example, automatically stopping when they reach the end of the sequence.

Indefinite Iteration

In which execution continues until a specific condition is met, typically handled by while loops, which will be explored in detail in the upcoming chapter.

Example Applications

for loops in Python can be used with any iterable object (lists, tuples, dictionaries, strings), allowing for data manipulation on a per-element basis.

Whether you need to access items in a list, keys or values in a dictionary, or characters in a string, for loops provide a clear syntax that simplifies code for repetitive tasks.

Here's how you can use a for loop to iterate over the elements in a string and a tuple, similar to how we saw with lists:

123456789
# Print each letter in the string vegetable = "Carrot" for letter in vegetable: print(letter) # Tuple containing different categories of the grocery store categories = ("Produce", "Bakery", "Meat", "Dairy") for category in categories: print(category)
copy

When using a for loop with a dictionary, iterating directly over the dictionary will loop through its keys by default.

Here's what to expect when you directly iterate over a dictionary:

1234567
# Dictionary of products and their stock counts productStock = {"milk": 120, "eggs": 200, "bread": 80} # Print each dictionary key print("Product list:") for product in productStock: print(product)
copy

Notice how the iterator variable product only accesses the dictionary keys.

To iterate over the values of a dictionary, you can use the values() method.

This is useful for operations that require access to values without needing to reference the keys:

1234567
# Dictionary of products and their stock counts productStock = {"milk": 120, "eggs": 200, "bread": 80} # Print each dictionary value print("Stock counts:") for stock in productStock.values(): print(stock)
copy

If you need to access the keys and values simultaneously, the items() method allows you to loop through key-value pairs in a dictionary.

To use this method in a for loop, we specify two variables before the in keyword — one for the key (product) and one for the value (stock):

1234567
# Dictionary of products and their stock counts productStock = {"milk": 120, "eggs": 200, "bread": 80} # Print both the key and value for each dictionary item print("Inventory details:") for product, stock in productStock.items(): print(f"{product} has {stock} units in stock.")
copy

Note

In this example, we use f-strings (also known as formatted string literals) to embed variables directly into strings. The syntax is simple: add an f before the opening quotation mark ", and place variables or expressions inside curly braces {} within the string. This method makes combining strings and variables in print statements much more readable, so it's worth learning.

Drawing on your knowledge of if/else, boolean operators, and for loops, we can run a simple inventory check on a dictionary:

123456789101112131415161718
# Product names as keys and their stock levels as values inventory = { "milk": 120, "eggs": 30, "bread": 80, "apples": 10 } # The threshold stock level that triggers a restock minimum_stock = 50 # Evaluating stock levels and deciding if restocking is necessary print("Checking inventory status:") for product, quantity in inventory.items(): if quantity < minimum_stock: print(f"{product} requires restocking. Only {quantity} units remain.") else: print(f"{product} has adequate stock with {quantity} units available.")
copy

Note

You may notice that we've placed if statements inside the for loop, which added extra indentation to the if block. As mentioned earlier, each indented block of code can be treated as independent, regardless of where it's placed. The key is to ensure that the indentation is consistent and correct between them.

Завдання

In this task, you are responsible for managing the stock and promotions for a grocery store. Your goal is to loop through the inventory dictionary, check if any product needs restocking, and apply promotions if they exist.

  1. Iterate through the items in the inventory dictionary.
  2. Inside the loop, retrieve the current stock and minimum stock for each product from the inventory list.
  3. Write an if statement that checks if the current stock is less than or equal to the minimum stock, triggering a message about restocking.
  4. When the restocking condition is met, increase the current stock by 20 units and update the inventory.
  5. Complete the if condition to verify if a product has a promotion by checking if it exists in the promotions dictionary.

Завдання

In this task, you are responsible for managing the stock and promotions for a grocery store. Your goal is to loop through the inventory dictionary, check if any product needs restocking, and apply promotions if they exist.

  1. Iterate through the items in the inventory dictionary.
  2. Inside the loop, retrieve the current stock and minimum stock for each product from the inventory list.
  3. Write an if statement that checks if the current stock is less than or equal to the minimum stock, triggering a message about restocking.
  4. When the restocking condition is met, increase the current stock by 20 units and update the inventory.
  5. Complete the if condition to verify if a product has a promotion by checking if it exists in the promotions dictionary.

Перейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів

Все було зрозуміло?

Секція 5. Розділ 1
toggle bottom row

For Loops

Welcome to the section dedicated to loops!

In this chapter, we'll dive into how loops serve as a key tool for automating repetitive tasks and are essential for efficiently handling lists and other iterable data types.

Join Alex as he demonstrates the use of for loops to simplify operations in our grocery store:

The usage of for loops in Python allows you to execute a block of code repeatedly for each item in a collection (iterable object). Here's what you need to know about for loops:

Syntax

Initiate a for loop with the for keyword, followed by a variable name such as item to represent each element in the sequence. This is followed by the in keyword and then the iterable object such as groceryItems. The code block within the loop is executed once for each element.

In this example, item acts as the iterator variable that sequentially accesses each element in the groceryItems list and executes the print() function for each one:

1234
groceryItems = ["milk", "eggs", "cheese", "butter"] for item in groceryItems: # Code to be executed print(item)
copy

Iteration refers to the process of executing a block of code repeatedly. Python supports two main types of iteration:

Definite Iteration

Where the number of iterations is known in advance. for loops are a classic example, automatically stopping when they reach the end of the sequence.

Indefinite Iteration

In which execution continues until a specific condition is met, typically handled by while loops, which will be explored in detail in the upcoming chapter.

Example Applications

for loops in Python can be used with any iterable object (lists, tuples, dictionaries, strings), allowing for data manipulation on a per-element basis.

Whether you need to access items in a list, keys or values in a dictionary, or characters in a string, for loops provide a clear syntax that simplifies code for repetitive tasks.

Here's how you can use a for loop to iterate over the elements in a string and a tuple, similar to how we saw with lists:

123456789
# Print each letter in the string vegetable = "Carrot" for letter in vegetable: print(letter) # Tuple containing different categories of the grocery store categories = ("Produce", "Bakery", "Meat", "Dairy") for category in categories: print(category)
copy

When using a for loop with a dictionary, iterating directly over the dictionary will loop through its keys by default.

Here's what to expect when you directly iterate over a dictionary:

1234567
# Dictionary of products and their stock counts productStock = {"milk": 120, "eggs": 200, "bread": 80} # Print each dictionary key print("Product list:") for product in productStock: print(product)
copy

Notice how the iterator variable product only accesses the dictionary keys.

To iterate over the values of a dictionary, you can use the values() method.

This is useful for operations that require access to values without needing to reference the keys:

1234567
# Dictionary of products and their stock counts productStock = {"milk": 120, "eggs": 200, "bread": 80} # Print each dictionary value print("Stock counts:") for stock in productStock.values(): print(stock)
copy

If you need to access the keys and values simultaneously, the items() method allows you to loop through key-value pairs in a dictionary.

To use this method in a for loop, we specify two variables before the in keyword — one for the key (product) and one for the value (stock):

1234567
# Dictionary of products and their stock counts productStock = {"milk": 120, "eggs": 200, "bread": 80} # Print both the key and value for each dictionary item print("Inventory details:") for product, stock in productStock.items(): print(f"{product} has {stock} units in stock.")
copy

Note

In this example, we use f-strings (also known as formatted string literals) to embed variables directly into strings. The syntax is simple: add an f before the opening quotation mark ", and place variables or expressions inside curly braces {} within the string. This method makes combining strings and variables in print statements much more readable, so it's worth learning.

Drawing on your knowledge of if/else, boolean operators, and for loops, we can run a simple inventory check on a dictionary:

123456789101112131415161718
# Product names as keys and their stock levels as values inventory = { "milk": 120, "eggs": 30, "bread": 80, "apples": 10 } # The threshold stock level that triggers a restock minimum_stock = 50 # Evaluating stock levels and deciding if restocking is necessary print("Checking inventory status:") for product, quantity in inventory.items(): if quantity < minimum_stock: print(f"{product} requires restocking. Only {quantity} units remain.") else: print(f"{product} has adequate stock with {quantity} units available.")
copy

Note

You may notice that we've placed if statements inside the for loop, which added extra indentation to the if block. As mentioned earlier, each indented block of code can be treated as independent, regardless of where it's placed. The key is to ensure that the indentation is consistent and correct between them.

Завдання

In this task, you are responsible for managing the stock and promotions for a grocery store. Your goal is to loop through the inventory dictionary, check if any product needs restocking, and apply promotions if they exist.

  1. Iterate through the items in the inventory dictionary.
  2. Inside the loop, retrieve the current stock and minimum stock for each product from the inventory list.
  3. Write an if statement that checks if the current stock is less than or equal to the minimum stock, triggering a message about restocking.
  4. When the restocking condition is met, increase the current stock by 20 units and update the inventory.
  5. Complete the if condition to verify if a product has a promotion by checking if it exists in the promotions dictionary.

Завдання

In this task, you are responsible for managing the stock and promotions for a grocery store. Your goal is to loop through the inventory dictionary, check if any product needs restocking, and apply promotions if they exist.

  1. Iterate through the items in the inventory dictionary.
  2. Inside the loop, retrieve the current stock and minimum stock for each product from the inventory list.
  3. Write an if statement that checks if the current stock is less than or equal to the minimum stock, triggering a message about restocking.
  4. When the restocking condition is met, increase the current stock by 20 units and update the inventory.
  5. Complete the if condition to verify if a product has a promotion by checking if it exists in the promotions dictionary.

Перейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів

Все було зрозуміло?

Секція 5. Розділ 1
toggle bottom row

For Loops

Welcome to the section dedicated to loops!

In this chapter, we'll dive into how loops serve as a key tool for automating repetitive tasks and are essential for efficiently handling lists and other iterable data types.

Join Alex as he demonstrates the use of for loops to simplify operations in our grocery store:

The usage of for loops in Python allows you to execute a block of code repeatedly for each item in a collection (iterable object). Here's what you need to know about for loops:

Syntax

Initiate a for loop with the for keyword, followed by a variable name such as item to represent each element in the sequence. This is followed by the in keyword and then the iterable object such as groceryItems. The code block within the loop is executed once for each element.

In this example, item acts as the iterator variable that sequentially accesses each element in the groceryItems list and executes the print() function for each one:

1234
groceryItems = ["milk", "eggs", "cheese", "butter"] for item in groceryItems: # Code to be executed print(item)
copy

Iteration refers to the process of executing a block of code repeatedly. Python supports two main types of iteration:

Definite Iteration

Where the number of iterations is known in advance. for loops are a classic example, automatically stopping when they reach the end of the sequence.

Indefinite Iteration

In which execution continues until a specific condition is met, typically handled by while loops, which will be explored in detail in the upcoming chapter.

Example Applications

for loops in Python can be used with any iterable object (lists, tuples, dictionaries, strings), allowing for data manipulation on a per-element basis.

Whether you need to access items in a list, keys or values in a dictionary, or characters in a string, for loops provide a clear syntax that simplifies code for repetitive tasks.

Here's how you can use a for loop to iterate over the elements in a string and a tuple, similar to how we saw with lists:

123456789
# Print each letter in the string vegetable = "Carrot" for letter in vegetable: print(letter) # Tuple containing different categories of the grocery store categories = ("Produce", "Bakery", "Meat", "Dairy") for category in categories: print(category)
copy

When using a for loop with a dictionary, iterating directly over the dictionary will loop through its keys by default.

Here's what to expect when you directly iterate over a dictionary:

1234567
# Dictionary of products and their stock counts productStock = {"milk": 120, "eggs": 200, "bread": 80} # Print each dictionary key print("Product list:") for product in productStock: print(product)
copy

Notice how the iterator variable product only accesses the dictionary keys.

To iterate over the values of a dictionary, you can use the values() method.

This is useful for operations that require access to values without needing to reference the keys:

1234567
# Dictionary of products and their stock counts productStock = {"milk": 120, "eggs": 200, "bread": 80} # Print each dictionary value print("Stock counts:") for stock in productStock.values(): print(stock)
copy

If you need to access the keys and values simultaneously, the items() method allows you to loop through key-value pairs in a dictionary.

To use this method in a for loop, we specify two variables before the in keyword — one for the key (product) and one for the value (stock):

1234567
# Dictionary of products and their stock counts productStock = {"milk": 120, "eggs": 200, "bread": 80} # Print both the key and value for each dictionary item print("Inventory details:") for product, stock in productStock.items(): print(f"{product} has {stock} units in stock.")
copy

Note

In this example, we use f-strings (also known as formatted string literals) to embed variables directly into strings. The syntax is simple: add an f before the opening quotation mark ", and place variables or expressions inside curly braces {} within the string. This method makes combining strings and variables in print statements much more readable, so it's worth learning.

Drawing on your knowledge of if/else, boolean operators, and for loops, we can run a simple inventory check on a dictionary:

123456789101112131415161718
# Product names as keys and their stock levels as values inventory = { "milk": 120, "eggs": 30, "bread": 80, "apples": 10 } # The threshold stock level that triggers a restock minimum_stock = 50 # Evaluating stock levels and deciding if restocking is necessary print("Checking inventory status:") for product, quantity in inventory.items(): if quantity < minimum_stock: print(f"{product} requires restocking. Only {quantity} units remain.") else: print(f"{product} has adequate stock with {quantity} units available.")
copy

Note

You may notice that we've placed if statements inside the for loop, which added extra indentation to the if block. As mentioned earlier, each indented block of code can be treated as independent, regardless of where it's placed. The key is to ensure that the indentation is consistent and correct between them.

Завдання

In this task, you are responsible for managing the stock and promotions for a grocery store. Your goal is to loop through the inventory dictionary, check if any product needs restocking, and apply promotions if they exist.

  1. Iterate through the items in the inventory dictionary.
  2. Inside the loop, retrieve the current stock and minimum stock for each product from the inventory list.
  3. Write an if statement that checks if the current stock is less than or equal to the minimum stock, triggering a message about restocking.
  4. When the restocking condition is met, increase the current stock by 20 units and update the inventory.
  5. Complete the if condition to verify if a product has a promotion by checking if it exists in the promotions dictionary.

Завдання

In this task, you are responsible for managing the stock and promotions for a grocery store. Your goal is to loop through the inventory dictionary, check if any product needs restocking, and apply promotions if they exist.

  1. Iterate through the items in the inventory dictionary.
  2. Inside the loop, retrieve the current stock and minimum stock for each product from the inventory list.
  3. Write an if statement that checks if the current stock is less than or equal to the minimum stock, triggering a message about restocking.
  4. When the restocking condition is met, increase the current stock by 20 units and update the inventory.
  5. Complete the if condition to verify if a product has a promotion by checking if it exists in the promotions dictionary.

Перейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів

Все було зрозуміло?

Welcome to the section dedicated to loops!

In this chapter, we'll dive into how loops serve as a key tool for automating repetitive tasks and are essential for efficiently handling lists and other iterable data types.

Join Alex as he demonstrates the use of for loops to simplify operations in our grocery store:

The usage of for loops in Python allows you to execute a block of code repeatedly for each item in a collection (iterable object). Here's what you need to know about for loops:

Syntax

Initiate a for loop with the for keyword, followed by a variable name such as item to represent each element in the sequence. This is followed by the in keyword and then the iterable object such as groceryItems. The code block within the loop is executed once for each element.

In this example, item acts as the iterator variable that sequentially accesses each element in the groceryItems list and executes the print() function for each one:

1234
groceryItems = ["milk", "eggs", "cheese", "butter"] for item in groceryItems: # Code to be executed print(item)
copy

Iteration refers to the process of executing a block of code repeatedly. Python supports two main types of iteration:

Definite Iteration

Where the number of iterations is known in advance. for loops are a classic example, automatically stopping when they reach the end of the sequence.

Indefinite Iteration

In which execution continues until a specific condition is met, typically handled by while loops, which will be explored in detail in the upcoming chapter.

Example Applications

for loops in Python can be used with any iterable object (lists, tuples, dictionaries, strings), allowing for data manipulation on a per-element basis.

Whether you need to access items in a list, keys or values in a dictionary, or characters in a string, for loops provide a clear syntax that simplifies code for repetitive tasks.

Here's how you can use a for loop to iterate over the elements in a string and a tuple, similar to how we saw with lists:

123456789
# Print each letter in the string vegetable = "Carrot" for letter in vegetable: print(letter) # Tuple containing different categories of the grocery store categories = ("Produce", "Bakery", "Meat", "Dairy") for category in categories: print(category)
copy

When using a for loop with a dictionary, iterating directly over the dictionary will loop through its keys by default.

Here's what to expect when you directly iterate over a dictionary:

1234567
# Dictionary of products and their stock counts productStock = {"milk": 120, "eggs": 200, "bread": 80} # Print each dictionary key print("Product list:") for product in productStock: print(product)
copy

Notice how the iterator variable product only accesses the dictionary keys.

To iterate over the values of a dictionary, you can use the values() method.

This is useful for operations that require access to values without needing to reference the keys:

1234567
# Dictionary of products and their stock counts productStock = {"milk": 120, "eggs": 200, "bread": 80} # Print each dictionary value print("Stock counts:") for stock in productStock.values(): print(stock)
copy

If you need to access the keys and values simultaneously, the items() method allows you to loop through key-value pairs in a dictionary.

To use this method in a for loop, we specify two variables before the in keyword — one for the key (product) and one for the value (stock):

1234567
# Dictionary of products and their stock counts productStock = {"milk": 120, "eggs": 200, "bread": 80} # Print both the key and value for each dictionary item print("Inventory details:") for product, stock in productStock.items(): print(f"{product} has {stock} units in stock.")
copy

Note

In this example, we use f-strings (also known as formatted string literals) to embed variables directly into strings. The syntax is simple: add an f before the opening quotation mark ", and place variables or expressions inside curly braces {} within the string. This method makes combining strings and variables in print statements much more readable, so it's worth learning.

Drawing on your knowledge of if/else, boolean operators, and for loops, we can run a simple inventory check on a dictionary:

123456789101112131415161718
# Product names as keys and their stock levels as values inventory = { "milk": 120, "eggs": 30, "bread": 80, "apples": 10 } # The threshold stock level that triggers a restock minimum_stock = 50 # Evaluating stock levels and deciding if restocking is necessary print("Checking inventory status:") for product, quantity in inventory.items(): if quantity < minimum_stock: print(f"{product} requires restocking. Only {quantity} units remain.") else: print(f"{product} has adequate stock with {quantity} units available.")
copy

Note

You may notice that we've placed if statements inside the for loop, which added extra indentation to the if block. As mentioned earlier, each indented block of code can be treated as independent, regardless of where it's placed. The key is to ensure that the indentation is consistent and correct between them.

Завдання

In this task, you are responsible for managing the stock and promotions for a grocery store. Your goal is to loop through the inventory dictionary, check if any product needs restocking, and apply promotions if they exist.

  1. Iterate through the items in the inventory dictionary.
  2. Inside the loop, retrieve the current stock and minimum stock for each product from the inventory list.
  3. Write an if statement that checks if the current stock is less than or equal to the minimum stock, triggering a message about restocking.
  4. When the restocking condition is met, increase the current stock by 20 units and update the inventory.
  5. Complete the if condition to verify if a product has a promotion by checking if it exists in the promotions dictionary.

Перейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів
Секція 5. Розділ 1
Перейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів
We're sorry to hear that something went wrong. What happened?
some-alt