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 ...
随机推荐
- intellij安装 配置 创建项目
使用intellij创建项目的整个过程如下: 首先,点击intllij的.exe文件,如果是第一次安装,选择第二个选项即可 Intellij需要license key,可以使用注册机生成相应的name ...
- 【转】CPU调度
转自:http://blog.csdn.net/xiazdong/article/details/6280345 CPU调度 用于多道程序 以下先讨论对于单CPU的调度问题. 回顾多道程序,同时把 ...
- c#基础语言编程-正则表达式应用
引言 在不同语言中虽正则表达式一样,但应用函数还是有所区别,在c#语言中使用Regex. 可以通过以下两种方式之一使用正则表达式引擎: 通过调用 Regex 类的静态方法. 方法参数包含输入字符串和正 ...
- AngularJS的开发工具---yeoman 简易安装
AngularJS 不错,yeoman作为推荐开发工具,网上的安装步骤较烦,这里给出简易步骤. 1.安装 Ruby 自己到 Ruby 官方下载最新安装包: http://rubyinstall ...
- 淘宝分布式数据层:TDDL[转]
淘宝根据自己的业务特点开发了TDDL(Taobao Distributed Data Layer 外号:头都大了 ©_Ob)框架,主要解决了分库分表对应用的透明化以及异构数据库之间的数据复制,它是一个 ...
- [AngularJS + Webpack] Requiring Templates
With Angular, most of the time you're specifying a templateUrl for your directives and states/routes ...
- Android 颜色渲染(五) LinearGradient线性渲染
版权声明:本文为博主原创文章,未经博主允许不得转载. Android 颜色处理(五) LinearGradient线性渲染 相信很多人都看过歌词同步的效果, 一是竖直方向的滚动,另一方面是水平方面的歌 ...
- android 50 进程优先级
程序在磁盘叫程序,程序加载到内存运行起来叫进程,优先级5个级别,内存不足的时候会杀掉低级别进程. Active Process:最上面用户可以操作的. Visible Process:可见进程,部分可 ...
- codevs 1817 灾后重建
/* 暴力暴力 离线每次添边 堆优化dij 70 SPFA 80..... */ #include<iostream> #include<cstdio> #include< ...
- ASP.NET 微信支付
一.在支付前期,我们需要获取用户的OpenId,此块内容只针对于JSAPI(微信中直接支付)才需要,如果生成二维码(NATIVE)扫描支付,请跳过此步骤 思路大致是:获取用户的code值 > 根 ...