- Practice
- Python
- Introduction
- Write a function
- Discussions

# Write a function

# Write a function

kpagcha + 40 comments For the learners: you should know that doing something like the setup for this challenge inclines you to do is a bad practice. Never do the following:

def f(): if condition: return True else: return False

This is just dumb. You are returning a boolean, so why even use if blocks in the first place? The correct what of doing this would be:

def f(): return condition

Because this already evaluates as a boolean.

So in this challenge, forget about ifs and elses, and that leap variable, and just do the following:

def is_leap(year): return year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)

Don't be redundant, be DRY.

dujincong_dufe + 3 comments How does the "return year%4==0..." sentence know what you are returning is a boolean? Is that defined by "def is_leap"? Thank you

kpagcha + 4 comments because all expressions used in that return statement evaluate to booleans

IndianRockPython + 0 comments thanx

_Kalpesh_ + 0 comments thanks brother

Krishnasaivamsi + 0 comments sir,can you give a clear description about return statements

omj1206 + 2 comments That exactly is not the case. Try to run following code in interpreter:

def is_leap(year):

`return (not(year%4) and ((year%100) or not(year%400)))`

Invoke it using

is_leap(1464)

It returns 64 instead of True. Thats because the expression (year%100) returns 64

omj1206 + 0 comments to mitigate that run following code and that returns either True or False:

def is_leap(year): return (not(year%4) and (bool(year%100) or not(year%400)))

apatil_cs + 0 comments How does that contradict what that guy said? You wrote different code than what he wrote. You're exploiting "truthy/falsey" values; the other guy's just using regular booleans

srious + 0 comments Check out python truthiness

jasar002 + 0 comments [deleted]

ajayi + 0 comments some of us do that for clarity sake for those who may have a hard time processing what is going on.

darshanjadav97 + 3 comments This is what i did.

def is_leap(year): if year%4==0: return True elif year%100==0: return False elif year%400==0: return True

Thanks for explaining

arpita0116 + 1 comment the first if statement if year%4==0: return True this will give true for 1900 year also but that it is not true

snath402 + 0 comments you have to give the constraint like

if year in range(1900,pow(10,5)+1): because they clearly mentioned this constraintr

a_kamal_89 + 2 comments You can just reverse the order and it will be fine.

zrolpin + 2 comments Reversing the order almost works, but you have to add an

`else`

block returning`False`

at the end to capture cases where none of the`if`

blocks execute (like for the year 1992) and also change all`elif`

statements to`if`

statements. I.e:def is_leap(year): if year % 400 == 0: return True if year % 100 == 0: return False if year % 4 == 0: return True else: return False

This passes all the test cases.

sjayanthkumar191 + 0 comments i will mark your words

bmp17c + 0 comments not passes year %100 == 0 test

navi7299 + 0 comments I reversed the order and it passed all the tests. But i dont know why it did. what did the reversing the order do??

ryoutausami_pyd1 + 4 comments Took a few tries before I understood the conditions but I got it!

Here's my solution:

`if year % 4 == 0: if year % 100 != 0: leap = True elif year % 400 == 0: leap = True return leap`

hhelzer + 0 comments That wound up failing two test cases.

Krishnasaivamsi + 1 comment how can you return heap without any function

Dvcks + 0 comments This quote

*is*the function. The post doesn't include the declaration because it's not relevant.

sjayanthkumar191 + 0 comments fail in two cases

dhagist + 5 comments What about trying something like this:

`if year % 4 == 0: leap = True if year % 400 == 0: leap = True elif year % 100 == 0: leap = False`

pratibhakumar225 + 0 comments this works for all test cases

hgahlot50 + 0 comments It fails for the year 2100

snath402 + 1 comment It is giving runtime error

pratibhakumar225 + 0 comments def is_leap(year): leap = False if year % 4 == 0: leap = True if year % 100 == 0: leap = False if year % 400 == 0: leap = True return leap

`It woked for me in all cases... Use a proper identation`

abhinavrubitry + 0 comments make the last loop as elif year%100!=0: return True

this will work for all the cases

zycarlton09 + 0 comments Good Work ！ I think I ignored the "unliess" in the problem sheet. I learned the if and elif, but never used them. This is an interesting question.

bjohnston370 + 5 comments You can write it without parentheses like this:

def is_leap(year): return year % 4 == 0 and year % 100 != 0 or year % 400 == 0

amitrajitbose9 + 1 comment Adding parenthesis increases readability. I might be wrong though!

def is_leap(y): return ((y%4==0)and(y%100!=0)or(y%400==0))

