Python编程基础

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/c_air_c/article/details/82623990

Python入门基础知识

1. Python数据基本结构

Python的数据是弱类型,使用一个变量前不必提前声明。

1.1. 字符串

string =  "this is a string!" #单引号可代替双引号
print(string)
this is a string!
string_new = 'this is a ""' 
print(string_new)
this is a ""
print("my name is %s" %"jok")
my name is jok

1.2. 数值

int_num = 9 #整形
float_num = 9.111111 #浮点型

print(int_num,float_num,int(9.9999),int_num == int(float_num))
9 9.111111 9 True

1.3.布尔类型

print(1>2,2>1,True == False,True == 1)
False True False True

1.4. 空值

list_None = [1,2,3,None,4]
i = 0
while list_None[i] != None:
    print(list_None[i])
    i +=1
1
2
3

1.5. 列表

list1 = ["zhangsan","1",2,None,1>2] #创建一个列表,其中的数据类型,可以是任意类型
print(list1)
['zhangsan', '1', 2, None, False]
print(len(list1)) #输出列表长度
type(list1) #输出变量的类型
4
list
list2 = [1,2,list1] #列表内也可以是另外一个列表
print(list2)
[1, 2, ['zhangsan', '1', 2, None, False]]
list1.remove('zhangsan') # 删除'zhangsan' 作用等同于  del list1[0]
print(list1)
['1', 2, None, False]
list1.reverse() # 反向输出
print(list1)
[False, None, 2, '1']
print(list2) #当我们改变list1时,list2也在同时发生改变
[1, 2, ['1', 2, None, False]]
list2[2][0] = 2 #修改元素值
print("list2:{}".format(list2)) #当我们改变list2中的list1的内容时,发现list1并没有被改变
print("list1:{}".format(list1))
list2:[1, 2, [2, 2, None, False]]
list1:[False, None, 2, '1']
a =  [1,2,3,[4,5,6]]
b = a
print("a的地址为{},b的地址为{}".format(id(a),id(b)))
a的地址为78568968,b的地址为78568968

1.6. 元组

tuple_new = (1,2,3,4)
print(tuple_new,type(tuple_new))
(1, 2, 3, 4) <class 'tuple'>
print(tuple_new[0])
tuple_new[0] = 5   #元组tuple类型不支持修改值
print(tuple_new)
1



---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-5-f8420301967a> in <module>()
      1 print(tuple_new[0])
----> 2 tuple_new[0] = 5   #元组tuple类型不支持修改值
      3 print(tuple_new)


TypeError: 'tuple' object does not support item assignment

1.7. 集合

set_new = {1,2,7,4,1}
print(set_new) # 集合会自动的调用去重与排序算法
{1, 2, 4, 7}
set_new.update([10])  #集合元素的添加
set_new.add(0)
print(set_new) 
{0, 1, 2, 4, 7, 10}
set_new = {4,3,2,1}
set_new.pop()
print(set_new) #去掉第一个元素(排序后的元素)
{2, 3, 4}
set_new.discard(3) # 去掉值为3的元素
print(set_new)
{2, 4}
print(2 in set_new) #判断2是否在集合set_new中
True

1.8. 字典

dict_new = {'name':'job','age':'55','state':'diey'}
print(dict_new)
{'name': 'job', 'age': '55', 'state': 'diey'}
print(dict_new['age']) #按照key取值
55
dict_new['age']=66 #修改值
del dict_new['state'] #删除元素
print(dict_new)
{'name': 'job', 'age': 66}
dict_nem = {1:2,(2,2):3,[3]:4} #因为字典的key不可变,所以不能使用list来充当key
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-40-f7209f4288fd> in <module>()
----> 1 dict_nem = {1:2,(2,2):3,[3]:4}


TypeError: unhashable type: 'list'

未完待续--条件、循环

猜你喜欢

转载自blog.csdn.net/c_air_c/article/details/82623990