Печать «количества» четных чисел в цикле с if

Я полагаю, что смогу выполнить следующее в Python...

Заполните пробелы, чтобы завершить функцию «even_numbers (n)». Эта функция должна подсчитывать, сколько четных чисел существует в последовательности от 0 до заданного числа «n», где 0 считается четным числом. Например, even_numbers(25) должен вернуть 13, а even_numbers(6) должен вернуть 4.

def even_numbers(n):
   count = 0
   current_number = 0
   while ___ # Complete the while loop condition
       if current_number % 2 == 0::
           ___ # Increment the appropriate variable
       ___ # Increment the appropriate variable
   return count
   
print(even_numbers(25))   # Should print 13
print(even_numbers(144))  # Should print 73
print(even_numbers(1000)) # Should print 501
print(even_numbers(0))    # Should print 1

Я перепробовал все возможные варианты изменения каждой переменной, о которой только мог подумать. Я сослался на курсовую работу (я застрял на этом вопросе в течение целой недели и считаю), я искал переполнение стека и нашел несколько вариантов, чтобы ссылаться не совсем на то, что мне нужно делать (и наиболее продвинутый из того, где я учусь прямо сейчас ... даже если они решают проблему, которую они не решают ... Я все равно попробовал их, надеясь, что лампочка погаснет, но это не так).

