您的位置:首页 > 编程语言 > Python开发

Python基础教程笔记——条件,循环和其他语句

2016-01-27 16:14 543 查看
1 print和import的更多信息

1.1 使用逗号输出
说明:使用print时,也可以在语句中添加多个表达式,每个表达式用逗 号分隔
注意:在用逗号分隔输出时,print语句会在每个输出项后面自动添加一 个空格
例子:
1: >>> greeting = 'Hello'

2: >>> salution = 'Mr.'

3: >>> name = 'Bill'

4: #以逗号分隔输出项

5: >>> print(greeting, salution, name)

6: Hello Mr. Bill

7: #在逗号前增加了一个空格符

8: >>> print(greeting, ',', salution, name)

9: Hello , Mr. Bill

10: #为了显示成'Hello, Mr. Bill'这个样式,可以使用连接符‘+’

11: >>> print(greeting + ',', salution, name)

12: Hello, Mr. Bill

13: >>>

14:

1.2 把一些东东作为另一些东东导入
说明:
将整个模块导入,格式为:import somemodule;

从某个模块中导入某个函数,格式为:from somemodule import somefunction;

从某个模块中导入多个函数,格式为:from somemodule import firstfunc, secondfunc, thirdfunc

将某个模块中的全部函数导入,格式为:from somemodule import *

注意:如果两个模块中都有相同的函数,则可以使用第一种方法导入模块, 也可以使用关键字 as为相同的函数取个别名,例子:
1: #第一种导入方法

2: #导入模块

3: import module1

4: import module2

5: #调用同名函数的方法

6: module1.open()

7: module2.open()

8:

9: #第二种导入方法

10: #导入函数,并给函数取相应的别名

11: from module1 import open as open1

12: from module2 import open as open2

13:

例子:
1: #从math中导入sqrt

2: >>> from math import sqrt as msqrt

3: #从cmath中导入sqrt

4: >>> from cmath import sqrt as csqrt

5: >>> msqrt(100)

6: 10.0

7: >>> csqrt(-1)

8: 1j

9: >>>

10:

2 赋值魔法

2.1 序列解包
说明:多个赋值操作可以同时进行
例子:
1: #一般的同时赋值操作

2: >>> x, y, z = (1,2,3)

3: >>> x

4: 1

5: >>> y

6: 2

7: >>> z

8: 3

9: >>>

10:

11: #从字典中弹出任意一对儿键值对儿,并赋值给两个变量

12: >>> people = {'first': 'Andy', 'second':'Bill'}

13: >>> key, value = people.popitem()

14: >>> key

15: 'second'

16: >>> value

17: 'Bill'

18: >>>

19:

2.2 链式赋值
说明:同时将一个值赋给多个变量
例子:
1: #链式赋值

2: >>> x=y=z=1

3: >>> x

4: 1

5: >>> y

6: 1

7: >>> z

8: 1

9: >>>

10:

2.3 增量赋值
说明:包括以下增量操作:
+=:将右侧的值加到变量上的和,然后再赋值给变量;

-=:将变量减去右侧的值得到的差,再赋值给变量;

/=:用变量除以右侧值得到的商,再赋值给变量;

%=:用变量取右侧值的余数,再赋值给变量;

注意: += 和 \*= 还可以应用在字符串上,见下面的示例;
例子:
1: #针对数字的各种操作

2: >>> x = 123

3: >>> x += 1

4: >>> x

5: 124

6: >>> x -= 4

7: >>> x

8: 120

9: >>> x *=2

10: >>> x

11: 240

12: >>> x /=3

13: >>> x

14: 80.0

15: >>> x %=9

16: >>> x

17: 8.0

18: >>>

19:

20: #字符串的增量赋值

21: >>> y = 'Test string'

22: >>> y += ', haha!'

23: >>> y

24: 'Test string, haha!'

25: >>> y *= 2

26: >>> y

27: 'Test string, haha!Test string, haha!'

28: >>>

29:

3 语句块:缩排的乐趣
说明:语句块是一组语句,在代码前放置空格来缩进语句即可创建语句 块;
4 条件和条件语句

4.1 这就是布尔变量的作用
说明:布尔值,
假值:false,None,所有类型的数字0,空序列,空字典;
真值:所有的非空值;
bool函数可以用来将其他值转换成布尔值;
注意:尽管假值具有不同的类型,但是不同的假值之前也是 不相等 的
例子:
1: >>> True

2: True

3: >>> False

4: False

5: >>> []

6: []

7: >>> bool ([])

8: False

9: >>> bool ([1,])

10: True

11: >>> bool (0)

12: False

13: >>> bool (0.0)

14: False

15: >>> bool (0.1)

16: True

17: #不同的假值之间也是不相同的

18: >>> [] == {}

19: False

20: >>> [] == None

21: False

22: >>>

23:

