• 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«Name on the advertising shield»

you got a job in the creative advertising agency "creativeplus". Your first task & mdash; Create a calculator to calculate the cost of placing text on an advertising shield. The agency director came up with a cunning pricing system to stimulate customers to choose “sonorous” and “safe” names.

rn

rules for calculating the rules for calculating cost:

rn
    rn
  1. basic cost: & nbsp; the cost of one symbol is entered User.
  2. rn
  3. gaps: & nbsp; They are paid, they are free.
  4. rn
  5. a vowel stand: & nbsp; vowels (Russian and English, in any register) They are considered more “attracting attention”, therefore their cost is 50% higher than the base.
  6. rn
  7. prohibited Symbols: & nbsp; symbols & nbsp; '@' & nbsp; and & nbsp; '#' & nbsp; prohibited for use on technical reasons. If at least one of them is found in the name, the calculation is impossible, and the program should display an error message.
  8. rn
  9. happy Symbol: & nbsp; a symbol of the exclamation mark ( '!' ) is part of a special action. It is free in itself, but if it is present in the name, on & nbsp; the final & nbsp; the cost of the entire inscription is given a 10%discount.
  10. rn

    You need to write The program that requests the user the name and basic cost of the symbol, and then calculates and displays the total price taking into account all the rules.

    Input format

    the name for the advertising shield (string)

    Output format

    The total cost is up to two signs after aim or a error message

    Example

    Input

    The best price!
    100.0

    Output

    Final cost: 1125.00 rub.

    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
# Получаем название для рекламы и базовую стоимость одного символа
ad_text = input()
base_price = float(input())

# Инициализируем переменные для итоговой стоимости и флагов
total_cost = 0.0
has_forbidden_char = False
has_discount_char = False

# Список гласных букв в нижнем регистре (русские и английские)
vowels = "аеёиоуыэюяaeiou"

# Перебираем каждый символ во введенном тексте с помощью цикла for
for char in ad_text:
    # Проверяем, не является ли символ запрещенным
    if char == '@' or char == '#':
        has_forbidden_char = True  # Устанавливаем флаг, что найден запрещенный символ
        break  # Немедленно прерываем цикл, дальнейший расчет бессмысленен

    # Если символ - пробел, он бесплатный, переходим к следующему символу
    if char == ' ':
        continue

    # Если символ - восклицательный знак, он бесплатный, но дает право на скидку
    if char == '!':
        has_discount_char = True  # Устанавливаем флаг скидки
        continue

    # Рассчитываем стоимость текущего символа
    current_char_price = base_price

    # Проверяем, является ли символ гласной (приведя его к нижнему регистру)
    if char.lower() in vowels:
        current_char_price = current_char_price * 1.5  # Применяем наценку 50%

    # Добавляем стоимость текущего символа к общей стоимости
    total_cost = total_cost + current_char_price

# После цикла проверяем, был ли найден запрещенный символ
if has_forbidden_char:
    print("Ошибка: в названии содержатся запрещенные символы.")
else:
    # Если запрещенных символов не было, проверяем, нужно ли применить скидку
    if has_discount_char:
        total_cost = total_cost * 0.9  # Применяем скидку 10%

    # Выводим итоговую стоимость, отформатированную до двух знаков после запятой
    print(f"Итоговая стоимость: {total_cost:.2f} руб.")

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