• 1
    डेटा I/O
    • कार्य
  • 2
    शर्तें
    • कार्य
  • 3
    for लूप
    • कार्य
  • 4
    स्ट्रिंग
    • कार्य
  • 5
    while लूप
    • कार्य
  • 6
    सूचियां
    • कार्य
  • 7
    2D मैट्रिक्स
    • कार्य
  • 8
    डिक्शनरी
    • कार्य
  • 9
    सेट
    • कार्य
  • 10
    फ़ंक्शन
    • कार्य
  • к

पाठ 5. While cycle

कठिनाई:

иконка человека красный иконка человека белая иконка человека зеленая Pythonlib

कार्य«लंबे समय से प्रतीक्षित छुट्टी»

💻 Python

अन्ना छुट्टी का सपना देखती है और इसके लिए एक निश्चित राशि जमा करना चाहती है। वह एक निश्चित वार्षिक वेतन से शुरुआत करती है और अपनी बचत की योजना बनाती है। हर साल, उसका नियोक्ता वृद्धि का वादा करता है, और उसका वेतन पिछले वर्ष की तुलना में 15% बढ़ जाता है। अन्ना बहुत अनुशासित है और प्रत्येक वर्ष के अंत में अपने वार्षिक वेतन का ठीक 10% बचाने का निर्णय लेती है।

एक प्रोग्राम लिखें जो अन्ना को यह गणना करने में मदद करेगा कि वह कितने पूर्ण वर्षों में आवश्यक राशि जमा कर सकती है। प्रोग्राम को उपयोगकर्ता से अन्ना का वर्तमान वार्षिक वेतन और छुट्टी की लागत पूछनी चाहिए।

अतिरिक्त शर्त: मुख्य परिणाम (वर्षों की संख्या) के आउटपुट के बाद, प्रोग्राम को उपयोगकर्ता से पूछना चाहिए कि क्या वह वर्ष-दर-वर्ष विस्तृत रिपोर्ट देखना चाहता है। यदि उपयोगकर्ता हाँ दर्ज करता है, तो प्रोग्राम को प्रत्येक वर्ष के लिए उसका नंबर, उस वर्ष का वेतन, कितना बचाया गया, और वर्ष के अंत में कुल संचय राशि क्या हो गई, प्रदर्शित करनी चाहिए।

 

इनपुट फॉर्मेट

एना का वार्षिक वेतन (संख्या, & nbsp; float )
(संख्या, & nbsp; float )
विस्तृत रिपोर्ट के प्रश्न का उत्तर (स्ट्रिंग, & nbsp; str )

आउटपुट फॉर्मेट

मुख्य परिणाम: एक पंक्ति जिसमें जानकारी हो कि इसमें कितने साल लगेंगे (पंक्ति, & nbsp; str )
अतिरिक्त परिणाम (वैकल्पिक): बचत के प्रत्येक वर्ष के लिए विस्तृत रिपोर्ट (पंक्तियाँ, & nbsp; str )

उदाहरण

इनपुट

100000
50000
हाँ

आउटपुट

अन्ना को छुट्टियों के लिए बचत करने में 5 साल लगेंगे।
क्या आप विस्तृत वार्षिक रिपोर्ट देखना चाहते हैं? (हाँ/नहीं): & nbsp;
--- वार्षिक रिपोर्ट ---
वर्ष 1: वेतन 100,000.00, जमा किया गया 10,000.00, कुल 10,000.00
वर्ष 2: वेतन 115000.00, जमा किया गया 11500.00, कुल संचित 21500.00
वर्ष 3: वेतन 132250.00, जमा किया गया 13225.00, कुल संचित 34725.00
वर्ष 4: वेतन 152087.50, जमा किया गया 15208.75, कुल संचित 49933.75
वर्ष 5: वेतन 174900.62, अलग रखा गया 17490.06, कुल संचित 67423.81

संकेत

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
परीक्षण 1
परीक्षण 2
परीक्षण 3
परीक्षण 4
परीक्षण 5
परीक्षण 6
परीक्षण 7
परीक्षण 8
परीक्षण 9
परीक्षण 10
डेवलपर का समाधान
# Запрашиваем у пользователя начальные данные
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}")

🎉 बधाई! 🎉

आपने कार्य को शानदार ढंग से हल किया! यह कठिन था, लेकिन आपने सही उत्तर खोजा। आप प्रोग्रामिंग में महारत के करीब हैं! ऐसे ही जारी रखें।

AD

विज्ञापन

red-snake blue-snake green-snake

कोड चल रहा है...

AI सहायक

नमस्ते! मैं आपका प्रोग्रामिंग सहायक हूँ। Python के बारे में कोई भी सवाल पूछें — मैं functions, methods समझा सकता हूँ और मौजूदा task में मदद कर सकता हूँ!