Я пытался заставить разделы print(even_numbers(#)) совпадать... заставить скрипт работать.

Есть ли кто-нибудь, кто может объяснить это мне, не давая прямого ответа? Очень хочется понять, где я ошибаюсь и почему. Я полный новичок и в основном самоучка по книгам.

Попытки (их несколько)


def even_numbers(n):
    count = 0
    current_numbers = 0
    while n > current_numbers: # Complete the while loop condition
        if current_numbers % 2 == 0:
            count = count + 1 # Increment the appropriate variable
        else:
            current_numbers = current_numbers + 1 # Increment the appropriate variable
    return count
    
print(even_numbers(25))   # Should print 13
print(even_numbers(144))  # Should print 73
print(even_numbers(1000)) # Should print 501
print(even_numbers(0))    # Should print 1

Evaluation took more than 5 seconds to complete.
                Please try again with a simpler expression.

def even_numbers(n):
    count = 0
    current_number = 0
    while n > current_number: # Complete the while loop condition
        if current_number % 2 == 0:
           count = count + 1 # Increment the appropriate variable
        else:
            current_number = current_number + 1 # Increment the appropriate variable
    return count

print(even_numbers(25))   # Should print 13
print(even_numbers(144))  # Should print 73
print(even_numbers(1000)) # Should print 501
print(even_numbers(0))    # Should print 1

Evaluation took more than 5 seconds to complete.
                Please try again with a simpler expression.

def even_numbers(n):
    count = 0
    current_numbers = 1
    while n > current_numbers: # Complete the while loop condition
        if current_numbers % 2 == 0:
           count = count + 1 # Increment the appropriate variable
           current_numbers = current_numbers + 1
        else:
           current_numbers = current_numbers + 1 # Increment the appropriate variable
    return count
    
print(even_numbers(25))   # Should print 13
print(even_numbers(144))  # Should print 73
print(even_numbers(1000)) # Should print 501
print(even_numbers(0))    # Should print 1

12
71
499
0

где 0 считается четным числом" - я в ужасе от того, что они это сказали. Может ли кто-нибудь найти определение «четного числа», где 0 не является четным?

Kelly Bundy 09.04.2023 07:30
Почему в Python есть оператор "pass"?
Почему в Python есть оператор "pass"?
Оператор pass в Python - это простая концепция, которую могут быстро освоить даже новички без опыта программирования.
Некоторые методы, о которых вы не знали, что они существуют в Python
Некоторые методы, о которых вы не знали, что они существуют в Python
Python - самый известный и самый простой в изучении язык в наши дни. Имея широкий спектр применения в области машинного обучения, Data Science,...
Основы Python Часть I
Основы Python Часть I
Вы когда-нибудь задумывались, почему в программах на Python вы видите приведенный ниже код?
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
Алиса и Боб имеют неориентированный граф из n узлов и трех типов ребер:
Оптимизация кода с помощью тернарного оператора Python
Оптимизация кода с помощью тернарного оператора Python
И последнее, что мы хотели бы показать вам, прежде чем двигаться дальше, это
Советы по эффективной веб-разработке с помощью Python
Советы по эффективной веб-разработке с помощью Python
Как веб-разработчик, Python может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
1
1
986
5
Перейти к ответу Данный вопрос помечен как решенный

Ответы 5

В коде задания нет else:. Вам нужно увеличивать current_number каждую итерацию, а не только когда число нечетное. В противном случае вы застрянете на одном и том же номере, когда он будет четным. Поэтому вам не следует добавлять блок else:.

Кроме того, результаты должны учитываться n, если они четные, поэтому условие должно быть current_number <= n.

def even_numbers(n):
    count = 0
    current_number = 0
    while current_number <= n: # Complete the while loop condition
        if current_number % 2 == 0::
            count += 1 # Increment the appropriate variable
        current_number += 1 # Increment the appropriate variable
    return count

Мне нравится твоя последняя попытка. Вам нужно начать current_number с 0 и обязательно использовать знак больше или равно:

def even_numbers(n):
    count = 0
    current_numbers = 0
    while n >= current_numbers: # Complete the while loop condition
        if current_numbers % 2 == 0:
           count = count + 1 # Increment the appropriate variable
           current_numbers = current_numbers + 1
        else:
           current_numbers = current_numbers + 1 # Increment the appropriate variable
    return count
    
print(even_numbers(25))   # Should print 13
print(even_numbers(144))  # Should print 73
print(even_numbers(1000)) # Should print 501
print(even_numbers(0))    # Should print 1
Ответ принят как подходящий

Вы считаете четные числа от current_number == 0 до current_number == n, поэтому вы должны инициализировать current_number до 0, а условие цикла должно быть current_number <= n.

Изменив вашу третью попытку, код должен быть:

def even_numbers(n):
    count = 0
    current_number = 0
    while n >= current_number: # Complete the while loop condition
        if current_number % 2 == 0:
           count = count + 1 # Increment the appropriate variable
           current_number = current_number + 1
        else:
           current_number = current_number + 1 # Increment the appropriate variable
    return count
    
print(even_numbers(25))   # Should print 13
print(even_numbers(144))  # Should print 73
print(even_numbers(1000)) # Should print 501
print(even_numbers(0))    # Should print 1

Наконец, строка current_number = current_number + 1 находится как в ветви if, так и в ветви else, поэтому вы можете извлечь ее и удалить else:

def even_numbers(n):
    count = 0
    current_number = 0
    while current_number <= n: # Complete the while loop condition
        if current_number % 2 == 0:
            count += 1 # Increment the appropriate variable
        current_number += 1 # Increment the appropriate variable
    return count

Всем спасибо! Эти ответы очень помогли, и я записал их для дальнейшего использования (надеюсь, чтобы не рвать на себе волосы неделю...)

Brittney Hanna 09.04.2023 05:08

Это дало мне правильный ответ

def even_numbers(n):
   count = 0
   current_number = 0
   while current_number <= n:
       if current_number % 2 == 0:
           count += 1
       current_number += 1
   return count
   
print(even_numbers(25))
print(even_numbers(144))
print(even_numbers(1000))
print(even_numbers(0))

Это тоже работает, и я бы абсолютно согласен с этим.

def even_numbers(n):
   count = 0
   current_number = 0
   while not current_number: # Complete the while loop condition
       if current_number % 2 == 0:
           count += n // 2 + 1 # Increment the appropriate variable
       current_number = 1 # Increment the appropriate variable
   return count

Другие вопросы по теме