'Year to Century Function Code Understanding

Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200. For year = 1905, the output should be centuryFromYear(year) = 20. For year = 1700, the output should be centuryFromYear(year) = 17.

Solution:

def centuryFromYear(year):
    if year % 100 == 0:
        return year/100
    else:
        return int(year/100) + 1

I tried the following code:

def centuryFromYea(year):
    return year % 100

I tried other solutions and received errors. I need an explanation on why the if statement is set to equals to 0 and if true return to year/100. I also need an explanation on the else return.



Solution 1:[1]

year % 100 value is the same like year / 100 ONLY if year % 100 == 0.

Example: If year is 2000 both expressions will return 20.

If it is not the case it means that the year is not a round multiple of 100.

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].

Solution 2:[2]

def solution(year):
    if year % 100 != 0:
        return year//100 +1
    else:
        return year/100

Solution 3:[3]

if statement is for the cases like 1200,1300,1700, 

where year%100 will result 0.

else statement is for all the other cases like 1201(13),1705(17) , where year%100 is not equal to 0.

Ex. 1201, solution: 
centuryFromYear(year) = 13
1201 % 100 = 1 which is not equal to zero
so it should return (1201/100) + 1  = 13

not : 1201/100 = 12

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 balderman
Solution 2 richardec
Solution 3 Junior_K27