#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2017
    Posts
    2
    Rep Power
    0

    I need help with a program for practice.


    So I'm trying to write a program to that reads into a Notepad text file of years listed (1996, 1997, 1998, 2000, ect...), one per line, and determine whether a year is a leap year or not. If it is, I want to output to a separate file those that are in fact leap years. All I have so far is the function to calculate which years are leap years and it works, but I'm confused on how to get the rest of this program to work.

    Here's what I have so far:

    Code:
    # function
    def leap_year(year):
        """ Calculate whether a year is or isn't a leap year. """
        return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
    Any advice would be appreciated.
  2. #2
  3. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,898
    Rep Power
    509
    I'd write the program as a command line filter to read stdin and write to stdout. Then use shell redirection operators to handle the file names.

    A:> python3 myfile.py < years.txt > leapy.txt

    To handle file names I'd also put those on the command line. Try the following program for experimenting:
    Code:
    import sys
    print(sys.argv)
    and DOS command

    A:> python3 some arguments zowie

    In this case you'll need to open the files within your program, and in both cases you'll need to convert the strings read by the program into numbers. This program is an untested mixture of the two ideas.
    Code:
    with open('years.txt') as inf:
        year_str = inf.readline()
        year_int = int(year_str)
        if leap_year(year_int):
            print(year_str)
    Now, when python first reads input it names the module '__main__' . And `main' is a common name for the main routine, taken from the c language and maybe from antiquity before then. You'd have a chance to write the main code as a function. You'll often see programs that conditionally execute code if the module is named 'main', and functions named main.
    Last edited by b49P23TIvg; September 15th, 2017 at 08:30 PM.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo