• 1
    Entrée et sortie
    • Tâches
  • 2
    Conditions
    • Tâches
  • 3
    Boucle for
    • Tâches
  • 4
    Chaînes
    • Tâches
  • 5
    Boucle while
    • Tâches
  • 6
    Listes
    • Tâches
  • 7
    Tableaux 2D
    • Tâches
  • 8
    Dictionnaires
    • Tâches
  • 9
    Ensembles
    • Tâches
  • 10
    Fonctions et récursion
    • Tâches
  • к

Leçon 3. FOR cycle

Difficulté :

Exercice«Achats de fête»

💻 Python

Vous planifiez un dîner festif et vous disposez d'un budget strictement limité. Votre tâche — Écrire un programme assistant qui suivra vos coûts en temps réel.

Le programme doit d'abord demander votre budget total et le nombre d'articles que vous allez acheter. Ensuite, pour chaque produit, il doit demander son nom et son prix.

Après l'ajout de chaque produit, le programme doit indiquer quel produit a été ajouté et combien d'argent il vous reste. Si à un moment donné vos dépenses dépassent le budget, le programme doit immédiatement afficher un avertissement à ce sujet, mais continuer tout de même à ajouter des articles à la liste.

Après avoir saisi les informations sur tous les articles, le programme doit afficher le montant total d'argent dépensé et le solde final sur votre compte (il peut être négatif).

Format d entrée

première ligne : le budget (nombre entier).
deuxième ligne : la quantité de produits (un nombre entier).

Suivent les paires de lignes pour chaque produit :

  • le nom du produit (ligne).
  • le prix du produit (nombre entier).

Format de sortie

pour chaque produit saisi :

rn
    rn
  • le produit et le solde du budget (ligne).
  • rn
  • si le budget est dépassé, un avertissement (ligne) est également affiché.
  • rn
rn

après avoir saisi tous les produits :

rn
    rn
  • le rapport final contenant le montant total des dépenses et le solde final (plusieurs lignes).
  • rn

Exemple

Entrée

1500
3
Gâteau Napoléon
800
champagne
500
Bougies
150

Sortie

Produits ajoutés : gâteau Napoléon. Reste du budget : 700
Produits ajoutés : champagne. Reste du budget : 200
Produits ajoutés : bougies. Reste du budget : 50

rn

Achats terminés.
Total dépensé : 1450
Solde final : 50

Indice

Basics of the forcycle

The for loop in Python is your main tool for iterating through elements in any sequence. Imagine that you have a box with different items. The for loop allows you to take one item at a time, do something with it, and move on to the next until the items in the box run out.

It is used to iterate over sequences such as lists, strings, tuples, sets, or even keys in a dictionary. The same block of code is executed for each element of the sequence.

Syntax:

for element in sequence:
    # a block of code that will be executed for each element
    # IMPORTANT: this block must be indented!

Here, the element is a temporary variable that is assigned a different value from the sequence at each iteration. You can name this variable any way you want, but it's better to choose a meaningful name (for example, fruit for a list of fruits or letter for a string).

Iterating through the list

A list is an ordered collection of items. The for loop will run through it from the first element to the last.

fruits = ['apple', 'banana', 'cherry']
for fruit in fruit:
    print(fruit)

Conclusion:

apple
banana
cherry

Iterating over the line

A string is, in fact, a sequence of characters. Therefore, the for loop can iterate over it just as easily.

word = "Python"
for a letter in a word:
    print(letter)

Conclusion:

P
y
t
h
o
n

Cycle control: break and continue

Sometimes you don't have to go through the whole cycle to the end. There are special operators for this.

The break operator

The break operator is used to immediately and completely terminate the loop. As soon as the program encounters a break, it immediately exits the loop and continues execution from the next line of code after it.

A useful tip: break is indispensable when you are looking for something. Once you've found what you're looking for, there's no point in continuing the search.

Example: We have a list of numbers, and we want to find the first even number and stop the loop as soon as it is found.

numbers = [1, 3, 5, 6, 7, 9, 10]
for num in numbers:
    if num % 2 == 0: # Check for parity
        print(f"The first even number is found: {num}")
break # Immediately exit the loop
print("The loop is completed.")

Conclusion:

The first even number was found: 6
The cycle is completed.

Please note that the numbers 7, 9, and 10 were not checked, as the cycle was interrupted by the number 6.

The continue operator

The continue operator is used to skip the current iteration and immediately move on to the next one. All the code that is in the loop after continue will not be executed for the current element.

A useful tip: continue is very convenient for "filtering" data inside a loop. If the current item doesn't suit you by some criterion, you just skip it and move on to the next one.

