使用月份和日期打印月份 [英] Print month using the month and day

查看:104
本文介绍了使用月份和日期打印月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用月份和日期来打印月份.但是我似乎无法使用Python将"1"之后的数字移至下一行.

I need to print month using the month and day. But I cannot seem to move the numbers after '1' to the next line using Python.

# This program shows example of "November" as month and "Sunday"  as day.

month = input("Enter the month('January', ...,'December'): ")
day = input("Enter the start day ('Monday', ..., 'Sunday'): ")
n = 1

if month == "January" or month == "March" or month == "May" or month == "July" or month == "August" or month == "October" or month == "December":
        x = 31
elif month == "February":
        x = 28
else:
        x = 30

print(month)
print("Mo Tu We Th Fr Sa Su")
if (day == "Sunday"):
        print("                  ", end='')
for i in range (1, 7):
        for j in range (1, 8):
                while n != x+1:
                        print('%2s' % n, end=' ')
                        n = n + 1
                        break
        print()


输出看起来像这样:


Output looks like this:

November
Mo Tu We Th Fr Sa Su
                   1  2  3  4  5  6  7 
 8  9 10 11 12 13 14 
15 16 17 18 19 20 21 
22 23 24 25 26 27 28 
29 30 

推荐答案

某些更改.

与其使用嵌套循环,不如使用一个循环来打印所有日期.然后,在该循环中,决定是否结束行(如果刚打印的日期对应于星期日).

Instead of having a nested loop, just have a single loop that prints all the dates. Then, inside that loop, make the decision about whether to end the line (if the date you just printed corresponded to a Sunday).

此外,每月查询的天数会更干净一些,您现在可以处理的天数"不只是星期日:

Also, the # of days in month look-up is a bit cleaner, and you now handle more "days" than just Sunday:

day = "Monday"
month = "March"


# Get the number of days in the months
if month in ["January", "March", "May", "July", "August", "October", "December"]:
    x = 31
elif month in ["February"]:
    x = 28
else:
    x = 30

# Get the number of "blank spaces" we need to skip for the first week, and when to break
DAY_OFF = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
off = DAY_OFF.index(day)

print(month)
print("Mo Tu We Th Fr Sa Su")
# Print empty "cells" when the first day starts after Monday
for i in range(off):
    print("  ", end=' ')
# Print days of the month
for i in range(x):
    print("%2d" % (i+1), end=' ')
    # If we just printed the last day of the week, print a newline
    if (i + off) % 7 == 6: print()

3月/星期一


March
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7 
 8  9 10 11 12 13 14 
15 16 17 18 19 20 21 
22 23 24 25 26 27 28 
29 30 31 

3月/周日


March
Mo Tu We Th Fr Sa Su
                   1 
 2  3  4  5  6  7  8 
 9 10 11 12 13 14 15 
16 17 18 19 20 21 22 
23 24 25 26 27 28 29 
30 31 

2月/周日


February
Mo Tu We Th Fr Sa Su
                   1 
 2  3  4  5  6  7  8 
 9 10 11 12 13 14 15 
16 17 18 19 20 21 22 
23 24 25 26 27 28 

这篇关于使用月份和日期打印月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