"""
元组 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)
标签:tuple,python,31,30,元组,print,month,day From: https://www.cnblogs.com/Remick/p/17086161.html