0.初识Python
作为一个曾经只会MATLAB的编程小白,无意间接触到了Python,就被它简洁的语法和强大的功能所吸引。写这一系列文章的初衷是想把学习过程中的感悟和思考记录下来,绝非是教程,因为作者也是零基础开始,水平着实有限。算是新学期的第一个flag,也算是为我即将进入数据科学领域热热身,希望能坚持下去,不负韶华不负心!
废话不多说,老规矩:
>>> print('Hello,python!')
Hello,python!
1. Python的数据类型
-
数值类型
- 整型(int):int会将小数向下取整(截断)
>>> int(6.9) 6 #一个巧妙的四舍五入办法 int(x+0.5) >>> int(6.4+0.5) 6 >>> int(6.6+0.5) 7
- 浮点型(float):Python区分整型or浮点型只看数据有没有小数点
>>> a=1 >>> b=1.0 >>> type(a) <class 'int'> >>> type(b) <class 'float'>
e记法为类型为浮点型
>>> a=3e10;type(a); <class 'float'>
- 布尔类型(bool):True(=1)、False(=0)
>>> print(True + 5) 6
字符串(str)
列表(list)
元组(tuple)
字典(dict)
集合(set)
各类型的具体用法会在以后的文章中提到。
注:判断变量的类型可用type()
或isinstance()
函数。
>>> name='Shan Jiawei'
>>> type(name)
<class 'str'>
>>> isinstance(name,bool)
False
2.常用操作符
-
算数操作符
-
四则运算:+ - * /
可用 a += 1 来表示 a = a + 1
求余:%
5 % 2 = 1
求幂: **
地板除: // 向下取整
-
比较操作符: < <= > >= == !=
逻辑操作符:and or not → True \ False
优先级
幂运算 > 正负号 > 算数操作符 > 比较操作符 > 逻辑操作符
逻辑操作符中 not > and > or
短路逻辑(short-circuit logic)
Python在进行逻辑操作符运算时有个有趣的特性:在不需要求值的时候不进行操作。举个例子,表达式 x and y
,需要 x 和 y 两个变量同时为True的时候,结果才为真。因此,如果当 x 变量得知是False的时候,表达式就会立刻返回False,而不用去管 y 变量的值。 这种行为被称为短路逻辑(short-circuit logic)或者惰性求值(lazy evaluation)。同样对于x or y
,只要x为True,则直接返回True,而不去判断y的值。
事实上,Python处理x and y
的方法是:若x为假,则返回x的值;若x为真,则返回y的值。并且对Python而言,任何非零数都是True。例如
>>> not 1 or 0 and 1 or True and 4 or 5 and True or 7 and 8 and 9
4
分析一下应该是
not 1 or 0 and 1 or True and 4 or 5 and True or 7 and 8 and 9
(not 1) or (0 and 1) or (True and 4) or (5 and True) or (7 and 8 and 9)
== 0 or 0 or 4 or True or 9
== 4
3.循环
写在前面
Python的循环中最应该注意的是冒号和缩进,通过缩进的方式强制将代码分块。这样可以有效避免诸如“悬挂else”的问题。
if x == 0:
if y == 0:
print('嘻嘻嘻');
else:
print('哈哈哈')
else
与第一个if
并列
for循环
if循环与while循环与其他语言差不多,所以不在赘述,注意elseif在Python中写作elif
。
for循环的调用格式为for (item) in (iterable)
,其中iterable可以是数组、列表甚至是字符串(好神奇●0●)。常用的构造数组的函数是range([start=0,]stop[,step=1])
。
Python一个很大的一个特点是索引值(index)全部是从0开始,range()函数也同样,默认从0开始,并且不包含‘stop’的值。例如range(3)返回0,1,2,range(1,4)返回1,2,3,range(1,6,2)返回1,3,5,这也说明了step是不必整除stop-start的,这比MATLAB好用多了!
>>> name='单嘉伟'
>>> for i in name:
print(i,end='^o^')
单^o^嘉^o^伟^o^
>>> for i in range(5):
print(i**2 , end=' ')
0 1 4 9 16
三元操作符
if x < y:
small = x
else:
small = y
可以写作
small = x if x < y else y
break与continue
break 语句的作用是终止当前循环,跳出循环体。 (break只能跳出一层循环)
continue 语句的作用是终止本轮循环并开始下一轮循环(在开始下一轮循环之前会先测试循环条件)。
for i in range(10):
if i%2 != 0:
print(i)
continue
i += 2
print(i)
结果为 2 1 4 3 6 5 8 7 10 9
今天就写到这吧,能看到这句话的估计都是真爱了,比心~