Python学习笔记1 循环结构和列表相关的知识(2020.6.17)

Python学习笔记1 循环结构和列表相关的知识

通过例题来学习

输入年月日,并输出该日是该年的第多少天。

注意:要考虑闰年情况。闰年的判断方法:(能被400整除的)或者(能被4整除且不能被100整除的)为闰年

提示:判断某个变量是否为多个值的判断可写为:
if a in (1,2,3):含义为:如果a的值为1 或者2或者3
print("{}年{:0>2d}月".format(year,month))表示将year变量输出到第一个{}位置,month输出第二个{}位置,且以整数形式输出占2位,右对齐,不够2位左补0

程序运行界面:
请输入年:2020
请输入月:6
请输入日:1
2020年06月01日是该年的第153天

利用for循环和列表索引取值来完成此题目

year = int(input("请输入年:"))
month = int(input("请输入月:"))
day = int(input("请输入日:"))
total_days = 0

ryear =  [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
pyear = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
    for i in range(1, month):
        total_days += ryear[i]
else:
    for i in range(1, month):
        total_days += pyear[i]

print("{}年{:0>2d}月{:0>2d}日是该年得第{:0>3d}天".format(year, month, day, total_days+day))

利用列表的方法来进行优化,可以去除for循环结构

year = int(input("请输入年:"))
month = int(input("请输入月:"))
day = int(input("请输入日:"))
total_days = 0

pyear =  [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
    pyear[1] = 29

pyear = pyear[:month-1]
total_days = sum(pyear) + day
print("{}年{:0>2d}月{:0>2d}日是该年得第{:0>3d}天".format(year, month, day, total_days+day))

杨辉三角
在这里插入图片描述

#  杨辉三角  #
n = int(input("请输入杨辉三角的行数n:"))
yang = [[1], [1, 1]] #因为杨辉三角第一行规律性不强直接给出

for i in range(2, n): #因为前两行已经给出,从第二行开始写,到n-1结束
    rows = [1]*(i+1) #假设为第二行,三个元素,先设置为1,在进行修改
    for j in range(1, len(rows)-1): #杨辉三角每一行的首尾元素皆为1
        rows[j] = yang[i-1][j] + yang[i-1][j-1] #改值
    yang.append(rows)
for row in yang:
    for volume in row:
        print(volume, end=" ")
    print(" ")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值