Python practice - print calendar tutorial

I haven't been exposed to C language for a long time. I want to do this business for three or two years.

Today, I suddenly think of the days when I used to write code on VC6 in C language, and I think of some practical exercises in the past.

So today I plan to use Python to write a topic that I practiced before in C language - Calendar printer, and optimize it according to the situation.

The effect is shown in the figure above

Algorithm idea:

First of all, the operation of the calendar is inseparable from a fundamental situation. January 1, 1990 is Monday, so the printing of the calendar needs to be based on this fact

The main problem to be solved in printing calendar is: what day is the first day of this month?

Before there is a better algorithm, the best way is to accumulate according to the received month and year, and then divide by seven to get the rest

As you can see, the core part of the algorithm is to mark "accumulate" and "divide by seven to get the rest" (seven days a week).

Take February 1991 (365 days in 1990 + 31 January 1991)% 7 = 4

So February 1 is Friday. If you can understand this, calendar printing will be easy to understand

Development ideas:

First receive the required data, i.e. year month

Days accumulation:

Taking October 1992 as an example, the days of 1990, 1991 and the first nine months of 1992 need to be recorded

Create a variable (sum) to count the accumulated days

The cycle was established from 1990 to the year before we input (year-1), the leap year (sum+=365) (sum+=366)

After the year is completed, the month is counted, and the cycle is established from January. If the big month (sum+=31) and the small month (sum+=30) are in February, there will be one more judgment (normal year 28, leap year 29)

Print calendar

After the days of statistics are divided into seven, we can get the day of the week of the first day. Then, according to the output of the month information, the line breaks every seven days from the beginning to the end of the month.

 

Obviously, for such an analysis, we need to create two functions, a calculation () to calculate the accumulated days and a display () to print the results

On this basis, I added a function islepyear () to judge whether it is a normal year or a leap year, which is also an optimization.

Development tutorial and code:

1.isleapyear()

The purpose of creating this function is to determine whether it is a leap year or not, and input the judgment function

First of all, as a judgment function, the most basic is to pass in the judged data. Isleayear() needs to pass in an int type annual data

Secondly, it is clear that leap years can be divided by 4 but not 100 or 400

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

Finally, the return result of the function is judged to be True or False, so I create a flag in the function, which defaults to False, and changes to True when it is judged to be True

def IsleapYear(year):
    flag =False
    if(year%4==0 and year%100!=0) or year%400==0:
        flag = True
    return flag

 

Some people think it's unnecessary, but it's necessary to judge the leap year of the normal year, the cumulative year, the cumulative month, and the printing,

It will be tedious and tedious to write judgment every time, so it's convenient to create a function to judge leap year

2.calculation()

This function is used to calculate the cumulative situation of the month and year, so you need to pass in the two information of the month and year

First of all, create a cycle of years, which starts in 1990 and ends in the year before the input year. In this cycle, add 365 leap years and 366 leap years

At this time, the islepyear() created earlier can be used. The code is as follows, taking s Φ year as the cycle year and the function as the judgment function:

if isleapyear(s_year): 

 

In the same way, we can get the month, the relevant cycle.

It should be noted here that the original branches of the month are three points, and the big month + = 31, the small month + = 30, and the February are nested with a judgment

You have solved the nesting judgment of February, so how to solve the problem of big month and small month?

There are two branch structures in c language: if and switch

Common judgment methods (if)

if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)

 

Or a little easier (switch)

 

 

In python, it can be simplified by combining sets of data types

It's much easier to create a lunar which can carry the information of the big moon and realize the judgment of the month through the "in" operation

Lunar=(1,3,5,7,8,10,12)
if s_month in Lunar:
            sum += 31
        elif s_month==2:
            if IsleapYear(year):
                sum+=29
            else:
                sum+=28
        else:
            sum+=30

 

Finally, send the calculation () code as follows

def calculation(year,month):
    sum = 0
    s_year=1990
    while s_year < year-1:
        s_year +=1
        if IsleapYear(s_year):
            sum+=366
        else:
            sum+=365

    s_month=1
    while s_month<month:
        if s_month in Lunar:
            sum += 31
        elif s_month==2:
            if IsleapYear(year):
                sum+=29
            else:
                sum+=28
        else:
            sum+=30
        s_month+=1

    return sum

 

3.display()