karthik_bharadh1 + 2 comments what is the logic of this.....man!!!!

agarwal_rishika7 + 0 comments here, the return statement returns in boolean. where the given conditions in the problem are put.a year is a leap year if it is divisible by 4 and 400 but not divisible by 100.

amitrajitbose9 + 0 comments You may find the

**logic**here.

ingoglia + 2 comments But then how does python know which one you mean: 1.y%4 AND y%100, or y%400

2.y%4, and y%100 OR y%400?

That's like saying these sentences state the same thing: 1.I will eat pie and roaches, or I will eat pasta.

2.I will eat pie, and either I will eat roaches or pasta.

Am I missing something?

jrmioduszewski + 0 comments Just like there is order of operations for mathematical operators, there is precedence for Python operators. AND has higher precedence than OR, so it is evaluated first.

rfstahl + 0 comments Order of precedence: NOT > AND > OR

ujezidonye + 0 comments Thanks for this. I was having issues with If/ else statements.

valanukonda1999 + 1 comment plss explain this a bit clear how return works their

agarwal_rishika7 + 0 comments here solving the given condition, return turns true

Krishnasaivamsi + 1 comment can you please explain the code.

amitrajitbose9 + 0 comments I think this is a good read, to understand the logic of a leap year. The code is straight forward.

sri_sam229 + 0 comments good one man.you seem to have pretty good understanding of python PEP.

zusammen + 1 comment why parenthesis are required and we get error without them??

codeharrier + 0 comments Associativity.

'a and b or c' reads like '(a and b) or c' to the interpreter.

'a and b' is only true every 400 years.

c is true every year except those divisible by 100, so you're marking only 3 years out of every 400 as non-leap years.

hamzabouabid7 + 1 comment if** year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)** is true the how the true boolean is affected to leap variable since we didn't you didn't make leap=something? I hope you get the idea

agarwal_rishika7 + 0 comments def is_leap(year): return year%4==0 and (year%400==0 or year%100!=0)

`by using this , you will get ur answer . you dont have to use an extra variable 'leap'`

chadwalt + 0 comments this is nice. it avoids repetition. Thanks alot.

intenseCtraining + 0 comments learners need to code like this imo. I use some of these programs with my classes and they simply dont understand any inline return equation, hell some of them dont even return values properly

scotmatson + 0 comments I agree, the multiple return statements are a tad heavy and go against DRY coding practices. However, your recommended solution also sacrifices readability, which IMO is more important than trying to massage your code into a single statement.

Be succinct but be readable. Let your bundlers handle the optimizations.

dhinastallion + 0 comments [deleted]sam_fold + 1 comment Your answer isn't really very clean code though. So while it works, it isn't very readable, which IMO is incredibly important.

abhishekreddy041 + 1 comment IMO means..?

hhelzer + 1 comment IMO = "in my opinion"

also there's

IMHO = "in my humble opinion" (which is often not very humble at all)

abhishekreddy041 + 0 comments thank u

Muttnstuff + 0 comments Thanks that explained it so clearly

Zawaldo + 0 comments Makes perfect sense, thank you very much for your explanation!

Adivareyhanptr + 0 comments can you explain why you use the 'or' operator instead of 'and' for the 'year%100 != 0'? i still don't get it. thank you

wanglei_okay + 0 comments I like your func very much

himanshu_chauhan + 0 comments That's way shorter than my if and else loop's. Thanks.

ftakelait + 0 comments Hi @kpagcha,

Thanks for your detail explanation for this problem. Could you please explaine to me the relationship of your answer and the problem context, please? Because I didn't understand well the answer.

I want to unerstand how did you formulated these steps in this form you had programmed

In the Gregorian calendar three criteria must be taken into account to identify leap years:

**1. The year can be evenly divided by 4; 2. If the year can be evenly divided by 100, it is NOT a leap year, unless; 3. The year is also evenly divisible by 400. Then it is a leap year**Thanks for advance. Fouzi

gaurav_sonkusle + 0 comments very effective buddy.... thnk u

beckwithdylan + 0 comments if you want to reduce redundancy, why not also return the bool of the comparisons to avoid explicitly checking for zero equivalency..

def is_leap(year): return bool(not year % 4 and (year % 100 or not year % 400))

irregardless.. you deserve an upvote

Anaximandrake + 0 comments Your solution is certainly the most elegant, but when the user is first presented with the problem in the coding box, the return command has already been given the object 'year' and we are given a #Write your logic here note

