• 1
    Entrada y salida de datos
    • Tareas
  • 2
    Condiciones
    • Tareas
  • 3
    Bucle for
    • Tareas
  • 4
    Cadenas de texto
    • Tareas
  • 5
    Bucle while
    • Tareas
  • 6
    Listas
    • Tareas
  • 7
    Matrices 2D
    • Tareas
  • 8
    Diccionarios
    • Tareas
  • 9
    Conjuntos
    • Tareas
  • 10
    Funciones y recursión
    • Tareas
  • к

Lección 5. While cycle

Dificultad:

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

Tarea«Acumulaciones de Denis»

💻 Python

Denis es un programador novato, y sueña con un nuevo teléfono inteligente potente para trabajar y entretenerse. Decidió que ahorraría el 20% de su salario mensual para esta compra.

rn

Escriba un programa que ayude a Denis a calcular cuánto tiempo necesitará para acumular la cantidad necesaria. El programa debe solicitar dos valores al usuario: el salario mensual de Denis y el costo total del teléfono inteligente.

rn

& nbsp;

rn rn
  • Si el salario de Denis es cero o negativo, el programa debe informar que es imposible ahorrar para un teléfono inteligente. Ahorrando el 20% de un salario, el programa debe mostrar el mensaje correspondiente.
  • rn
  • En otros casos, el programa debe calcular el número exacto de años completos y meses necesarios para la acumulación.
  • rn
  • La salida debe ser gramaticalmente correcta. Por ejemplo, "1 año", "2 años", "5 años"; "1 mes", "3 meses", "10 meses".
  • rn
  • Si la acumulación requiere exactamente n años (sin meses) o exactamente n meses (menos de un año), muestre solo años o solo meses, respectivamente.
  • rn

    Formato de entrada

    En la primera línea se introduce un número & mdash; El tamaño del salario mensual.
    En la segunda línea, se introduce un número & mdash; El costo total de un teléfono inteligente.

    Formato de salida

    línea & mdash; El número de meses o años que serán necesarios para acumular la cantidad correcta.

    Ejemplo

    Entrada

    50000
    25000

    Salida

    El acceso tomará: 3 meses

    Pista

    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
    Prueba 1
    Prueba 2
    Prueba 3
    Prueba 4
    Prueba 5
    Prueba 6
    Prueba 7
    Prueba 8
    Prueba 9
    Prueba 10
    Solución del desarrollador
    # Запрашиваем у пользователя исходные данные
    salary = float(input())
    smartphone_cost = float(input())
    
    # Проверяем, может ли Денис в принципе копить
    if salary <= 0:
        print("При такой зарплате Денис никогда не сможет накопить на смартфон.")
    else:
        # Рассчитываем, сколько Денис откладывает каждый месяц
        monthly_saving = salary * 0.20
    
        # Проверяем, может ли он купить смартфон с одной зарплаты
        if monthly_saving >= smartphone_cost:
            print("Денис может купить смартфон сразу, с одной зарплаты!")
        else:
            # Используем цикл while для симуляции процесса накопления
            accumulated_sum = 0  # Переменная для хранения накопленной суммы
            total_months = 0     # Счетчик месяцев
    
            while accumulated_sum < smartphone_cost:
                accumulated_sum += monthly_saving  # Каждый месяц добавляем к накоплениям
                total_months += 1                  # Увеличиваем счетчик месяцев
    
            # Рассчитываем полные годы и оставшиеся месяцы
            years = total_months // 12
            months = total_months % 12
    
            # Готовим строки для вывода с правильными окончаниями
            year_str = ""
            month_str = ""
    
            # Формируем строку для лет (используем условия для правильной грамматики)
            if years > 0:
                if years % 10 == 1 and years % 100 != 11:
                    year_str = f"{years} год"
                elif 2 <= years % 10 <= 4 and (years % 100 < 10 or years % 100 >= 20):
                    year_str = f"{years} года"
                else:
                    year_str = f"{years} лет"
    
            # Формируем строку для месяцев (используем условия для правильной грамматики)
            if months > 0:
                if months == 1:
                    month_str = "1 месяц"
                elif 2 <= months <= 4:
                    month_str = f"{months} месяца"
                else:
                    month_str = f"{months} месяцев"
    
            # Собираем и выводим итоговый результат
            result_parts = []
            if year_str:
                result_parts.append(year_str)
            if month_str:
                result_parts.append(month_str)
            
            print("Накопление займет: " + " и ".join(result_parts))

    🎉 ¡Felicidades! 🎉

    ¡Has resuelto la tarea brillantemente! Era un reto difícil, pero encontraste la solución correcta. ¡Estás un paso más cerca de dominar la programación! Sigue así, cada etapa superada te hace más fuerte.

    AD

    Publicidad

    red-snake blue-snake green-snake

    Ejecutando tu código...

    Asistente de IA

    ¡Hola! Soy tu asistente de programación. Hazme cualquier pregunta sobre Python — puedo explicarte funciones, métodos y ayudarte con la tarea actual.