• 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
  • к

Занятие 3. FOR cycle

Difficulty level:

Task«Square and sum»

you & mdash; A new clerk in the famous guild of heroes. The head of the guild has developed a new system for assessing the potential of recruits & mdash; "Force index." This system helps to quickly determine how promising the new guild member is. You are instructed to create a calculator program for automatically calculating this index.

rn

the calculation of "index Forces ":

rn
    rn
  1. the index is calculated based on the main characteristics of the hero: strength, dexterity, intelligence and TM
  2. rn
  3. the sum of the squares & nbsp; all the conveyed characteristics.
  4. rn
  5. an important condition from the head Guilds: & nbsp; characteristics, the value of which & nbsp; is less than 5 are considered insignificant for a beginner and & nbsp; are not taken into account & nbsp; in the calculation. Also, any negative or zero values ​​should be ignored.
  6. rn rn

    your task:
    Write a program that first requests the number of characteristics for the assessment, and then the values ​​of these characteristics. The program should calculate the "force index" according to the rules and derive the final result.

    Input format

    pipe line: the number of characteristics for input (an integer, & nbsp; int ).
    Subsequent lines: the value of each characteristic (an integer, & nbsp; int ), one number per line.

    Output format

    final "power index" (an integer, & nbsp; int ).

    Example

    Input

    5
    10
    4
    8
    -2
    12

    Output

    308

    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
# Инициализируем переменную для хранения итоговой суммы квадратов.
# Начинаем с нуля, так как еще ничего не посчитали.
total_power_index = 0

# Запрашиваем у пользователя, сколько характеристик он собирается ввести.
# input() считывает строку, например "5".
characteristics_count_str = input()

# Превращаем полученную строку "5" в целое число 5, чтобы использовать в цикле.
characteristics_count = int(characteristics_count_str)

# Запускаем цикл, который повторится ровно столько раз,
# сколько характеристик мы хотим ввести (значение characteristics_count).
# Переменная i здесь не используется, поэтому ставим прочерк _.
for _ in range(characteristics_count):
    # Внутри цикла считываем значение очередной характеристики.
    stat_value_str = input()
    # Превращаем строку в целое число для математических операций.
    stat_value = int(stat_value_str)

    # Это главное условие задачи. Проверяем, что характеристика больше или равна 5.
    # Если условие истинно (например, введено 10), то код внутри if выполнится.
    # Если ложно (например, введено 3 или -2), то код внутри if будет проигнорирован.
    if stat_value >= 5:
        # Возводим значение характеристики в квадрат (умножаем само на себя).
        # Затем прибавляем полученный результат к нашей общей сумме.
        # Оператор += это сокращение для total_power_index = total_power_index + (stat_value * stat_value)
        total_power_index += stat_value * stat_value

# После того как цикл завершится, выводим на экран итоговое накопленное значение.
print(total_power_index)

🎉 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, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!