**above**it. So it's at least forgivable for some of us to construct multiple 'if' blocks to solve it, wouldn't you agree?sachinsavita95 + 0 comments it is not passing all the test cases?

Veerubhotla + 0 comments thanks :D

zpf7879 + 0 comments Might be clearer:

def is_leap(year): return year % 400 == 0 or year % 4 == 0 and year % 100 != 0

guardadopatrici1 + 0 comments Hi just a question about parenthesis placement why does placing a parenthesis like below year % 4 == 0 and (year % 400 == 0 or year % 100 != 0) is correct code versus not placing parenthesis at all or writting it like ((y%4==0)and(y%100!=0)or(y%400==0)) results in error

JayPatel2810 + 0 comments thanks for advice, keep commenting :)

mayank_sept92 + 0 comments Hi, thanks for the shorter approach but, what about the condition-- 1900<= year <=10**5

[deleted] + 0 comments Thank you sir for the advice.

Zvezdobroeca + 0 comments Thanks for this. I've been learning for 4 days now and I really want to be a good coder that abides by the zen of python. Because of your advice I've turned the default code:

def is_leap(year): leap = False if 1900 <= year <= 10**5 and year % 4 == 0 and \ (year % 100 != 0 or year % 400 == 0): leap = True return leap year = int(input()) print(is_leap(year))

into this DRY code:

def is_leap(): return 1900 <= year <= 10**5 and year % 4 == 0 and \ (year % 100 != 0 or year % 400 == 0) year = int(input()) print(is_leap())

I'm sure there are ways to improve this further.

chefyunfei + 0 comments That's crazy simple. Wow. I did do if elif and elif. if year%4 == 0: leap = True elif year % 100 == 0: leap = False elif year % 400 == 0: leap = True

`for some reason it was wrong for 2100 the test case too. That makes so much sense. and makes it so that both have to be true. Truly a masterful stroke.`

ctrlshftenter + 0 comments agree with you on "dry" . succintness is power and a bloated code is such a waste of python zen.

moreover i dislike it that the code is partially provided: it shoeboxes one into a specific pattern (priming).

the instructions werebloatedtootoomucuunnecessaryinformationpresentedunclearlyinordertoappearsiphisticatedlikethislongword.

mai_tran1992 + 0 comments Well, the problem is set up with variable leap = False and then return leap at the end, which surely guides the beginners to the if-else method.

def is_leap(year): leap = False ### return leap

deepika121 + 1 comment how it will come can u explain

sjayanthkumar191 + 0 comments its a mistake he may copied and pasted the code..

abhijeetanythin1 + 0 comments but for 1900,its divisible by 4 but also by 100..so how is that code possible

letitslide87 + 0 comments Wow, amazing comment, thank you!

dillingerjames + 0 comments Thanks for the lesson. For other newbies here is a good article worth reading that will clarify the syntax: https://www.codesdope.com/python-boolean/

jadhav_rohan100 + 0 comments failed 2 cases

zrolpin + 0 comments Your code is certainly shorter, but you also make a slight sacrifice in readability. Of course, the 'readability' of your code will depend on the experience level of the reader. But you won't always be working with talented programmers. For many, I think the following code is more readily understandable and its decrease in computational efficiency is marginal:

def is_leap(year): if year % 400 == 0: return True if year % 100 == 0: return False if year % 4 == 0: return True else: return False

ENIGMA_96 + 0 comments Thanks for the advice. I am new to python and this something that i would have never thought of.

mrknowledge38 + 0 comments Thank you for the tip. The logic is so clear when I lok at your code. For whatever reason it isn't straightfoward reading from the problem statement.

am110 + 5 comments The calendar builtin module has a function isleap() that returns True if the year is leap, otherwise it returns False

import calendar def is_leap(year): return calendar.isleap(year)

michaelhuynhquoc + 1 comment What I just learnt from you: don't re-invent the wheel :D

super_geek + 0 comments true af

ajayi + 0 comments haha, you are the boss.

cssd1983 + 0 comments Amazing

chefyunfei + 0 comments That kind of defeats the point of this exercise doesn't it?

flmmartins + 4 comments The problem's explanation is not clear. I am not an english speaker and the bullet points were not clear enough for me.

Can that be improved?

Suggested explanation is bellow:

In the Gregorian calendar three criteria must be taken into account to identify leap years

`The year can be evenly divided by 4; If the year can be evenly divided by 100, then it is not a leap year The year is also evenly divisible by 400 then it is a leap year.`

