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

Lesson 5. While cycle

Difficulty level:

Task«Finding an average value in the list»

💻 Python

You work for a company that produces futuristic gadgets. Your new product is a bio-tracker "Vita-Pulse", which measures the user's "vital energy indicator" every day. At the end of the week, the device generates a final report in the form of a single string. Your task is to write a program that analyzes this report.

The program should extract the user's name and their weekly indicators from the string. Then, using a while loop, it should calculate the average of only positive indicators. A positive indicator means a good, energetic day. Negative indicators (stress, fatigue) and zero values (neutral day) should not be included in the average calculation.

You need to process the input string, convert the numeric data from string type to numeric (you can use a for loop for this), and then use a while loop to find the sum and count of positive indicators to compute the average.

Input format

line (string), which always has the following view: & nbsp; "name: [user name]; indicators: number through a gap]" . For example, & nbsp; Name: Alexey; Indicators: 10 -5 22 0 -12 18 7 .

Output format

The line (string) containing the user name and the average value of its positive indicators. If there were no positive reasons for a week, you need to display a special message.

Example

Input

Name: Elena; Indicators: 15 -4 25 0 10 -8 5

Output

Elena, the average indicator of your life energy for the week: 13.75

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
# Получаем на вход одну строку с данными от био-трекера
input_string = input()

# Разделяем строку на две части по символу ';'
# parts будет списком, например: ['Имя: Елена', ' Показатели: 15 -4 25 0 10 -8 5']
parts = input_string.split(';')

# Из первой части извлекаем имя
# Сначала разделяем 'Имя: Елена' по ':', получаем ['Имя', ' Елена']
# Берем второй элемент ' Елена' и убираем пробелы по краям с помощью strip()
user_name = parts[0].split(':')[1].strip()

# Из второй части извлекаем строку с показателями
# Аналогично получаем ' 15 -4 25 0 10 -8 5' и убираем пробелы
scores_string = parts[1].split(':')[1].strip()

# Разделяем строку с показателями по пробелу, чтобы получить список строк
# ['15', '-4', '25', '0', '10', '-8', '5']
str_numbers = scores_string.split()

# Создаем пустой список для хранения чисел
numbers = []
# Используем цикл for для преобразования каждой строки в списке в целое число
for s_num in str_numbers:
    numbers.append(int(s_num))

# Инициализируем переменные для цикла while
sum_of_positives = 0  # Сумма положительных чисел
count_of_positives = 0  # Количество положительных чисел
index = 0  # Индекс для перебора списка
list_length = len(numbers) # Длина списка, чтобы знать, когда остановиться

# Основной цикл while для подсчета среднего значения
while index < list_length:
    # Получаем текущее число из списка по индексу
    current_number = numbers[index]
    
    # Проверяем, является ли число строго положительным
    if current_number > 0:
        # Если да, добавляем его к сумме
        sum_of_positives += current_number
        # и увеличиваем счетчик положительных чисел
        count_of_positives += 1
    
    # Переходим к следующему элементу списка
    index += 1

# После цикла проверяем, были ли найдены положительные числа
if count_of_positives > 0:
    # Если да, вычисляем среднее значение
    average = sum_of_positives / count_of_positives
    # Выводим результат в заданном формате
    print(f"{user_name}, средний показатель вашей жизненной энергии за неделю: {average}")
else:
    # Если положительных чисел не было, выводим другое сообщение
    print(f"{user_name}, на этой неделе не было дней с положительными показателями.")

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

AI Helper

Hi! I am your programming assistant. Ask me anything about Python — I can explain functions, methods, and help you understand the current task!