python笔记05:条件、循环和其它语句
5.1 print和import的更多使用方式
5.1.1 使用逗号输出
print 'Age',42
print 1,2,3
>>> name = 'Gumby'
>>> salutation = 'Mr.'
>>> greeting = 'Hello'
>>> print greeting,salutation,name
Hello Mr. Gumby
>>> print greeting + ',',salutation,name
Hello, Mr. Gumby
>>> print greeting,',',salutation,name
Hello , Mr. Gumby
5.1.2 把某件事作为另一件事导入
import somemodule
from somemodule import somefunction
from somemodule import somefunction1 somefunction2 somefunction3
from somemodule import *
>>> import math as foobar
>>> print foobar.sqrt(9)
3.0
>>> from math import sqrt as foobar
>>> foobar(4)
2.0
5.2 赋值魔法
5.2.1 序列解包
>>> x,y,z = 1,2,3
>>> print x,y,z
1 2 3
>>> y=x
>>> print x,y,z
1 1 3
>>> x,z=z,x
>>> print x,y,z
3 1 1
>>> dd = {'name':'Anti','Age':42}
>>> key,value = dd.popitem()
>>> key
'Age'
>>> value
42
5.2.2 链式赋值
x = y = somefunction()
#
y = somefunction()
x = y
x = somefunction()
y = somefunction()
5.2.3 增量赋值
>>> x = 2
>>> x += 1 #加等
>>> x
3
>>> x *= 6 #乘等
>>> x
18
>>> x -= 2 #减等
>>> x
16
5.3 语句块
5.4 条件和条件语句
5.4.1 布尔变量的作用
>>> bool('I think, therefor I am.')
True
>>> bool([])
False
>>> bool({'name':'Aoto'})
True
>>> bool(0)
False
5.4.2 条件执行和if语句
5.4.3 else子句
name = raw_input("What's your name ? ")
if name.endswith('Gumby'):
print 'Hello, Mr.Gumby.'
else:
print 'Hello, stranger.'
#输出如下
What's your name ? Gumby
Hello, Mr.Gumby.
5.4.4 elif语句
if ...:
do ...
elif ...:
do ...
else:
do ...
5.4.5 嵌套代码块
5.4.6 更复杂的条件
1.比较运算符
2.相等运算符:==
3.is:同一性运算符
>>> x = y = [1,2,3]
>>> z = [1,2,3]
>>> x == y
True
>>> x == z
True
>>> x is y
True
>>> x is z
False #注意
4.in:成员资格运算符
5.字符串和序列比较
6.布尔运算符
number = input('Enter a number between 1 and 10 : ')
if number <= 10 and number > 1:
print 'Great!'
else:
print 'Wrong!'
#输出如下
Enter a number between 1 and 10 : 8
Great!
name = raw_input('Please input your name: ') or '<Unknow>'
print name
#输出如下:
Please input your name:
<Unknow>
#输出如下:
Please input your name: Aoto
Aoto
a if b else c
x=2 if 10>=2 else 4
print x result = 'gt' if 1 >3 else 'lt'
print result
5.4.7 断言:assert
if not condition:
crash program
>>> age = 10
>>> assert 0 < age < 100
>>> age = -1
>>> assert 0 < age < 100
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> age = -1
>>> assert 0 < age < 100, 'The age must be reallistic.'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: The age must be reallistic.
5.5 循环
5.5.1 while循环
name = ''
while not name or name.isspace():
name = raw_input('Please enter your name: ')
print 'Hello,%s!' % name
#输出如下:
Please enter your name:
Please enter your name: #输入空格是无效的,要求重新输入
Please enter your name: dodo
Hello,dodo!
5.5.2 for循环
kl = []
for i in range(1,10,2):
kl.append(i)
print kl #输出如下
[1, 3, 5, 7, 9]
5.5.3 循环遍历字典元素
>>> d = {'name':'ToTo','Age':23,'Address':'BeiJing'}
>>> for key in d:
... print key,'corresponds to',d[key]
...
Age corresponds to 23
name corresponds to ToTo
Address corresponds to BeiJing
>>> for k,v in d.items():
... print k,'corresponds to',v
...
Age corresponds to 23
name corresponds to ToTo
Address corresponds to BeiJing
5.5.4 一些迭代工具
1.并行迭代
names = ['Anne','Beth','George','Damon']
ages = [12,23,78,67]
for name,age in zip(names,ages):
print name,'is',age,'years old.' #输出如下
Anne is 12 years old.
Beth is 23 years old.
George is 78 years old.
Damon is 67 years old.
name = ['Anne','Beth','George','Damon']
age = [12,23,78,67]
for i in range(len(name)):
print name[i],'is',age[i],'years old.' #输出如下
Anne is 12 years old.
Beth is 23 years old.
George is 78 years old.
Damon is 67 years old.
zip(range(5),xrange(1000))
输出:[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
2.按索引迭代
for string in strings:
if 'xxx' in string:
index = strings.index(string)
strings[index] = '[censored]'
index = 0
for string in strings:
if 'xxx' in string:
strings[index] = '[censored]'
index += 1
for index,string in enumerate(strings):
if 'xxx' in string:
string[index] = '[censored]'
3.翻转和排序迭代:reversed和sorted
>>> sorted([4,3,5,2,3,6,9,0])
[0, 2, 3, 3, 4, 5, 6, 9]
>>> sorted('Hello,world!')
['!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('Hello,world!'))
['!', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello,world!'))
'!dlrow,olleH'
5.5.5 跳出循环
1.break
from math import sqrt
for n in range(99,0,-1):
root = sqrt(n)
if root == int(root):
print root,n
break #结果如下,求出0-100范围内最大的平方数
9.0 81
2.continue
for x in seq:
if condition1:continue
if condition2:continue
if condition3:continue do_something()
do_something_else()
do_another_thing()
etc()
for x in seq:
if not(condition1 or condition1 or condition1):
do_something()
do_something_else()
do_another_thing()
etc()
3.while True/break习语:
while True:
word = raw_input('Please enter a word: ')
if not word: break
#处理word
print 'The word was ' + word
4.循环中的else语句
from math import sqrt
for n in range(99,0,-1):
root = sqrt(n)
if root == int(root):
print root,n
break
else:
print "Don't find it."
5.6 列表推导式:轻量级循环
>>> [x*x for x in range(5)]
[0, 1, 4, 9, 16]
>>> [x*x for x in range(10) if x%3 == 0]
[0, 9, 36, 81]
>>> [(x,y) for x in range(3) for y in range(3) if y<=x]
[(0, 0), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2)]
>>> [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
girls = ['alice','bernice','clarice']
boys = ['chris','arnord','bob']
print [boy + ' + ' + girl for boy in boys for girl in girls if boy[0]==girl[0]]
#结果如下
['chris + clarice', 'arnord + alice', 'bob + bernice']
girls = ['alice','bernice','clarice','bibl']
boys = ['chris','arnord','bob']
letterGirls = {}
for girl in girls:
letterGirls.setdefault(girl[0],[]).append(girl)
print letterGirls
print [Boy + ' + ' + Girl for Boy in boys for Girl in letterGirls[Boy[0]]] #结果如下
{'a': ['alice'], 'c': ['clarice'], 'b': ['bernice', 'bibl']}
['chris + clarice', 'arnord + alice', 'bob + bernice', 'bob + bibl']
5.7 三人行:pass、del、exec
5.7.1 什么都没发生:pass
if name == 'Raplh Auldus Melish':
print "Welcome!"
elif name == 'Enid':
#在elif这个代码块中,必须要有一个执行语句,否则空代码块在Python中是非法的,解决方法就是加一个pass
#还没完
pass
elif name == 'Bill Gates':
print "Access Denied!"
5.7.2 使用del删除
>>> x = 1
>>> del x
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> x = ["Hello",'World']
>>> y = x
>>> y[1] = "python"
>>> x
['Hello', 'python']
>>> del x
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> y
['Hello', 'python']
5.7.3 使用exec和eval执行和求值字符串
1.exec
>>> exec "print 'Hello,world!'"
Hello,world!
>>> from math import sqrt
>>> exec "sqrt = 1"
>>> sqrt(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> from math import sqrt
>>> scope = {}
>>> exec 'sqrt = 1' in scope
>>> sqrt(4)
2.0
>>> scope['sqrt']
1
2.eval
5.8 小结
python笔记05:条件、循环和其它语句的更多相关文章
- python学习笔记2_条件循环和其他语句
一.条件循环和其他语句 1.print和import的更多信息. 1.1.使用逗号输出 //print() 打印多个表达式是可行的,用逗号隔开. 在脚本中,两个print语句想在一行输出 ...
- Python基础教程之第5章 条件, 循环和其它语句
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 #Chapter 5 条件, 循环 ...
- Python之条件 循环和其他语句 2014-4-6
#条件 循环和其他语句 23:30pm-1:431.print和import的更多信息 使用逗号将多个表达式输出 >>> print 'age:',42 age: 42 >&g ...
- Python笔记之字典循环
Python笔记之字典循环 1.问题 Python是一门比较好入门的编程语言,但是入门简单,当然坑也是有的,今天就来介绍一个我遇到的坑吧,也是很简单的一个,就是当时脑子有点转不过弯来了. 先看代码 ...
- python笔记05
python笔记05 数据类型 上个笔记知识点总结: 列表中extend特性:extend,(内部循环,将另外一个列表,字符串.元组添加到extend前的列表中) li.extend(s),将s中元素 ...
- python基础教程第5章——条件循环和其他语句
1.语句块是在条件为真(条件语句)时执行或者执行多次(循环语句)的一组语句.在代码前放置空格来缩进语句即可穿件语句块.块中的每行都应该缩进同样的量.在Phyton中冒号(:)用来标识语句块的开始,块中 ...
- 一步一步学python(五) -条件 循环和其他语句
1.print 使用逗号输出 - 打印多个表达式也是可行的,但要用逗号隔开 >>> print 'chentongxin',23 SyntaxError: invalid synta ...
- python基础之条件循环语句
前两篇说的是数据类型和数据运算,本篇来讲讲条件语句和循环语句. 0x00. 条件语句 条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块. 可以通过下图来简单了解条件语 ...
- python变量、条件循环语句
1. 变量名 - 字母 - 数字 - 下划线 #数字不能开头:不能是关键字:最好不好和python内置的函数等重复 2. 条件语句 缩进用4个空格(Tab键)注意缩进如果是空格键和Tab键混用, ...
随机推荐
- java中拼写xml
本文为博主原创,未经博主允许,不得转载: xml具有强大的功能,在很多地方都会用的到.比如在通信的时候,通过xml进行消息的发送和交互. 在项目中有很多拼写xml的地方,进行一个简单的总结. 先举例如 ...
- js ajax跨域
一般情况后台返回... 也就是说,无论数据本身是什么数据类型,数据,对象,都是以字符串形式返回的. 如何把字符串化成相应对象. 如: var s='{"left":100}' co ...
- Java中引用的详解
Java中没有指针,到处都是引用(除了基本类型).所以,当然,你肯定知道java的引用,并用了很久,但是是不是对此了解地比较全面?而这些引用有什么作用,且有什么不同呢?Java中有个java.lang ...
- hdu 1573 X问题 两两可能不互质的中国剩余定理
X问题 Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Problem Desc ...
- 转载:负载均衡器技术Nginx和F5的优缺点对比
https://blog.csdn.net/zxc456733/article/details/78861100 nginx(一) nginx详解 nginx是一个被广泛使用的集群架构组件,我们有必要 ...
- jQuery双击编辑td数据
html <td class="remark" style="width: 200px;"> {$vo.remark} </td> js ...
- org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): 问题解决方法
在用maven配置mybatis环境时出现此BindingExceptiony异常,发现在classes文件下没有mapper配置文件,应该是maven项目没有扫描到mapper包下的xml文件,在p ...
- Python处理HTML转义字符
抓网页数据经常遇到例如>或者 这种HTML转义符,抓到字符串里很是烦人. 比方说一个从网页中抓到的字符串: html = '<abc>' 用Python可以这样处理: import ...
- mycat分布式mysql中间件(自增主键)
一.全局序列号 全局序列号是MyCAT提供的一个新功能,为了实现分库分表情况下,表的主键是全局唯一,而默认的MySQL的自增长主键无法满足这个要求.全局序列号的语法符合标准SQL规范,其格式为:nex ...
- 用Rails.5.2+ Vue.js做 vue-todolist app
Rails5.2+Vue.js完成Lists(curd) 注意: Edit/update使用SPA(single-page Application单页面程序)的方法完成.点击文字出现一个输入框和按钮. ...