4.2 条件执行和if语句
说明:if 判断其后面的条件语句是否为真,如果为真,执行if后面的语句 块,否则不执行;
4.3 else子句
说明:之所以称为子句是因为else必须跟在if语句后面,而不能单独使用;
4.4 elif子句
说明:如果需要更多的判断,可以使用elif,判断更多的条件;
例子:
1: #if, elif, else应用

2: num = input("Please enter a number:")

3: num = int(num)

4: if num > 0:

5: print ('You input a positive number!')

6: elif num < 0:

7: print ('You input a negative number!')

8: else:

9: print ('You input a zero!')

10:

4.5 嵌套代码块
说明:在if判断后,还需要进一步进行判断就可以使用嵌套代码的方式。
例子:
1: key = input("Please select type, color(c) or number(n):")

2: if key == 'c':

3: color = input ("Please select a color, Red(r), Green(g), Blue(b):")

4: if color == 'r':

5: print('You selected red')

6: elif color == 'g':

7: print('You selected green')

8: elif color == 'b':

9: print('You selected blue')

10: else:

11: print("Illegal color type!")

12: else:

13: print ("You select number!")

14:

4.6 更复杂的条件

4.6.1 比较运算符
说明:
x==y: 等于;
x<y:  小于;
x>y: 大于;
x<=y: 小于等于;
x>=y: 大于等于;
x!=y: 不等于;
x is y:x和y是同一对象;
x is not y:x和y不是同一对象;
x in y: x在y中;
x not in y: x不在y中;
注意:
比较运算符是可连接的,例如:14 < age < 26;

比较运算符不能比较不同类型的数据;
4.6.2 相等运算符
说明:用来判断两个数据是否相等;
4.6.3 同一性运算符
说明:用于判断两个变量是否指向同一对象;
注意:避免把 is 比较运算符应用于比较常量值,如数字,字符串等。 即 避免以下比较:
1: if '123' is '123':

4.6.4 成员资格运算符
说明:判断元素是否被包含在对象中;
4.6.5 字符串和序列比较
说明:字符串可以按照字母顺序排列进行比较;
4.6.6 布尔运算符
说明:包括,and, or, not
例子:
1: #or的特殊用法,如果没有输入,则会返回or后面的值

2: >>> name = input("Please enter a name:") or '<unknown>'

3: Please enter a name:

4: >>> name

5: '<unknown>'

6:

7: >>> a = 'a'

8: >>> c = 'c'

9: #如果if后面的判断语句为真,返回a

10: >>> a if True else c

11: 'a'

12: #如果if后面的判断语句为假,返回c

13: >>> a if False else c

14: 'c'

15: >>>

16:

4.7 断言
说明:关键字为 assert , 如果断言的条件判断为假,则程序直接崩溃
例子:
1: >>> age = 10

2: >>> assert 1<age<120, "Age must be realistic"

3: >>> age = -1

4: >>> assert 1<age<120, "Age must be realistic"

5: Traceback (most recent call last):

6: File "<pyshell#26>", line 1, in <module>

7: assert 1<age<120, "Age must be realistic"

8: AssertionError: Age must be realistic

9: >>>

10:

5 循环

5.1 while循环
说明:关键字 while ,判断条件为真就一直执行
例子:
1: name = ''

2: while not name.strip():

3: name = input("Please input your name:")

4: print("Hello,", name)

5.2 for循环
说明:可以用于迭代集合中的每个元素;
例子:
1: #遍历列表中的各个元素

2: >>> x = [1,2,3,4,5]

3: >>> for number in x:

4: print (number)

5: 1

6: 2

7: 3

8: 4

9: 5

10: >>>

11:

12: #使用内建函数range

13: >>> x = range(10)

14: >>> x

15: range(0, 10)

16: >>> for number in x:

17: print(number)

18: 0

19: 1

20: 2

21: 3

22: 4

23: 5

24: 6

25: 7

26: 8

27: 9

28: >>>

29:

5.3 循环遍历字典元素

说明:通过keys遍历字典,或者通过values
例子:
1: x = {'a':'1', 'b':'2', 'c':'3'}

2: for key in x.keys():

3: print (key, x[key])

4:

5: for val in x.values():

6: print(val)

7:

5.4 一些迭代工具

5.4.1 并行迭代
说明:zip内置函数可以将多个序列“压缩”成一个元组的序列;
例子:
1: >>> x = list(range(0,5))

2: >>> y = list(range(5,10))

3: >>> z = list(range(10, 15))

4: >>> z

5: [10, 11, 12, 13, 14]

6: >>> y

7: [5, 6, 7, 8, 9]

8: >>> x

9: [0, 1, 2, 3, 4]

10:

11: >>> zipped = zip(x, y, z)

12: >>> list(zipped)

13: [(0, 5, 10), (1, 6, 11), (2, 7, 12), (3, 8, 13), (4, 9, 14)]

14: >>>

15:

5.4.2 编号迭代
说明:使用内建函数enumerate来进行迭代操作;
例子:
1: >>> mylist = ['12312', '12ab', '123sa', '1231s']

2: >>> for index, string in enumerate(mylist):

