Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Automating Repetitive Tasks with Loops | Everyday Calculations and Automation
/
Python for Daily Tasks

bookAutomating Repetitive Tasks with Loops

Deslize para mostrar o menu

When you find yourself repeating the same calculation over and over—like adding up daily expenses or tracking steps walked each day—a for-loop can save you time and effort. In Python, a for-loop lets you automate repetitive actions by running a block of code multiple times, once for each item in a sequence. This is especially useful for everyday tasks where you need to process similar data points, such as daily spending or habit tracking.

12345678
# Summing daily expenses over a week using a for-loop daily_expenses = [12.50, 9.75, 15.20, 8.40, 11.60, 14.30, 10.00] total_expense = 0 for expense in daily_expenses: total_expense += expense print("Total weekly expense:", total_expense)
copy

In the example above, the list daily_expenses stores your spending for each day of the week. The for-loop goes through each expense in the list and adds it to total_expense. This process is known as accumulating a total. The function range() is often used with loops when you want to repeat an action a specific number of times. The range() function produces a sequence of numbers, which you can use to control how many times the loop runs. A loop variable (like expense in the example) takes on each value from the sequence, one at a time, allowing you to perform calculations with each item.

12345678
# Calculating total steps walked in a week using a list and a loop steps_per_day = [7000, 8200, 9000, 7500, 8800, 10000, 6500] total_steps = 0 for steps in steps_per_day: total_steps += steps print("Total steps walked in the week:", total_steps)
copy

1. What does the range() function produce in a for-loop?

2. How can you accumulate a total inside a loop?

3. Fill in the blanks to complete a loop that sums a list of numbers:

question mark

What does the range() function produce in a for-loop?

Select the correct answer

question mark

How can you accumulate a total inside a loop?

Select the correct answer

question-icon

Fill in the blanks to complete a loop that sums a list of numbers:

in numbers: total print(total)
17

Clique ou arraste solte itens e preencha os espaços

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 4

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 1. Capítulo 4
some-alt