Example: We have a list of numbers, and we want to output all the numbers except the even ones.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
    if num % 2 == 0: # Check for parity
        continue # If the number is even, skip print() and go to the next number.
    print(num)

Conclusion:

1
3
5
7
9

When num was equal to 2, 4, 6, etc., the if condition was met, continue skipped the print(num) command, and the loop immediately started a new iteration.

The difference between break and continue is in a nutshell

  • break: "Stop, car!". Stops the cycle completely.
  • continue: "This one doesn't fit, let's do the next one!". Skips only the current step.

The else block in the for

loop

The for loop may have an optional else block. This block is executed only if the loop has completed all its iterations naturally, that is, it has not been interrupted by the break operator.

A useful tip: It is a very powerful tool for search tasks. The else block makes it easy to handle a situation where the search has ended but nothing has been found.

Example 1: The loop ended normally

for number in range(3):
print(number)
else:
    print("The cycle is completed without interruptions.")

Conclusion:

0
1
2
The cycle is completed without interruptions.

Example 2: The loop is interrupted by the break

operator
for number in range(3):
if number == 1:
        print("We found 1, we break the loop.")
break
    print(number)
else:
    # This block will not be executed because there was a break
    print("The cycle is completed without interruptions.")

Conclusion:

0
We found 1, we interrupt the cycle.

Practical examples

The sum of all the numbers in the list

This is a classic task for understanding how to work with a cycle and accumulate results.

numbers = [1, 2, 3, 4, 5]
amount = 0 # Initialize the variable to store the amount BEFORE the loop
for a number in numbers:
    sum += number # At each iteration, we add the current number to the total
print(f' Sum: {sum}') # Output the final result AFTER the loop

Conclusion: Amount: 15

A useful tip: Although this method perfectly demonstrates how the loop works, in real code it is better to use the built-in sum() function to find the sum of the list elements: print(sum(numbers)). It's shorter and more efficient.

Finding the maximum number in the list

Here we assume that the first element is the maximum, and then in the loop we compare it with all the others.

numbers = [1, 7, 3, 9, 5]
maximum = numbers[0] # We take the first element as the temporary maximum
for a number in numbers:
    if the number is > maximum: # If we find a number greater than our maximum...
maximum = number # ...then we update the maximum
print(f' Maximum: {maximum}')

Conclusion: Maximum: 9

A useful tip: As with the sum, Python has a built-in function max() for this task: print(max(numbers)). Knowing these functions saves time, but understanding how they work using the for loop is a key skill for a programmer.

main.py
Test 1
Test 2
Test 3
Test 4
Test 5
Test 6
Test 7
Test 8
Test 9
Test 10
Solution du développeur
# Запрашиваем и считываем общий бюджет, преобразуя его в целое число
budget = int(input())
# Запрашиваем и считываем количество товаров, преобразуя его в целое число
num_items = int(input())

# Создаем переменную для хранения общей суммы потраченных средств, изначально она равна 0
total_spent = 0
remaining_budget = budget
# Запускаем цикл, который повторится столько раз, сколько товаров мы планируем купить
for i in range(num_items):
    # Внутри цикла запрашиваем название очередного товара
    item_name = input()
    # Затем запрашиваем его цену и преобразуем в целое число
    item_price = int(input())

    # Добавляем цену текущего товара к общей сумме трат
    total_spent = total_spent + item_price
    # Вычисляем, сколько денег осталось от первоначального бюджета
    remaining_budget = budget - total_spent

    # Выводим сообщение о том, какой товар добавлен и какой остаток бюджета
    print(f"Добавлен товар: {item_name}. Остаток бюджета: {remaining_budget}")

    # Проверяем условие: если остаток бюджета стал меньше нуля...
    if remaining_budget < 0:
        # ...то выводим предупреждение с указанием суммы превышения
        # Мы используем -remaining_budget, чтобы показать положительное число долга
        print(f"Внимание! Бюджет превышен на {-remaining_budget}.")

# После завершения цикла выводим пустую строку для лучшей читаемости
print("\nПокупки завершены.")
# Выводим итоговую сумму всех трат
print(f"Всего потрачено: {total_spent}")
# Выводим финальный остаток, который может быть положительным или отрицательным
print(f"Итоговый остаток: {remaining_budget}")

🎉 Félicitations ! 🎉

Tu as brillamment résolu la tâche ! C était difficile, mais tu as trouvé la bonne solution. Tu es encore plus proche de maîtriser la programmation ! Continue ainsi.

AD

Publicité

red-snake blue-snake green-snake

Exécution de votre code...

Assistant IA

Bonjour ! Je suis ton assistant de programmation. Pose moi toutes tes questions sur Python — je peux t expliquer les fonctions, les méthodes et t aider avec la tâche en cours !