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

5.1 print和import的更多信息

1. print()3.0之后print不再是语句,而是函数,

       >>> print('udg',12,13)   udg 12 13

       >>> name='yanliang'  >>> print(name)  yanliang 

2. import 把某件事当做另外一件事导入

import somemodule

from somemodule import somefunction

from somemodule import somefunction1,somefunction2,somefunction3.。。。

from somemodule import *

(1)为导入的模块提供别名:>>> import math as foo  >>> foo.sqrt(4)   2.0

(2)也可以为函数提供别名:>>>from module import function as function1

5.2 赋值魔法

1. 序列解包

(1)多个赋值同时进行:>>> x,y,z=1,2,3  >>> print(x,y,z)  1 2 3

(2)>>> x,y=y,x  >>> print(x,y)  2 1

2. 链式赋值

(1)>>> x=y=2 相当于 >>> y=2  >>> x=y

3. 增量赋值

(1)>>> x+=3 类似于C++中的

5.3 语句块:缩排的乐趣

5.4 条件和条件语句

1. bool值是True配合False  ,bool()函数可以用来转换其它的值。

2. if语句 

1 name=input("what is your name!")
2 if name.endswith('liang'):
3     print('hello,yanliang')

3.else子句

1 name=input("what is your name!")
2 if name.endswith('liang'):
3     print('hello,yanliang')
4 else:
5     print("hello stringer")

 4. elseif

5. 嵌套代码块

6. 更复杂的条件

(1)比较运算符:例如x<y , x<=y ,0<x<100也可以等

(2)相等运算符:>>> "foo"=="foo"  True  >>> "foo"=="fod"  False

(3)is: 同一性运算符:

       >>> x=y=[1,2,3]  >>> x is y  True  这里x,y被绑定到同一个对象上,所以具有同一性

      >>> z=[1,2,3]  >>> z is y  False      z虽然与y是相等的但不是同一个对象所以不具有同一性

(4)in 成员资格运算符

(5)字符串和序列的比较:按照字母顺序排列

(6)bool运算符:and or not

1 name=int(input("input the number"))
2 if name<10 and name>1:
3     print("OK")
4 else:
5     print("wrong")

(7)断言 assert 当不满足条件时直接崩溃退出

5.5 循环

1. while循环

1 name=''
2 while not name:
3     name=input("please input your name")
4     print("hello %s !" % name)

2. for循环

1 for number in range(10):
2     print(number)

3. 循环遍历字典元素

1 d={"a":1,"b":2,"c":3}
2 for key in d:
3     print(key,"corrsponds to",d[key])

 4. 一些迭代工具

(1)并行迭代:zip()可以将两个序列合成一个字典对应起来

1 key1=['a','b','c']
2 value2=[1,2,3]
3 mapa=zip(key1,value2)
5 for name,age in mapa: 6 print(name,'is',age)

(2)编号迭代

将字符串数组中的包含‘yan’的自字符串全部替换成‘yanliang’

一种方法:

1 strings=['jhsf','yansgd','gd']
2 print(strings,'
')
3 index=0;
4 for string in strings:
5     if 'yan' in string:
6         strings[index]='yanliang'
7     index+=1
8 print(strings,'
'

第二种方法:采用enumerate函数 enumerate(strings)可以返回索引-值对

1 strings=['jhsf','yansgd','gd']
2 print(strings,'
')
3 index=0;
4 for index,string in enumerate(strings):
5     if 'yan' in string:
6         strings[index]='yanliang'
7 print(strings,'
') 

 (3)翻转和排序迭代

sorted和reserved 返回排好序或翻转后的对象

sort和reserve 在原地进行排序或翻转

5. 跳出循环

(1)break

(2)continue

(3)while True  。。。break

6. 循环中的else 语句

5.6 列表推导式——轻量级的循环

>>> [x*x for x in range(10)]  [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

>>> [x*x for x in range(10) if x%3==0]  [0, 9, 36, 81]

5.7 pass del exec

pass: 程序什么也不做

del: 不仅会删除对象的引用也会删除对象的名称,但是那个指向的对象的值是没办法删除的

exec: 执行一个字符串语句

          最好是为这个exec语句提供一个命名空间,可以放置变量的地方

eval: 

         >>> eval(input('please input the number '))

         please input the number 

         1+2+3

         6  

原文地址:https://www.cnblogs.com/yanliang12138/p/4708940.html