• 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«Calculation of the number of fibonacci»

you & mdash; A researcher in the fantasy world studying magic crystals. You have found that these crystals are growing according to a special law that is very reminiscent of an ancient mathematical sequence.

rn
    rn
  • rn
  • rn
  • rn
rn

You need to write a program that will help you predict the growth of crystals. The program should request from the user the number of the month & nbsp; n & nbsp; and calculate how many whole crystals you will have by the end of this month.

rn

Technical requirements:

rn
    rn
  1. the program must request one whole. number & nbsp; n & nbsp; & mdash; number of the month.
  2. rn
  3. you need to calculate Use & nbsp; Cycle & nbsp; While .
  4. rn
  5. the program should correctly Process special cases: & nbsp; n = 0 & nbsp; and & nbsp; n = 1 . Style = "Font-Size: 14pt;"> If the user introduces a negative number or text instead of the number, the program must display an error message: & nbsp; "Error: introduced incorrect value."
  6. rn
  7. the result must be displayed in the format: & nbsp; " the number of fibonacci for n = [month] equals: [result] "
  8. rn

    & nbsp;

    Input format

    number of the month & nbsp; n for calculation (a whole non-negative number).

    Output format

    The final number of crystals (the number of fibonacci) in the form of a formatted line or error message (line).

    Example

    Input

    10

    Output

    The number of fibonacci for n = 10 is: 55

    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_str = input()

# Проверяем, состоит ли введенная строка только из цифр
if not n_str.isdigit():
    # Если нет, выводим сообщение об ошибке
    print("Ошибка: введено некорректное значение.")
else:
    # Преобразуем строку в целое число
    n = int(n_str)

    # Обрабатываем базовые случаи n=0 и n=1
    if n == 0:
        # Для 0-го месяца результат 0
        result = 0
        print(f"Число Фибоначчи для n = {n} равно: {result}")
    elif n == 1:
        # Для 1-го месяца результат 1
        result = 1
        print(f"Число Фибоначчи для n = {n} равно: {result}")
    else:
        # Инициализируем первые два числа последовательности
        a, b = 0, 1
        # Инициализируем счетчик, начинаем со второго числа, так как 0 и 1 уже есть
        count = 1

        # Запускаем цикл, который будет работать, пока мы не достигнем нужного месяца n
        while count < n:
            # Вычисляем следующее число Фибоначчи
            # a становится b, а b становится суммой старых a и b
            a, b = b, a + b
            # Увеличиваем счетчик на 1
            count += 1
        
        # После завершения цикла в переменной 'b' находится n-ое число Фибоначчи
        result = b
        print(f"Число Фибоначчи для n = {n} равно: {result}")

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