开始之前先讲一下python的命令行如何清屏,在idle环境下无效。打开cmd窗口,输入python回车,键入 import os i=os.system('cls')就能实现清屏函数。
①if 语句,if … elif … elif … 序列用于替代其它语言中的 switch
或 case
语句。
>>> x = int(input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... x = 0 ... print('Negative changed to zero') ... elif x == 0: ... print('Zero') ... elif x == 1: ... print('Single') ... else: ... print('More')
②for 语句,Python 的 for 语句依据任意序列(链表或字符串)中的子项,按它们在序列中的顺序来进行迭代。在迭代过程中修改迭代序列是不安全的。例如:
Python和C for循环中最大的不同在于他会自己进行循环,当没有条件控制语句的时候他可以自己执行完一个周期,目标在表达式中,按照表达式的从头至尾执行循环。
for的语法格式: for 目标 in 表达式:
循环体
>>> words=['cat','windows','defenestrate']
>>> for w in words:
print(w,len(w))
>>> for w in words:
print(w,len(w))
>>> a="通哥好帅哦,他是世界上最帅的男人!"
>>> for i in a:
... print(i,end='_')
...
通_哥_好_帅_哦_,_他_是_世_界_上_最_帅_的_男_人_!_>>>
cat 3
windows 7
defenestrate 12
>>> for w in words[:]: # Loop over a slice copy of the entire list. ... if len(w) > 6: ... words.insert(0, w) # insert函数 插入作用 ... >>> words ['defenestrate', 'cat', 'window', 'defenestrate']
③ range() 函数,如果你需要一个数值序列,内置函数 range() 会很方便,它生成一个等差级数链表,所生成的链表中不包括范围中的结束值:
for i in range(5): #range 函数只能生成 整数函数 ... print(i)
0 1 2 3 4
range(5, 10) #可以选择生成数的范围 5 through 9 range(0, 10, 3) #可以选择生成数的 步距 0, 3, 6, 9 range(-10, -100, -30) #可以选择... -10, -40, -70
a作为一个循环的数据基础,i是循环变量,这样写可以循环执行print的同时,首先生成一个序列,再打印值
>>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print(i, a[i]) ... 0 Mary 1 had 2 a 3 little 4 lamb
list函数,它从可迭代(对象)中创建列表:
>>> list(range(5)) [0, 1, 2, 3, 4]
④break和continue函数,continue 语句是从 C 中借鉴来的,它表示循环继续执行下一次迭代:
>>> for num in range(2,10):... if num%2 ==0:
... print("Found an even number",num)
... continue
... print("Found a number",num)
...
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
break 语句和 C 中的类似,用于跳出最近的一级 for 或 while 循环。
>>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, 'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3
⑤pass语句,什么也不做,它用于那些语法上必须要有什么语句,但程序什么也不做的场合。
>>> def initlog(*args): ... pass # Remember to implement this!
⑥定义函数,三引号引起来的内容叫_函数文档
>>> def fib(n): # write Fibonacci series up to n ... """Print a Fibonacci series up to n.""" ... a, b = 0, 1 ... while a < n: ... print(a, end=' ') ... a, b = b, a+b ... print() #用来转移最后一行的光标到新的一行 ... >>> # Now call the function we just defined: ... fib(2000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
>>> def fib2(n): # return Fibonacci series up to n ... """Return a list containing the Fibonacci series up to n.""" ... result = [] ... a, b = 0, 1 ... while a < n: ... result.append(a) # see below ... a, b = b, a+b ... return result ... >>> f100 = fib2(100) # call it >>> f100 # write the result [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
语句result.append(b)成为链表对象result的一个方法。方法是“属于”一个对象的函数,
它被命名为obj.methodname,这里的obj是某个对象(可能是一个表达式),methodname是
某个在该对象类型定义中的方法的命名。
python提供了多种函数定义形式:
(1)def ask_ok(prompt, retries=4, complaint=
'Yes or no, please!'):
(2)ask_ok('Do you really want to quit?')
(3)ask_ok('OK to overwrite the file?', 2)
(4)ask_ok('OK to overwrite the file?', 2,
'Come on, only yes or no!')
可变参数列表,通常,这些可变参数是参数列表中的最后一个,因为它们将把所有的剩余输入参数
传递给函数。
⑦ Lambda 形式,Lambda 形式可以用于任何需要的函数对象。出于语法限制,
它们只能有一个单独的表达式。语义上讲,它们只是普通函数定义中的一个语法
技巧。类似于嵌套函数定义,lambda 形式可以从外部作用域引用变量:
>>> def lamb_test(n):... return lambda x:x+n...>>> f=lamb_test(39)>>> f(1)40
>>> mm = lambda x: x ** 3
>>> mm(3)
使用print函数打印函数文档的用法:print(mytest.__doc__)其中doc左右两边的 _ 字符 有两个。
⑧函数注解,注解是以字典形式存储在函数的 __annotations__
属性中,对函数的其它部分没有任何影响。参数注解(Parameter annotations)是定义在参数名称的冒号后面,紧随着一个用来表示注解的值得表达式。返回注释(Return annotations)是定义在一个 ->
后面,紧随着一个表达式,在冒号与 ->
之间。下面的示例包含一个位置参数,一个关键字参数,和没有意义的返回值注释: (没看懂...)
>>> def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here": ... print("Annotations:", f.__annotations__) ... print("Arguments:", ham, eggs) ... >>> f('wonderful') Annotations: {'eggs': <class 'int'>, 'return': 'Nothing to see here', 'ham': 42} Arguments: wonderful spam
⑨编码风格:
使用 4 空格缩进,而非 TAB在小缩进(可以嵌套更深)和大缩进(更易读)之间,4空格是一个很好的折中。TAB 引发了一些混乱,最好弃用
折行以确保其不会超过 79 个字符,这有助于小显示器用户阅读,也可以让大显示器能并排显示几个代码文件
使用空行分隔函数和类,以及函数中的大块代码
可能的话,注释独占一行
使用文档字符串
把空格放到操作符两边,以及逗号后面,但是括号里侧不加空格:
a = f(1, 2) + g(3, 4)
统一函数和类命名
推荐类名用
驼峰命名
, 函数和方法名用小写_和_下划线
。总是用self
作为方法的第一个参数(关于类和方法的知识详见 初识类 )不要使用花哨的编码,如果你的代码的目的是要在国际化环境。Python 的默认情况下,UTF-8,甚至普通的 ASCII 总是工作的最好
同样,也不要使用非 ASCII 字符的标识符,除非是不同语种的会阅读或者维护代码。