veganXedge + 0 comments i agree. maybe this has something to do with my math skil level but, i couldn't understand how to properly figure out that(code below) was an acceptable way to write it.

year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)

i would like to understand or have some sort of guide on how to better interpret these questions.

iamphanisai + 0 comments yes. i too faced the same problem and had to google what a gregorian calendar was and found a page long explanation about how julias caesar invented it... etc etc before actually understanding what it means!

scotmatson + 1 comment Agree.

I am an English speaker and struggled with this definition. It was poorly written.

xbuildx_matrix + 0 comments I agree

kasunr + 1 comment My answers are ...

def is_leap(year): leap = False if year %4 == 0: if year %400 == 0: leap = True elif year %100 == 0: leap = False else: leap = True else: leap = False return leap

or

return (year %4 == 0 and year %100 != 0 or year %400 == 0)

chefyunfei + 0 comments Pretty much what I did, but I don't htink I nested the arguments under if year%4 so it ended up being wrong.

JonathanV + 2 comments Working

if year%4 == 0 and (year%100 != 0 or year%400 == 0): leap = True

Vangelic_surgeon + 1 comment Thanks this stupid problem took me more time to solve and even the official solution is s**t

KavinRanawella + 0 comments if u are refering to the solution under the editorial tab, I would say, it is more elaborating. I think either you have misread the question, or you haven't noticed that there are no 'elseif' logic in the given solution. Only 'if' statements are there. It suits the requirements perfectly. Read the solution again carefully. U'll get it. :)

tricerabottoms + 2 comments This one is a little longer but I think you'll find it easier to follow:

class is_leap: pass is_leap.__init__ = lambda s,y: setattr(s,'y',y) is_leap.__repr__ = lambda s: str((not s.y%4)^(not s.y%100)^(not s.y%400))

hamichok11 + 1 comment lol :D much easier!

cssd1983 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 1 comment LOL

saumitra13325 + 2 comments LOL

saumitra13325 + 0 comments [deleted]saumitra13325 + 0 comments Ahhh...got the end

bartyl + 0 comments :DDDD good joke

nishant_bhumca17 + 0 comments I think this is pretty starightforward :

def is_leap(year): return year % 4 == 0 if year % 100 != 0 else year % 400 == 0

Faker88Si + 0 comments Python 3

def is_leap(year): if year % 400 == 0: return True if year % 100 == 0: return False if year % 4 == 0: return True else: return False year = int(input())

n_aswath + 0 comments def is_leap(year): if year in range(1900,100000): if (year % 4) == 0 and (year % 100) == 0 and (year % 400) == 0: leap = True elif (year % 4) != 0 and (year % 100) == 0: leap = False elif (year % 4) == 0 and (year % 100) != 0: leap = True elif (year % 4) !=0: leap = False elif (year % 100) !=0: leap = False elif (year % 400) !=0: leap = False return leap

cnhnyu + 3 comments If a year is a leap year: 1. it can be evenly divided by 4 and NOT evenly divided by 100; OR 2. it can be evenly divided by 400

leap = False if any([year % 4 == 0 and year % 4 != 0, year % 400 == 0]): leap = True

alexandar_naray1 + 1 comment I like the use of any here, I didn't think of that. You could set

leap = any([year % 4 == 0 and year % 4 != 0, year % 400 == 0])

since any returns a boolean

cnhnyu + 1 comment Thanks, you're right. It's much simpler.

leap = any([year % 4 == 0 and year % 100 != 0, year % 400 == 0])

Correction: year % 4 == 0 and year % 100 != 0

marcon_zm + 2 comments What is the comma doing here exactly?

year % 100 != 0, year % 400 == 0

Is it testing the output of "%100 != 0", and if it returns false it tests for the "% 400 == 0" conditional?

alexandar_naray1 + 0 comments the any function takes an iterable so it is basically saying: if any of the items in this iterable is true return true. so the comma makes them elements of a list between the brackets.

cnhnyu + 0 comments You can think it as an OR operation in this case.

alexandar_naray1 expains it very well.

mohamedfardinkh1 + 0 comments How to use "any" function? What are it's cases ?

bad_coder_lol + 0 comments for some reason, the Hacker Rank team wasn't able to clarify that clearly

sandhyapandey961 + 0 comments def is_leap(year):

`leap=False if year%400==0: leap=True elif year%4==0: leap=True elif year%100==0: leap=False return leap why first statement leap= false is written?`

siraryangupta + 0 comments how can i can make 1992 show as a leap year

Sort 349 Discussions, By:

Please Login in order to post a comment