3: print(index, string)

4:

5:

6: 0 12312

7: 1 12ab

8: 2 123sa

9: 3 1231s

10: >>>

11:

5.4.3 翻转和排序迭代
说明:内建函数reversed用于翻转序列,内建函数sorted用于对序列排 序,他们都是返回操作后的序列,不对原序列进行修改;
例子:
1: >>> data = [1,67,1,13,14,61,2]

2: >>> sorted(data)

3: [1, 1, 2, 13, 14, 61, 67]

4: >>> list(reversed(data))

5: [2, 61, 14, 13, 1, 67, 1]

6: >>>

7:

5.5 跳出循环

5.5.1 break
说明:符合条件时直接中断循环;
例子:
1: >>> import math

2: >>>for x in range(99, 0, -1):

3: >>> root = math.sqrt(x)

4: >>> if root == int(root):

5: >>> print ('Max number is:', x)

6: >>> break

7:

8: Max number is 81

9:

5.5.2 continue
说明:结束当前循环,并跳到下一轮循环开始;
例子:
1: #一个打印偶数的例子,不加else 语句,程序也能正确执行

2: >>> for x in range(10):

3: if x%2 == 0:

4: print(x)

5: else:

6: continue

7:

8:

9: 0

10: 2

11: 4

12: 6

13: 8

14: >>>

15:

5.5.3 while True/break
说明:while True部分实现了一个永不停止的循环,由内部的if判断语 句控制跳出循环;
例子:
1: while True:

2: word = input("Please enter a word:")

3: if not word:

4: break

5: print("You input:" , word)

6:

7: Please enter a word:TEst

8: You input: TEst

9: Please enter a word:ls

10: You input: ls

11: Please enter a word:

12: >>>

13:

5.5.4 循环中的else子句
说明:else子句可以用于判断循环操作是否始终没有执行break操作。
例子:
1: #设置一个奇数序列,判断里面是不是有偶数(一个蛋疼的程序,哈哈)

2: x = list(range(1,100,2))

3: for val in x:

4: if val%2 == 0:

5: print (x)

6: break;

7: else:

8: print("Did not break!")

9: #执行结果

10: Did not break!

11:

6 列表推导式
说明:利用其他列表创建列表,利用for循环遍历序列,将元素执行相应的 操作;
例子:
1: #得到10以内数字的平方的列表

2: import math

3: mylist = [math.pow(x, 2) for x in list(range(0,10))]

4: print (mylist)

5:

6: #得到10以内偶数的平方的列表

7: mylist = [math.pow(x, 2) for x in list(range(0,10)) if x % 2 == 0]

8: print (mylist)

9:

7 三人行

7.1 pass
说明:pass关键字用于占位,当函数或者代码块还没有添加时,可以用 pass来占位,以免语法错误
例子
1: >>> a = 10

2: #if的语句块中并没有其他语句需要执行,先用pass占位,执行的时候,如果if判断为真直接跳过。

3: >>> if a>0:

4: pass

5: >>>

7.2 del
说明:用于删除对象;
注意:del仅能删除变量或者对象中的项,不能直接删除变量指向的对象, 当对象没有被任何变量引用时,python会将变量回收;
例子:
1: >>> x = {'a':'1', 'b':'2', 'c':'3'}

2: >>> y = x

3: >>> y

4: {'a': '1', 'c': '3', 'b': '2'}

5: #删除变量x,再调用会报“未定义”的错误

6: >>> del x

7: >>> x

8: Traceback (most recent call last):

9: File "<pyshell#15>", line 1, in <module>

10: x

11: NameError: name 'x' is not defined

12: >>> y

13: {'a': '1', 'c': '3', 'b': '2'}

14: #删除字典中的项

15: >>> del y['a']

16: >>> y

17: {'c': '3', 'b': '2'}

18: >>>

19:

7.3 exec和eval
说明:
exec用于执行一个字符串的语句;
eval用于执行字符串语句,并返回语句执行的结果;
注意:通过增加字典,起到命名空间的作用,以防止由字符串的语句导致 的安全问题;
例子
1: #exec直接执行语句

2: >>> exec('print("Hello, world!")')

3: Hello, world!

4: #exec执行后不返回执行结果

5: >>> exec("2*2")

6: >>>

7: #exec在命名空间中执行语句

8: >>> exec("""

9: x=2

10: y=3

11: z=4

12: """, scope)

13: >>> scope.keys()

14: dict_keys(['__builtins__', 'x', 'z', 'y'])

15: >>> scope['x']

16: 2

17: >>>

18:

19: #eval直接执行语句

20: >>> eval('print("Hello, world!")')

21: Hello, world!

22: #eval在执行后将执行结果返回

23: >>> eval('2*2')

24: 4

25: >>>

26: #eval操作字典中的数据

27: >>> scope.keys()

28: dict_keys(['__builtins__', 'x', 'z', 'y'])

29: >>> eval('x+y+z', scope)

30: 9

31: >>>

32:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息