python入门之元组(tuple)

"""
元组 tuple
1.由一系列变量组成的不可变系列容器
2.不可变是指一但创建,不可以再添加/删除/修改元素
3.列表用[],元组用()
4.列表和元组之间能互相转换
5.元组切片还是元组,列表切片还是列表,字符串切片还是字符串

"""
复制代码
# 1.创建元组
#
tuple01 = ()

# 列表  --> 元组
tuple01 = tuple(["a", "b"])
print(tuple01)

# 元组 --> 列表
list01 = list(tuple01)
print(list01)

# 如果元组只有一个元素要加逗号
# tuple02 = (100)
# print(type(tuple02)) # int
tuple02 = (100,)
print(type(tuple02))  # tuple

# 具有默认值
tuple01 = (1, 2, 3)
print(tuple01)
# 不能变化

# 2.获取元素(索引  切片)
tuple03 = ("a", "b", "c", "d")
e01 = tuple03[1]
print(type(e01))  # str

e02 = tuple03[-2:]
print(type(e02))  # tuple

tuple04 = (100, 200)
# 可以直接将元组赋值给多个变量
a, b = tuple04
print(a)  # 100
print(b)  # 200

# 3.遍历元素
# 正向
for item in tuple04:
    print(item)
# 反向
# 1 0
for i in range(len(tuple04) - 1, -1, -1):
    print(tuple04[i])
复制代码

 

练习:

复制代码
"""
    练习1:
        借助元组完成下列功能
"""
# month = int(input("请输入月份:"))
# if month < 1 or month > 12:
#     print("输入有误....")
# elif month == 2:
#     print("当前月份是28天")
# elif month == 4 or month == 6 or month == 9\
#         or month == 11:
#     print("当前月份是30天")
# else:
#     print("当前月份是31天")

# 方式1:
month = int(input("请输入月份:"))
if month < 1 or month > 12:
    print("输入有误....")
elif month == 2:
    print("当前月份是28天")
elif month in (4, 6, 9, 11):
    print("当前月份是30天")
else:
    print("当前月份是31天")

# 方法2:
month = int(input("请输入月份:"))
if month < 1 or month > 12:
    print("输入有误....")
else:
    # 将每月天数存入元组
    day_of_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    # 5月
    print(day_of_month[month - 1])
复制代码

 

复制代码
# 练习2:
#     在控制台中录入日期(年月),计算这是这一年的第几天
#     例如:3月5日
#          1月天数+ 2月天数 + 5

# 方法1:
day_of_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
month = int(input("请输入月份:"))
day = int(input("请输入日:"))
# 累加前几个月的天数
total_day = 0
# 思路1:
# month = 3
# # 0  1
# for item in range(2):
for i in range(month - 1):
    total_day += day_of_month[i]
# 与思路1对比:
# day_of_month[1]
# month = 5
# # 0 1 2 3
# for item in range(4):

# 累加当月天数
total_day += day
print("是这年的第%d天....." % total_day)

# 方法2:使用切片的方法去实现
day_of_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
month = int(input("请输入月份:"))
day = int(input("请输入日:"))
total_day = 0
total_day = sum(day_of_month[:month - 1])
total_day += day
print("是这年的第%d天....." % total_day)
复制代码

 

posted @   黎小菜  阅读(116)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示