• 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 5. While cycle

Difficulté :

Exercice«Les vacances tant attendues»

💻 Python

Anna rêve de vacances et souhaite accumuler un certain montant pour celles-ci. Elle commence avec un salaire annuel donné et planifie ses économies. Chaque année, son employeur promet une augmentation, et son salaire augmente de 15 % par rapport à l'année précédente. Anna est très disciplinée et décide d'économiser exactement 10 % de son salaire annuel à la fin de chaque année.

Écrivez un programme qui aidera Anna à calculer combien d'années complètes il lui faudra pour accumuler le montant nécessaire. Le programme doit demander à l'utilisateur le salaire annuel actuel d'Anna et le coût des vacances.

Condition supplémentaire : après l'affichage du résultat principal (le nombre d'années), le programme doit demander à l'utilisateur s'il souhaite voir un rapport détaillé par année. Si l'utilisateur répond oui, le programme doit afficher pour chaque année son numéro, le salaire de cette année, le montant économisé et le montant total des économies à la fin de l'année.

 

Format d entrée

Salaire annuel d'Anna (nombre,   float )
(Nombre,   float )
La réponse à la question d'un rapport détaillé (chaîne de caractères,   str )

Format de sortie

Résultat principal : une ligne contenant des informations sur le nombre d'années nécessaires (chaîne,   str )
Résultat supplémentaire (optionnel) : un rapport détaillé pour chaque année d'épargne (chaîne,   str )

Exemple

Entrée

100000
50000
Oui

Sortie

Anna mettra 5 ans pour économiser pour les vacances.
Vous souhaitez voir un rapport annuel détaillé ? (oui/non) :  
--- Rapport annuel ---
année 1 : salaire 100 000,00, mis de côté 10 000,00, total accumulé 10 000,00
année 2 : salaire 115 000,00, mis de côté 11 500,00, total accumulé 21 500,00
année 3 : salaire 132 250,00, mis de côté 13 225,00, total accumulé 34 725,00
année 4 : salaire 152 087,50, mis de côté 15 208,75, total accumulé 49 933,75
année 5 : salaire 174 900,62, mis de côté 17 490,06, total accumulé 67 423,81

Indice

While in python

In the Python programming language, the while loop construction can have an optional else block. This block is executed only when the loop completes in its natural way, that is, when its condition becomes false, and not as a result of a forced interruption using the break operator.

Syntax:

while condition:
    # the body of the loop
    # ...the code that runs on each iteration...
else:
    # else block
    # ...the code that is executed if the loop ended without a break...

You can think of the else block as a "plan B": it is triggered if the main goal within the loop (which is usually completed through a break) has not been achieved.

Usage example: Searching for an element

Consider a classic problem where we search for a number in a list. If a number is found, we immediately break the loop using break. If we have checked all the elements and still haven't found what we are looking for, the else block is executed.

numbers = [1, 2, 3, 4, 5]
target = 8 # Let's try to find a number that is not in the list.

index = 0
while index < len(numbers):
    if numbers[index] == target:
        print(f"Success! {target} found at {index}.")
break # Goal reached, exit the loop
    index += 1
else:
    # This block will be executed because break was not called
    print(f"The search is completed. {target} not found in the list.")

How it works:

  1. The whileloop is executed as long as the index < len(numbers) condition is true.
  2. Inside the loop, we check whether the current element is equal to the desired one (target).
  3. If we find a value, a success message is displayed and the loop is immediately interrupted by the break statement. The else block is ignored in this case.
  4. If the loop reaches the end (checked all the elements), it means that break has never worked. The index < len(numbers) condition becomes false, and then the else block is executed, reporting a failed search.

A useful tip: Using while...else helps to avoid "flagged" variables. Without this block, the code would look like this:

# Alternative version with "flag"
numbers = [1, 2, 3, 4, 5]
target = 8
found = False # Flag variable

index = 0
while index < len(numbers):
    if numbers[index] == target:
        found = True
        break
    index += 1

if found:
    print(f"Success! {target} found.")
else:
print(f"Search completed. {target} not found in the list.")

As you can see, the while...else construction makes the code cleaner, more concise, and more "Pythonic", eliminating the need to manually control the flag.

If break is missing

If there is no break operator in the body of the while loop, then the else block will always be executed after the loop ends.

count = 0
while count < 3:
print(f"Iteration number {count}")
count += 1
else:
print("The loop ended naturally, so the else block is executed.")

Here, the while loop runs until count is less than 3. As soon as count becomes 3, the loop condition becomes false, and control is transferred to the else block.

Important nuances

  • What about continue? The continue operator does not interrupt the loop, but only ends the current iteration ahead of schedule. It does not affect the execution of the else block in any way.
  • If the loop was never executed? If the while condition is initially false, the loop body will not be executed even once. However, the else block will still run, since the loop ended "normally" (it was not interrupted via break).
value = 10
while value < 5: # The condition is immediately false
    print("This text will never be printed")
else:
print("The cycle didn't even start, but it ended normally, so else worked.")
  • This also works for for loops! The same logic applies to for...else loops. The else block after for is executed if the cycle has passed through all the elements and has not been interrupted using break.

Output

The while...else construction is a powerful and elegant Python tool. It is ideal for situations where you need to perform an action only if the loop has completed its work completely without being interrupted. This is especially useful in search algorithms, condition checking, or when working with data streams, where break signals a special event, and else indicates a regular termination without any.

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
# Запрашиваем у пользователя начальные данные
initial_salary = float(input())
vacation_cost = float(input())

# Проверяем корректность введенных данных
if initial_salary <= 0 or vacation_cost <= 0:
    print("Ошибка: Зарплата и стоимость отпуска должны быть положительными числами.")
else:
    # Инициализация переменных для цикла
    current_salary = initial_salary  # Текущая годовая зарплата
    total_savings = 0.0              # Общая сумма накоплений
    years = 0                        # Счетчик лет
    
    # Список для хранения детальной информации по годам
    yearly_details = []

    # Цикл while работает, пока накопленная сумма меньше стоимости отпуска
    while total_savings < vacation_cost:
        years += 1  # Увеличиваем счетчик лет на 1
        
        # Рассчитываем, сколько денег будет отложено в этом году (10%)
        saved_this_year = current_salary * 0.10
        
        # Добавляем отложенные деньги к общей сумме накоплений
        total_savings += saved_this_year
        
        # Сохраняем детали этого года для возможного отчета
        yearly_details.append((years, current_salary, saved_this_year, total_savings))
        
        # Увеличиваем зарплату на 15% для следующего года
        current_salary *= 1.15

    # Выводим основной результат
    print(f"Анне потребуется {years} лет, чтобы накопить на отпуск.")
    
    # Спрашиваем пользователя, нужен ли детальный отчет
    show_details = input("Хотите увидеть подробный годовой отчет? (да/нет): ")
    
    # Условие для вывода детального отчета
    if show_details.lower() == 'да':
        print("\n--- Годовой отчет ---")
        # Цикл for для вывода информации по каждому году
        for detail in yearly_details:
            year, salary, saved, total = detail
            # Выводим отформатированную строку с данными за год
            print(f"Год {year}: Зарплата {salary:.2f}, Отложено {saved:.2f}, Всего накоплено {total:.2f}")

🎉 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 !