注意:
1,Python 中的变量赋值不需要类型声明。(java必须先声明变量,才可以使用)
2,变量在使用之前必须赋值(使用=来赋值)
python 常用的数据类型
#整数
x = 5
y = 6
z = x + y
print(z)
#字符串
str = "hello world!"
print(str)
#转义字符
print("hello \world")
print("c:\\python")
#布尔值
t = True
f = False
print(t and f)
print(t or f)
输出结果为:
11
hello world!
hello \world
c:\python
False
True
数组以及增删改
数组定义: 数组(list)是一种有序的集合,可以随时添加和删除其中的元素
student=["jack", "Bob","lucy","Micle"]
print(student)
访问数组元素
用索引来访问list中每一个位置的元素,记得索引是从0开始的:
student=["jack", "Bob","lucy","Micle"]
print(student[0]) jack 第一个
print(student[-1])Micle 最后一个
数组元素的添加修改与删除( 数组注意不要越界哦!!!)
添加元素
#末尾追加元素
student.append("haha")
print(student)
#指定位置添加元素
student.inset(0,"haha")
print(student)
修改元素
student[0]='no.1'
print(student)
删除元素
在末尾删除元素
student.pop()
print(student)
在指定位置删除元素
student.pop(1) 删除第二个元素
print(student)
数组打印结果为:
['jack', 'Bob', 'lucy', 'Micle']
jack
Micle
['jack', 'Bob', 'lucy', 'Micle', 'haha']
['haha', 'jack', 'Bob', 'lucy', 'Micle', 'haha']
['no.1', 'jack', 'Bob', 'lucy', 'Micle', 'haha']
['no.1', 'jack', 'Bob', 'lucy', 'Micle']
['no.1', 'Bob', 'lucy', 'Micle']
元组(Tuple)
python 的元组与列表类似,不同之处在于元组一旦定义就不能修改,元组使用小括号,列表使用方括号,元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
定义:
course = ('chinese', 'math', 'English', 'computer')
print(course)
第一个
print(course[0])
最后一个
print(course[-1])
不包括3
print(course[1:3])
1之后的显示
print(course[1:])
1之前的显示
print(course[:1])
要定义一个只有1个元素的元组,则需要在元素后面加逗号,用来消除数学歧义
t = (1,)
返回元组的最大的值
cource=(1,21,35,48,59)
最大数
print(max(cource))
打印元组个数
print(len(cource))
元组输出结果为:
('chinese', 'math', 'English', 'computer')
chinese
computer
('math', 'English')
('math', 'English', 'computer')
('chinese',)
59
5
字典
字典是一种可变容器模型,且可存储任意类型对象,字段的每个键值对用冒号分割,每个对之间用逗号分割。整个字典包括在花括号{}中,格式如下所示
d = {key1:value1,key2: value2}
键必须是唯一的,但值则不必,值可以取任何数据类型,但键值必须是不可变的
定义字典
student = {1:'jack', 2 : 'bob', 3 : 'lucy'}
print(student[3])
字典添加
student[4] = ‘jaj’
print(student)
字典更改
student[2] = 'harry'
print(student)
字典删除
del student[3]
print(student)
清空字段内容
student.clear()
print(student)
del student删除字典打印print(student)则报错
以上字典输出结果为:
lucy
{1: 'jack', 2: 'bob', 3: 'lucy', 4: 'jaj'}
{1: 'jack', 2: 'harry', 3: 'lucy', 4: 'jaj'}
{1: 'jack', 2: 'harry', 4: 'jaj'}
{}