340,079 views
15 votes
15 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
User Doa
by
3.0k points

1 Answer

18 votes
18 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 Rodrigo A
by
3.3k points