Introduction

Welcome! In today's lesson, we'll delve into a unique coding challenge that centers around traversing the digits of a number using a while loop under a specific condition. You'll have the opportunity to practice and enhance your skills in working with Python's loops and conditional statements - fundamental concepts in programming. Are you as excited as I am? Let's dive in!

Task Statement
Solution Building: Step 1

To start, we need the basic structure of our function, where we begin by defining a variable digit_sum to keep track of the sum of even digits.

Below is the initial platform for our function:

def solution(n):
    digit_sum = 0
    # Our code will evolve from here
Step 2: Setting up the Loop

The tool we've chosen to traverse through the digits of the input integer n is the while loop, which is set to run as long as n is greater than zero. Let's incorporate this into our function:

def solution(n):
    digit_sum = 0
    while n > 0:
        # We'll develop our function from here
Step 3: Extracting and Processing Each Digit

Inside our loop, we'll first extract the last digit of n using the modulo operation (n % 10). If the digit is even, we'll increase our digit_sum by this digit.

After processing a digit, we'll then chop off the last digit of n using integer division (n // 10), which allows the while loop to proceed to the next digit. Here's how this appears in the code:

def solution(n):
    digit_sum = 0
    while n > 0:
        digit = n % 10
        if digit % 2 == 0:  # Check if the digit is even
            digit_sum += digit
        n = n // 10  # Remove the last digit
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal