Python Tutorial 学习(四)--More Control Flow Tools
4.1 if 表达式
作为最为人熟知的if.你肯定对这样的一些表达式不感到陌生:
>>> x = int(raw_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'
...
More
if 后面可以跟上一个或者多个分支,代码上表现为else或者elif.toturial菌的说明里面这样解释的:elif是else if的缩写...
if ... elif ... elif ... 可以很好的作为类似C语言里面的switch ... case ... 的替代.
4.2. for 表达式
同 C 或者 Pascal比较的话,Python中的for长的又略有不同.与前面两者不同的是(至于怎么不同,只有知道了才知道了,哎呀),Python里面的for表达式 'iterates over the items of any sequence',也就是说,任何可以 '迭代'的'东西'都是可以作为for表达式的对象的(a list or string).
>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print w, len(w)
...
cat 3
window 6
defenestrate 12
原文这里给出了一个很好的栗子,解了我之前的一个疑惑,也是怪自己基础没有打牢固,不知道这样来用.
这里给出原文中的解释说明:
If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:
>>> for w in words[:]: # Loop over a slice copy of the entire list.
... if len(w) > 6:
... words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
4.3. range()函数
内建函数rang()用来生成一个整数构成的序列.
range()有多种用法,
range(stop)
range(start, stop[, step])
常用的是直接提供一个参数stop,比如
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
再比如,给出开始和结束:
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
又比如,给出开始,结束,又再给出步长:
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
负数哟哟,切克闹...
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
4.4. break and continue Statements, and else Clauses on Loops
如果你有过C语言的学习经历,辣么你肯定对于break和continue不感到困惑和迷茫,简单来说,break就是用来终止当前层的循环(跳出当前一层的循环),continue则是用来进入当前循环的下一次.
欧耶,once more~
Python里面比较稀奇的是,对于循环(while, for)来说,还可以再跟上一个for循环.
4.5. pass Statements
pass 就是什么也不做.给出几个常用的地方
def foo():
pass
class Foo(object):
pass
if xxx:
do something
else:
pass
try:
# if can
do something
except:
# pass it
pass
简单的说一下,就是,有时候预定义一个函数,预定义一个类但是光是想到了原型骨架,细节部分尚为完善的时候,可以用一个pass来占位.这样Pthon编译的时候就可以通过,否则就会有语法错误.先用一个pass放在那里,后面再慢慢的完善.
还有写地方必须要 '做些什么'的时候,但是又没有必要'做些什么',那么就也可以去做一点'什么也不做'的操作,比如说try的except里面
4.6. Defining Functions
Python里面函数的定义需要用关键字def起头.函数名称中可以包含字母数字下划线,关于函数名字的问题,这个非常值得好好学习一番.
def foo():
do something
函数名称需要定义的恰到好处,简洁明了,能看到函数就知道要做什么,想来也是极好的.
函数支持别名,比如我定义了一个函数 def a_very_long_named_func():print 'hello';
那么我同样也可以这样用
f = a_very_long_named_func
当我调用f()的时候,同样的也会打印 'hello'
所有的函数都会有返回,默认没有return的时候,返回的就是None
4.7. More on Defining Functions
4.7.1. Default Argument Values
为函数的参数指定一个默认值
i = 5 def f(arg=i):
print arg i = 6
f()
这样做的意义在于,当没有传入参数的时候,默认值就会起作用,当有时候不必要去传入参数的时候,默认值同样也会起作用.
需要注意的是:
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:
def f(a, L=[]):
L.append(a)
return L print f(1)
print f(2)
print f(3)
This will print
[1]
[1, 2]
[1, 2, 3]
If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
4.7.2. Keyword Arguments
Python里面定义函数的时候,经常会看见诸如 def foo(request, *args, **kwargs)样子的函数
这里需要说明的是*args是一个list,而**kwargs则是一个dict
简单的一个栗子说明一下
a, b, c, d = 1, 2, 3, 4
e, f, g = 5, 6, 7
def f(*args, **kwargs):
print args, type(args)
print kwargs, type(kwargs)
f(a, b, c, d, e=e, f= f, g=g, h=a)
#output
[1, 2, 3, 4] list
{'e': 5, 'f': 6, 'g': 7, 'h': 1} dict
4.7.5. Lambda Expressions
Small anonymous functions can be created with the lambda keyword. This function returns the sum of its two arguments: lambda a, b: a+b. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope:
当一些函数简单到不需要专门的去定义一个函数的时候,可以用lambda临时的来一发,比如说这样
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
又比如:
f = lambda x, y: x + y # 冒号左边的是参数,右边的返回的值 f(1, 2) # 将会得到1和2的和3
4.7.6. Documentation Strings
一份好的代码,往往不需要注释都清晰明了一目了然,但当项目代码变得复杂,高度的模块化了的时候,嵌套引用有时候又会让人看的云里雾里.所以适当的注释同样是有必要的.Python里面的有这么个东西 docstring,使用方法是用三引号给标记出来,python在适当的时候会自动的把这些东西展现出来,比如说,这样:
>>> def my_function():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
>>> print my_function.__doc__
Do nothing, but document it. No, really, it doesn't do anything.
4.8. Intermezzo: Coding Style
代码风格:每个语言都会有自己的代码风格,Python同样如此.关于代码风格,这里建议看一下PEP8 和PEP20
[pep8]http://legacy.python.org/dev/peps/pep-0008/
[pep20]http://legacy.python.org/dev/peps/pep-0020/
附上原文:
Use 4-space indentation, and no tabs.
4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out.
Wrap lines so that they don’t exceed 79 characters.
This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.
Use blank lines to separate functions and classes, and larger blocks of code inside functions.
When possible, put comments on a line of their own.
Use docstrings.
Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4).
Name your classes and functions consistently; the convention is to use CamelCase for classes and lower_case_with_underscores for functions and methods. Always use self as the name for the first method argument (see A First Look at Classes for more on classes and methods).
Don’t use fancy encodings if your code is meant to be used in international environments. Plain ASCII works best in any case.
Python Tutorial 学习(四)--More Control Flow Tools的更多相关文章
- [译]The Python Tutorial#4. More Control Flow Tools
[译]The Python Tutorial#More Control Flow Tools 除了刚才介绍的while语句之外,Python也从其他语言借鉴了其他流程控制语句,并做了相应改变. 4.1 ...
- Python Tutorial 学习(八)--Errors and Exceptions
Python Tutorial 学习(八)--Errors and Exceptions恢复 Errors and Exceptions 错误与异常 此前,我们还没有开始着眼于错误信息.不过如果你是一 ...
- Python基础学习四
Python基础学习四 1.内置函数 help()函数:用于查看内置函数的用途. help(abs) isinstance()函数:用于判断变量类型. isinstance(x,(int,float) ...
- Python Tutorial 学习(六)--Modules
6. Modules 当你退出Python的shell模式然后又重新进入的时候,之前定义的变量,函数等都会没有了. 因此, 推荐的做法是将这些东西写入文件,并在适当的时候调用获取他们. 这就是为人所知 ...
- Python Tutorial学习(十一)-- Brief Tour of the Standard Library – Part II
11.1. Output Formatting 格式化输出 The repr module provides a version of repr() customized for abbreviate ...
- Python Tutorial 学习(十)-- Brief Tour of the Standard Library
10.1. Operating System Interface os库 import os os.getcwd() # Return the current working directory 'C ...
- Python Tutorial 学习(五)--Data Structures
5. Data Structures 这一章来说说Python的数据结构 5.1. More on Lists 之前的文字里面简单的介绍了一些基本的东西,其中就涉及到了list的一点点的使用.当然,它 ...
- Python Tutorial 学习(九)--Classes
## 9. Classes 类 Compared with other programming languages, Python's class mechanism adds classes wit ...
- Python Tutorial 学习(一)--Whetting Your Appetite
Whetting Your Appetite [吊你的胃口]... 这里就直接原文奉上了... If you do much work on computers, eventually you fin ...
随机推荐
- Java 内存泄露的理解与解决过程
本文详细地介绍了Java内存管理的原理,以及内存泄露产生的原因,同时提供了一些列解决Java内存泄露的方案,希望对各位Java开发者有所帮助. Java内存管理机制 在C++ 语言中,如果需要动态分配 ...
- poj 2631 Roads in the North【树的直径裸题】
Roads in the North Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 2359 Accepted: 115 ...
- [转]jquery中使用event.target的几点
转自: http://www.cnblogs.com/12go/archive/2011/12/28/2304502.html 1.this和event.target的区别: js中事件是会冒泡的,所 ...
- hdu 2546 饭卡(DP)
很久以前做过这道题,晚上睡不着,看见nyist加了一个DP的比赛,就进来打个酱油. 这道题的点睛之笔是将最大值记录下来,然后将其值改为0.之后就是普通的背包了. #include<stdio.h ...
- 《Linux设备驱动开发详解(第2版)》配套视频登录51cto教育频道
http://edu.51cto.com/course/course_id-379-page-1.html http://edu.51cto.com/course/course_id-379-page ...
- IAAS云计算产品畅想-公有云主机产品优势
关于云计算的优势介绍真是太多太多了,但是说实话准确性欠妥. 云计算也是有很多细分的: 公有云.私有云.混合云 IAAS.PAAS.SAAS 园区云.行业云(医疗云.教育云等等) 说起优点来,绝对不能一 ...
- 每天一个JavaScript实例-从一个div元素删除一个段落
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...
- [RxJS + AngularJS] Sync Requests with RxJS and Angular
When you implement a search bar, the user can make several different queries in a row. With a Promis ...
- hdoj Last non-zero Digit in N! 【数论】
找规律! 求N!最后非0位的值.比方2是120的最后一个不是0的值. 输入N比較大,要大数保存. 注意到最后0的个数是与5的因数的个数相等.设f(n)为n!的最后非0位. 那么f(n)=((n%5)! ...
- Notepad++如何安装并使用source code pro 字体 转
http://blog.yucanlin.cn/2015/04/08/linux-%E5%AE%89%E8%A3%85-source-code-pro-%E5%AD%97%E4%BD%93/ ht ...