• 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«Accumulation of funds for purchase»

You work as a programmer in a company that creates a "digital archive of personal files." Your task & mdash; Develop a module to verify the introduced dates. The system should be absolutely reliable and not accept incorrect or impossible dates (for example, on February 30 or April 31), as well as data in the wrong format.

rn

The program must read the lines one after another until the user introduces & nbsp; 0 . For each introduced line, it is necessary to check: whether it is a correct, existing date in the & nbsp; dd.mm.YYYY .

Input format

The program receives several lines to the input. Each line contains either a date for verification or an arbitrary set of characters. Data entry ends when a symbol & nbsp; 0 .

is introduced in a separate line.

Output format

for each entered line (except for the final line & nbsp; 0 ), the program should display in a new line:

rn
    rn
  • the correct date & nbsp; & mdash; If the line is the existing date in the & nbsp; DD.MM.YYYY . In all other cases (incorrect format, non -existent date).
  • rn

Example

Input

12.12.2024
31.04.2023
02.29.2023
Hello World
02.29.2024
01/01/2000
0

Output

The correct date
incorrect date or format
incorrect date or format
incorrect date or format
correct date
correct date

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
import datetime

while True:
    # Считываем очередную строку от пользователя
    input_str = input()

    # Проверяем условие выхода из цикла
    if input_str == '0':
        break

    try:
        # Пытаемся преобразовать строку в дату по заданному формату.
        # Формат '%d.%m.%Y' означает:
        # %d - день месяца с ведущим нулем (01-31)
        # %m - месяц с ведущим нулем (01-12)
        # %Y - год в виде четырех цифр (например, 2024)
        #
        # Эта функция автоматически проверяет и формат, и существование даты.
        # Например, для "30.02.2024" она вызовет ошибку, так как такой даты нет.
        datetime.datetime.strptime(input_str, '%d.%m.%Y')
        
        # Если преобразование прошло успешно, значит дата корректна
        print("Корректная дата")

    except ValueError:
        # Если в процессе преобразования возникла ошибка ValueError,
        # это означает, что либо формат строки не соответствует 'ДД.ММ.ГГГГ',
        # либо сама дата невозможна (например, 31 апреля).
        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, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!