Python基础语法学习笔记

以下为我整理的Python基础语法学习笔记,大约就是记一下自己感兴趣的和Python与我之前用过语言写法上的区别,比较主观。

代码全部为伪代码(因为文档编辑器的缩进可能不符合Python规范,所以直接用可能不行)。

1.python2python3有重大区别,建议使用python3.

2.python推荐的命名规范是全小写字母,单词和单词间加下划线,例如hello_world.py

3.变量名只能包含字母数字下划线。

4.字符串可以用单引号也可以用双引号,合并字符串用加号,删除空格用strip(),还有lstrip()rstrip()

5.**表示乘方,0.2+0.1=0.300000000000000004

6.注释用#

7.import this会输出python之禅

8.方括号[]表示列表(数组?),最后一个元素可以用bicycle[-1]得到,-2-3也都可以。

9.pop可以弹出列表中任何元素,只要加个索引。

10.sort()排序,sorted()临时排序,len()列表长度,remove()根据值删除元素。

11.for循环例子

>>> for motorcycle in motorcycles:

... print (motorcycle)

...

必须有缩进才能被识别为是for循环里面得句子。

12.随便缩进也不行。。。漏了冒号也不行。。。

13.range(1,5)的结果为

1

2

3

4

14.列表解析代码

>>> squares = [value**2 for value in range(1,11)]

>>> print(squares)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

15.列表复制要用切片形式:

list = [1,2,3]

another_list = list[:]#这样是把list复制一份存到another_list里面

another_list = list #这样是将another_list关联到list上。

16.用圆括号定义的列表其中元素不可修改,成为元组。

17.True,False必须大写才能被识别为关键字。

18.if …:

do sth

elif …:

do sth

else:

do sth

19.{}表示字典(键值对?)。索引就用键值对中的键加入[]中。

20.set()表示集合,集合类似列表但其中元素不重复。

21.函数:

def greet_user():

”””显示简单问候语”””

print('hello')

22.给函数传参时候可以指定关键字,不用按位置传,例如:

def describe_pet(animal_type, pet_name):

describe_pet(pet_name = 'harry', animal_type = 'dog')

23.默认值写在定义函数的时候.

def describe_pet(animal_type, pet_name = 'dog'):

24.函数还可以接收任意数量的实参(常年c#的人表示真的666啊),写法为:

def make_pizza(*toppings):#toppings为空的元组

def make_pizza(**toppings):#toppings为空的字典

25.import可以导入特定函数,方法为:

from module_name import function_0, function_1, function_2

from module_name import * #导入这模块里面的所有函数,极其不推荐。。。

导入也可以导入类

还可以给导入的函数取个别名,例如:

from module_name import function_0 as f_0

模块也行。。。:

import module_name as mn

26.形参赋默认值和关键字方式传值时候,等号两边不带空格(我也不知道为啥。。。)

27.首字母大写的名称为类

class Dog():

初始化函数前后都要加下划线

def _init_(self,name,age)#self在调用的时候不用赋值

初始化写法

my_dog = Dog('white','6')

28.继承方式

class Car()

def _init_(self,make,model,year)

class ElectricCar(Car)

def _init_(self,make,model,year)

super()._init_(make,model,year)

29.类名建议驼峰命名法,跟上注释。

30.异常处理:

try:

except xxx:

pass #什么也不做的时候这么写

else:

31.unittest.TestCase类包含方法setUp(),让我们只需要创建要测试的对象一次,并在每个测试方法中调用它们。如果你在TestCase中包含方法setUp()Python将先运行setUp(),再运行各个test_开头的方法。

猜你喜欢

转载自www.cnblogs.com/resourceful-orange/p/9121722.html