• 1
    Input and Output Data
    • Tasks
  • 2
    Conditions
    • Tasks
  • 3
    For Loop
    • Tasks
  • 4
    Strings
    • Tasks
  • 5
    While Loop
    • Tasks
  • 6
    Lists
    • Tasks
  • 7
    Two-Dimensional Arrays
    • Tasks
  • 8
    Dictionaries
    • Tasks
  • 9
    Sets
    • Tasks
  • 10
    Functions and Recursion
    • Tasks
  • к

Занятие 5. While cycle

Difficulty level:

Task«The sum of the squares of numbers»

You work as an engineer in a secret laboratory and test the new computing module "Quadron". The module accepts commands in the form of text lines through the console. Your task & mdash; Write a symbol program that will emulate the work of this module.

rn

the simulator should work in the cycle, constantly expecting a command to complete the work.

rn

module commands:

rn
  • rn
  • set & lt; number & gt; : This team sets the upper border of calculations & nbsp; n . For example, & nbsp; to set 10 & nbsp; it means that & nbsp; n & nbsp; now 10. The program must confirm the installation by displaying a message & nbsp; the new limit N = 10 is set. . If the number in the team is indicated incorrectly (for example, this is not a number), the program should derive an error.
  • rn
  • : the simulator must find all the valid numbers in this command in this command. The range from 0 to & nbsp; n & nbsp; (inclusive), build each square, and then fold all the resulting squares. The result must be deduced in & nbsp format; the calculation result for n = 10: 220 . If & nbsp; n & nbsp; has not yet been installed using the first command, the program should report an error.
  • rn
  • output : this team completes the simulator.
  • RN RN

    you need to create a program that will correctly process these commands, manage the state (value & nbsp; n ) and perform calculations using cycles and conditions.

    Input format

    Team (String). This is a text line that can be one of the three: & nbsp; set & lt; number & gt; , & nbsp; calculate & nbsp; or & nbsp; output . The program accepts commands sequentially, one after another.

    Output format

    Simulator response (String). This is a text line that depends on the entered command. This may be confirmation, the result of the calculation or error message.

    Example

    Input

    Install 10
    Calculate
    Exit

    Output

    The new limit n = 10 is set.
    The calculation result for n = 10: 220

    Hint

    There will be no clue here, decide for yourself!

    main.py
    Test 1
    Test 2
    Test 3
    Test 4
    Test 5
    Test 6
    Test 7
    Test 8
    Test 9
    Test 10
    Developer’s solution
    # Инициализируем переменную для хранения лимита n.
    # None означает, что значение еще не было установлено пользователем.
    n_limit = None
    
    # Запускаем бесконечный цикл, который будет работать, пока пользователь не введет команду "выход".
    # Это основной цикл программы, обрабатывающий команды.
    while True:
        # Считываем текстовую команду, введенную пользователем с клавиатуры.
        command = input()
    
        # Проверяем, если пользователь ввел команду "выход".
        if command == "выход":
            # Если да, то прерываем исполнение цикла while с помощью оператора break.
            break
        # Проверяем, начинается ли введенная строка с "установить ".
        # Это позволяет нам обрабатывать команды вида "установить 10", "установить 50" и т.д.
        elif command.startswith("установить "):
            # Разбиваем введенную строку на части по пробелу. Например, "установить 10" станет списком ["установить", "10"].
            parts = command.split()
            # Проверяем, что команда состоит из двух частей и вторая часть является числом.
            if len(parts) == 2 and parts[1].isdigit():
                # Если проверка прошла, преобразуем вторую часть (которая является строкой) в целое число.
                n_limit = int(parts[1])
                # Выводим пользователю подтверждение, что лимит успешно установлен, используя f-строку для форматирования.
                print(f"Новый лимит n = {n_limit} установлен.")
            else:
                # Если формат команды неверный (например, "установить" без числа или "установить abc"), выводим ошибку.
                print("Ошибка: неверный формат команды. Используйте: установить <число>")
        # Проверяем, если пользователь ввел в точности команду "рассчитать".
        elif command == "рассчитать":
            # Прежде чем считать, проверяем, было ли значение n_limit установлено ранее.
            if n_limit is not None:
                # Если n_limit установлен, инициализируем переменную для хранения суммы квадратов.
                sum_of_squares = 0
                # Запускаем цикл for, который перебирает все числа от 0 до n_limit включительно.
                for i in range(n_limit + 1):
                    # Внутри цикла проверяем, является ли текущее число i четным.
                    # Деление с остатком (%) на 2 вернет 0 только для четных чисел.
                    if i % 2 == 0:
                        # Если число четное, вычисляем его квадрат (i * i) и добавляем к общей сумме.
                        sum_of_squares += i * i
                # После завершения цикла выводим итоговый результат в требуемом формате.
                print(f"Результат расчета для n={n_limit}: {sum_of_squares}")
            else:
                # Если n_limit все еще равен None, значит, команду "установить" еще не вызывали.
                print("Ошибка: лимит n не установлен. Используйте команду установить <число>.")
        # Если введенная команда не совпала ни с одной из известных.
        else:
            # Сообщаем пользователю, что его команда не распознана.
            print("Неизвестная команда. Доступные команды: установить <число>, рассчитать, выход.")

    🎉 Congratulations! 🎉

    You did an excellent job with the task! It was a challenging problem, but you found the correct solution. You are one step closer to mastering programming! Keep up the good work, because every stage you pass makes you even stronger.

    AD

    Advertisement

    red-snake blue-snake green-snake

    Running your code...

    Помощник ИИ

    Привет! Я твой помощник по программированию. Задавай любые вопросы по Python, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!