问:
【基础题】输入某年某月某日,判断这一天是这一年的第几天?
【提高题】用 *号输出字母 C的图案
答:
【基础题】输入某年某月某日,判断这一天是这一年的第几天?
方法1:
import time test_time = input("请输入日期(年-月-日):") time_struct = time.strptime(test_time, "%Y-%m-%d") time_year = time_struct.tm_year time_yday = time_struct.tm_yday print("{}是{}年这一年中的第{}天".format(test_time, time_year, time_yday))
方法2:
import datetime date_time = input("请输入日期(年-月-日):") datetime_struct = datetime.datetime.strptime(date_time, "%Y-%m-%d") time_year = datetime_struct.timetuple().tm_year time_yday = datetime_struct.timetuple().tm_yday print("{}是{}年这一年中的第{}天".format(date_time, time_year, time_yday))
方法3:
def get_daynum(): year = input("请输入年份:") month = input("请输入月份:") day = input("请输入天:") date1 = datetime.date(year=int(year), month=int(month), day=int(day)) date2 = datetime.date(year=int(year), month=1, day=1) return ((date1 - date2).days + 1) if __name__ == '__main__': print(get_daynum())
【提高题】用 *号输出字母 C的图案
方法1:
print(" ***** ") print(" ** * ") print(" ** ") print(" ** ") print(" ** * ") print(" ***** ")
方法2:
ch = [[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 1], [0, 1, 1, 0]] for i in range(len(ch)): for j in ch[i]: if j == 0: print(" ",end="") else: print("*", end=" ") print()
输出结果:
方法3:
from PIL import Image,ImageDraw,ImageFont import numpy as np text = "C" myfont = ImageFont.truetype("msyh.ttc", 12) # 在代码所在目录下需要放置字体文件,此处为msyh.tcc size = myfont.getsize(text) img = Image.new("1", size, "black") draw = ImageDraw.Draw(img) draw.text((0,0), text, "white", font=myfont) pixels = np.array(img, dtype=np.uint8) chars = np.array([' ', '*'], dtype="U1")[pixels] strings = chars.view('U' + str(chars.shape[1])).flatten() print(" ".join(strings))
输出结果: