Python Forum
Algorithm for leap year (structogramm - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Algorithm for leap year (structogramm (/thread-34351.html)



Algorithm for leap year (structogramm - coder_sw99 - Jul-22-2021

Hello!

Before I solve a problem I usually always draw a structogramm and then start to code. But I just can´t find a way how to code
this structogramm. I have the feeling that I´m doing something wrong with the if-statements

I would be very happy if you could code exactly this structogramm attached to this thread and show me how you would do it!

Thanks
SW

This is the structogram: https://ibb.co/NKtMLrC


leap = 0

year = int(input("Please type in your year :"))


if year%4 == 0:
    pass
    if year%100 == 0:
        pass
    else:
        leap = 1

        if year%400 == 0:
            leap = 1
        else:
            pass

if leap == 1:
    print("This year is a leap year")

else:
    print("This year isn´t a leap year")



RE: Algorithm for leap year (structogramm - perfringo - Jul-23-2021

One way to look at this problem: define two cases for leap year and use or to stitch them together:

- divisible by 4 and not divisible by 100 -> leap years, but misses years divisible by 400
- divisible by 400 -> leap years missed in first case

In Python code it can be expressed something like below, returns True if leap year, False if not; if first case is true then or condition will not be evaluated, if first case is false then or kicks in and result of second case evaluation will be returned:

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



RE: Algorithm for leap year (structogramm - coder_sw99 - Jul-23-2021

Thanks a lot! This is big help


RE: Algorithm for leap year (structogramm - DeaD_EyE - Jul-23-2021

You can use calendar.isleap(year).

In [1]: import calendar

In [2]: calendar.isleap(2020)
Out[2]: True
And this is the implementation:
In [3]: calendar.isleap??
Signature: calendar.isleap(year)
Source:   
def isleap(year):
    """Return True for leap years, False for non-leap years."""
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
File:      ~/.pyenv/versions/3.9.6/lib/python3.9/calendar.py
Type:      function