Reputation: 35
I can't understand why some codes in Python are written with no indentation.
Both functions do the same thing but why the first function which is is_leap1 are writting in style with return only and no if statemnt? How did the first function return True and False without using if and else: ?
def is_leap1(year):
return year % 4==0and(year %100 !=0 or year %400==0)
print(is_leap1(2014))
def is_leap2(year):
if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
return True
else:
return False
print(is_leap2(2014))
output
False
False
Upvotes: 1
Views: 62
Reputation: 11
In the first function Logical operators are used which output True or False.
Since the condition year % 4==0 and (year %100 !=0 or year %400==0) is written using Logical AND, OR, these functions will compute the value and produce the value True or False, which is then finally returned using the return keyword from the function
Upvotes: 1
Reputation: 164673
Comparison operators such as ==
, !=
, <
, >=
, and
, or
, etc, all return Boolean values naturally. Therefore, you do not need to use if
statements to return True
or False
when using these operators. You can test this trivially yourself:
print(5 > 3) # True
print(True if 5 > 3 else False) # True
The official documentation makes this explicit:
Comparisons yield boolean values:
True
orFalse
.
Upvotes: 1