Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking to see if a number ends in 5?

Tags:

python

I'm trying to define a function that takes 2 parameters, adds them up, and if the sum of the two parameters ends in 5, it reports a 2. If it doesn't end in 5, it returns 8.

Any ideas?

I was thinking of doing an if statement, but I'm confused as to how I would check if a number ends in 5( or is 5).

Thanks for your help, trying to teach myself how to program is so difficult yet so rewarding :)

like image 827
Billy Thompson Avatar asked Dec 06 '25 08:12

Billy Thompson


1 Answers

Solution

My answer assumes you are checking integers (which seems pretty reasonable judging from your question):

def sum_ends_with_5(a, b):
    """
    Checks if sum ends with "5" digit.
    """
    result = a + b
    return 2 if result % 10 == 5 else 8

or more flexible (with any number of arguments):

def sum_ends_with_5(*args):
    """
    Checks if sum ends with "5" digit.
    """
    result = sum(args)
    return 2 if result % 10 == 5 else 8

How it works (aka tests)

The function behaves like that:

>>> sum_ends_with_5(5)
2
>>> sum_ends_with_5(3)
8
>>> sum_ends_with_5(2, 8)
8
>>> sum_ends_with_5(7, 8)
2
>>> sum_ends_with_5(10, 20, 3, 2)
2

Shorter version

So, if you want to write it in shorter and more flexible way, you can do this:

def sum_ends_with_5(*args):
    return 2 if sum(args) % 10 == 5 else 8
like image 194
Tadeck Avatar answered Dec 08 '25 20:12

Tadeck