python3中变量的定义是不固定类型的(动态),区分大小写
值类型 | 引用类型 |
---|---|
不可变的(值类型) | 可变的(引用类型) |
int (整型) | list (列表) |
str (字符串) | set (集合) |
tuple (元组) | dict (字典) |
id()
,能够知道变量在内存的位置b = "icessun" b = b + "hello" print(b) >>> "icessunhello" # 不是说字符串是不可变的嘛?怎么改变了
若是字符串能够改变,那么可使用索引值给字符串赋值"python"[0] = 'h' -----> 报错
,会发现报错,是不行的。python
上面程序的结果是由于,+
链接符,把两个字符串链接起来了,连接起来的值从新赋值给了b元素,使用id(b)
函数,会发现其实上面两个b变量在内存的位置是不同的,因此第一个b变量的值没有改变,被覆盖了。app
2**5 ----> 2的5次方=32
is / not is
函数
a = (1,2,3) b = (1,3,2) print(a is b) # 元组是不可变的 print(a == b) # 元组是有序的,值是不相等的 >>> False False # 集合 a = {1,2,3} b = {1,3,2} print(a==b) # 集合是无序的,因此值是相等的 print(a is b) >>> True False # 字符串,数字 两个取值相等,则is 返回True,可是数字有特殊 a = 'icessun' b = 'icessun' print(a is b) >>> True a = 1 b = 1 c = 1.0 print(a==b) print(a==c print(a is b) print(a is c) >>> True True True False
从上面能够看出,元组是不可变的,改变里面元素的位置就变成了两个新的元组。is
不是比较两个变量的值是否相等,而是比较变量在内存的地址是否相等,算术运算符==
是比较值是否相等的ui
对象的三个特性 | 一切都是对象 |
---|---|
id()函数:变量在内存的地址 | is :身份运算符 |
type()函数:类型判断函数 | isinstance(变量,(int,str,float....)) |
value值的比较 | == :算术比较符 |
判断一个变量是否在一个变量里面
in / not in
b= 'a' b in {'c':1} >>> False b=1 b in {'c':1} >>> False b='c' b in {'c':1} >>> True
{ }
pass
:占位语句#
;推荐在这行语句的开头写,与上一条语句有空格 '''注释内容'''
new
关键词if else / elseif
a = input() a = int(a) print('a is ' + str(a)) if a==1: print('apple') elif a==2: print('orange') elif a==3: print('banana') else: print('shoppingp') # 使用 if else if a==1: print('apple') else: if a==2: print('orange') else: if a==3: print('banana') else: print('shopping')
input()
接收用户的输入,elif
功能相似于switch
功能;int(a)
:由于终端输入的是字符串,因此应该强制转为数字进行比较print('a is ' + str(a))
:字符串的拼接只能二者都是字符串,否者会报错code
for 变量 in 循环体
主要用来遍历循环:序列List,集合Set,字典Dict
a = [['apple','orange','banana','grape'],(1,2,3)] for x in a: for y in x: if y=='orange': break # continue print(y) # 默认是换行(print(y,end='/n'))输出的,要想不换行:print(y,end=' ');故能够在end里面添加其余的符号来链接字符 else: print('fruit is gone') >>> apple 1 2 3 fruit is gone
break
跳出里面的for循环,可是外面的for循环没有跳出,仍是会执行;和else配对的是外面的for循环,因此依然会执行;要是在外层的for循环里面加入break,那么就不会执行else语句;for循环后面有else语句,当循环执行完毕,也会依然接着执行else语句,因此会输出fruit is gone;通常不推荐在for循环后面使用else语句对象
range()
函数for x in range(0,10): print(x,end='|') >>> 0|1|2|3|4|5|6|7|8|9| for x in range(10,0,-2): print(x,end='|') >>> 10|8|6|4|2| # 打印列表a中全部的基奇数项 a=[1,2,3,4,5,6,7,8] # 循环+range()函数的方法 for x in range(0,len(a),2): print(a[x]) # 列表的切片的方法 print(a[0:len(a):2]) >>> [1,3,7]
range()
函数的做用相似于其余语言中的for(i = 初始值;i < 长度;i ++)
;里面能够传入两个或者三个参数,两个参数的时候表示的是:初始值,长度;传入三个参数的时候表示的是:初始值,长度,步长索引
def ice(a,b): a1=a*3 b1=b*2+10 return a1,b1 ice_a1,ice_b1 = ice(3,6) print(ice_a1,ice_b1) >>> 9 22 a=1 b=2 ====> a,b,c=1,2,3 或者 (1,2,3) 当abc都相等的时候:a=b=c=1 或者 a,b,c=1,1,1 c=3
序列解包:就是当一个函数有多个返回值的时候,不须要使用一个变量接收到全部的返回值,而后又从新遍历返回值,取到对应的返回值;只须要使用和返回值个数对等的变量依次接收就行;固然只是针对返回值是值类型的函数。个数相等,顺序对应内存
当在函数参数里面使用的时候,能够在实参里面修改默认值;在调用函数传入参数的时候,明确告诉实参,形参给传的是那个实参的值sum(y=3,x=2)
字符串