1. Basic knowledge
# 元组只有查询操作 不能修改 支持下标与切片
# 定义空元组
a=()
a=tuple()
# 定义一个数据的空元组 数据元素后边必须有 逗号
b=(1,)
# 多个数据
my=('a','b','c','d')
Two, training
Topic 1 [Strengthen training]
Question stem
There are two lines of code as follows: tuple1 = (2) tuple2 = (2,) What is the difference between tuple1 and tuple2
training target
define a tuple of elements
training tips
What can be seen by the naked eye is only a comma difference, so how does he understand it in python?
Reference plan
Use the type() method to distinguish these two variables separately
Steps
Use type(tuple1), compare with the result of type(tuple12)
reference answer
tuple1 = (2)
tuple2 = (2,)
print(type(tuple1))
print(type(tuple2))
# 对于tuple1 = (2),python解释器会将小括号理解成一个运算符号,那么这时候 返回的值是一个int类型
# 所以对于只有一个元素的元组来说,要创建一个元组,那么就必须要加逗号
Topic 2 [Strengthen training]
Question stem
Have the following code, please answer the question?
my_tuple = ("itcast", "python", "CPP", 18, 3.14, True)
- Use the subscript method to output the elements in the tuple
"CPP"
- Use a for loop to iterate through the tuples
- Use while loop to iterate over tuples
training target
- Subscripting operations on tuples
- For loop traversal of tuples
- While loop traversal of tuples
training tips
- Do subscripts in python start from 0 or 1?
- How to do for traversal?
- How to do while traversal? How to write the condition of while?
Reference plan
- The subscript starts from 0, so the subscript of CPP is 2
- use
for ... in ...
traversal - The while loop needs to use subscripts, and the judgment conditions can be
len()
realized by means of
Steps
- Use the subscript method to get the value of CPP
- for loop through
- while loop traverses
reference answer
my_tuple = ("itcast", "python", "CPP", 18, 3.14, True)
# 1. 使用下标的方法,输出元组中的元素 \`"CPP"\`使用下标的方法,
result = my_tuple[2]
print(result)
# 2. 使用 for 循环遍历元组
for i in my_tuple:
print(i)
print("-" * 20)
# 3. 使用 while 循环遍历元组
i = 0
while i < len(my_tuple):
print(my_tuple[i])
i += 1