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键混用, ...
随机推荐
- ACM-ICPC 2018 沈阳赛区网络预赛 Made In Heaven(K短路)题解
思路:K短路裸题 代码: #include<queue> #include<cstring> #include<set> #include<map> # ...
- 3D CNN for Video Processing
3D CNN for Video Processing Updated on 2018-08-06 19:53:57 本文主要是总结下当前流行的处理 Video 信息的深度神经网络的处理方法. 参考文 ...
- 让低版本浏览器支持html5的标签
原理就是首先用js的createElement来创建,之后在使用 document.createElement('header'); <header> <hgroup>头部信息 ...
- HDU 2544 最短路(Dijkstra)
https://vjudge.net/problem/HDU-2544 题意: 输入包括多组数据.每组数据第一行是两个整数N.M(N<=100,M<=10000),N表示成都的大街上有几个 ...
- ZOJ 3869 Ace of Aces
There is a mysterious organization called Time-Space Administrative Bureau (TSAB) in the deep univer ...
- 51nod 1042 数字0-9的数量 数位dp
1042 数字0-9的数量 基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题 收藏 关注 给出一段区间a-b,统计这个区间内0-9出现的次数. 比如 10-1 ...
- C# 二进制字符串互转
1.字符转二进制 public static string ChineseToBinary(string s) { byte[] data = Encoding.Unicode.GetBytes(s) ...
- Unity3D中人物模型的构成
1.动画: 2.骨骼: 就是一些 Transform 组件,没有其他组件,它们会根据动画的要求而进行运动. 3.皮肤: 其上的 SkinnedMeshRenderer 关联了 网格.骨骼.材质 三个组 ...
- php.ini配置说明
1.设置时区为中国时区 date.timezone = PRC 2.设置支持MySql数据 extension=php_pdo_mysql.dll 直接将这个注释打开就OK了 3.让PHP支持简写&l ...
- Java基础七-正则表达式
Java基础七-正则表达式 一.定义: 特定的符号的组合 二.作用: 用于操作字符串数据 三.优缺点 简化代码,但是阅读性差 四.引入 4.1 问题 判断一个号码是否是QQ号? 不是零开头 6-15位 ...