Step 1: judge the day of the week as the next number 1, and add one to the remaining seven days in the first day of the accumulated day to get the day of the week

Step 2: print the header, starting from the far left, "day one, two, three, four, five, six". In order to make it beautiful, you need to add a tab in the middle of each column (\ t)

Step 3: the output starts from the far left. For example, the first day starts on Friday. You need to print four tabs (\ t) until you reach the position on Friday

Step 4: judge how many days should be printed according to the month information. You need to set a count variable, and output a new line after seven

def display(sum,year,month):
    #First step
    week=(sum+1)%7
    #The second step
    print("day\t One\t Two\t Three\t Four\t Five\t Six")
    #The third step
    count = 0
    space = 0
    while space<=week:
        space+=1
        count+=1
        print("\t",end="")
        if count%7==0:
            print("\n",end="")
    #The fourth step
    if month in Lunar:
        day=31
    elif month==2:
        if IsleapYear(year):
            day=29
        else:
            day=28
    else:
        day=30
    days=1
    while days<=day:
        print(days,"\t",end="")
        days+=1
        count+=1
        if count %7 ==0:
            print("\n")    

 

In the third step, some people doubt that week itself is the result of accumulating days. Why add an if count%7==0: print("\n",end = "")?

In fact, there is a detail here, because the while loop is used, which is executed first and then judged. If week=6, the space+=1 operation is executed first, and then space=7,

If there is no such judgment, the line break will not appear, but will be printed from the position after six (wrong line), as shown in the figure below

 

 

 4.main()

The code is basically finished here, but I'm afraid I forgot a little

We haven't set how to input the date information, and the code is all written in the function. Someone needs to call it. The last function main() is created here

The main function needs to be set to accept the month and year information, and at the same time, pass parameters to call the just function

At the same time, some input restrictions are added, for example, the year must be larger than 1990, so a range [19909999] is also limited

There are only 12 months in a year, so month must be within the range of [0,12]

The program is not only executed once. You can add a decision. After printing the calendar, ask if you want to continue, etc

So the code is as follows:

def main():
    year =int( input("year="))
    if year<1990 or year>9999:
        print("year Input error")
        main()
    month = int(input("month="))
    if month<1 or month > 12:
        print("month Input error")
        main()
    sums=calculation(year,month)
    display(sums,year,month)

if __name__=="__main__":
    while True:
        main()
        choose=input("\n Continue:")
        if choose in("n","N"):
            break

 

In this way, we make a python version of the calendar with a code of about 70 lines

If there are other new ideas that can be improved, such as making the calendar look more beautiful, etc

As always, put all the codes at the end. I hope you can support it. If you want to see or learn, you can also leave a message

Lunar=(1,3,5,7,8,10,12)

def IsleapYear(year):
    flag =False
    if(year%4==0 and year%100!=0) or year%400==0:
        flag = True
    return flag

def calculation(year,month):
    sum = 0
    s_year=1990
    while s_year < year-1:
        s_year +=1
        if IsleapYear(s_year):
            sum+=366
        else:
            sum+=365

    s_month=1
    while s_month<month:
        if s_month in Lunar:
            sum += 31
        elif s_month==2:
            if IsleapYear(year):
                sum+=29
            else:
                sum+=28
        else:
            sum+=30
        s_month+=1

    return sum

def display(sum,year,month):
    week=(sum+1)%7
    if month in Lunar:
        day=31
    elif month==2:
        if IsleapYear(year):
            day=29
        else:
            day=28
    else:
        day=30

    print("day\t One\t Two\t Three\t Four\t Five\t Six")
    count = 0
    space = 0
    while space<=week:
        space+=1
        count+=1
        print("\t",end="")
        if count%7==0:
            print("\n",end="")
    days=1
    while days<=day:
        print(days,"\t",end="")
        days+=1
        count+=1
        if count %7 ==0:
            print("\n")
def main():
    year =int( input("year="))
    if year<1990 or year>9999:
        print("year Input error")
        main()
    month = int(input("month="))
    if month<1 or month > 12:
        print("month Input error")
        main()
    sums=calculation(year,month)
    display(sums,year,month)

if __name__=="__main__":
    while True:
        main()
        choose=input("\n Continue:")
        if choose in("n","N"):
            break

Tags: Python C REST

Posted on Fri, 08 Nov 2019 07:43:07 -0500 by mrdamien