我需要使用月份和日期打印月份。但我似乎无法使用Python将'1'后面的数字移动到下一行。
# 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()
输出如下:
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
答案 0 :(得分:1)
一些变化。
没有嵌套循环,只需要一个打印所有日期的循环。然后,在该循环内,决定是否结束该行(如果您刚刚打印的日期对应于星期日)。
此外,每月查找的天数更清晰一些,您现在处理更多"天"而不仅仅是星期天:
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()
三月/星期一
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
三月/周日
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
答案 1 :(得分:0)
我在你的代码中看到的第一个问题是:为什么你在启动它之后使用了一段时间和一个休息时间? 您似乎只需要 if 语句,而不是而。
其次,您对日历的任何一行都使用相同的逻辑,这意味着:它们从星期一开始,到星期日结束。
您应该为第一行更改内部 for 循环的起点,具体取决于它开始的日期。
一个简单的字典可以保存与一周中每一天相关联的数字,并且在第一周您将其用作for的起点,而不是 1 。
您的代码仅适用于本月的第一天的周一和周日。 要使它适用于任何第一天,您应该更改打印空间的方式,根据第一天更改它。
包含更改的代码:
月=' 11月' day =' Sunday' x = 30 n = 1
days = { 'Mo': 1, 'Tu': 2, 'We': 3, 'Th': 4, 'Fr': 5, 'Sa': 6, 'Su': 7 }
print(" "*(days[day[:2]]-1), end='') # print 3 spaces for each day that isn't the first day of the month
start = days[day[:2]] # Set the start of the inner loop to the first day of the month
for i in range (1, 7):
for j in range (start, 8):
start = 1
if n < x+1:
print('%2s' % n, end=' ')
n = n + 1
print()