204k views
2 votes
Create a function to calculate and return the sum of all of the even numbers from 0 to the passed number (inclusive) using a while loop.

Create a function to calculate and return the sum of all of the even numbers from-example-1

1 Answer

3 votes

Answer:

def sum_evens(n):

# Initialize a variable to keep track of the sum

sum = 0

# Initialize a variable to keep track of the current number

current = 0

# Loop until the current number is greater than the passed number

while current <= n:

# If the current number is even, add it to the sum

if current % 2 == 0:

sum += current

# Increment the current number

current += 1

# Return the sum

return sum

User Chris Noe
by
8.0k points

No related questions found

Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.