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(startstop[, 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的更多相关文章

  1. [译]The Python Tutorial#4. More Control Flow Tools

    [译]The Python Tutorial#More Control Flow Tools 除了刚才介绍的while语句之外,Python也从其他语言借鉴了其他流程控制语句,并做了相应改变. 4.1 ...

  2. Python Tutorial 学习(八)--Errors and Exceptions

    Python Tutorial 学习(八)--Errors and Exceptions恢复 Errors and Exceptions 错误与异常 此前,我们还没有开始着眼于错误信息.不过如果你是一 ...

  3. Python基础学习四

    Python基础学习四 1.内置函数 help()函数:用于查看内置函数的用途. help(abs) isinstance()函数:用于判断变量类型. isinstance(x,(int,float) ...

  4. Python Tutorial 学习(六)--Modules

    6. Modules 当你退出Python的shell模式然后又重新进入的时候,之前定义的变量,函数等都会没有了. 因此, 推荐的做法是将这些东西写入文件,并在适当的时候调用获取他们. 这就是为人所知 ...

  5. 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 ...

  6. Python Tutorial 学习(十)-- Brief Tour of the Standard Library

    10.1. Operating System Interface os库 import os os.getcwd() # Return the current working directory 'C ...

  7. Python Tutorial 学习(五)--Data Structures

    5. Data Structures 这一章来说说Python的数据结构 5.1. More on Lists 之前的文字里面简单的介绍了一些基本的东西,其中就涉及到了list的一点点的使用.当然,它 ...

  8. Python Tutorial 学习(九)--Classes

    ## 9. Classes 类 Compared with other programming languages, Python's class mechanism adds classes wit ...

  9. Python Tutorial 学习(一)--Whetting Your Appetite

    Whetting Your Appetite [吊你的胃口]... 这里就直接原文奉上了... If you do much work on computers, eventually you fin ...

随机推荐

  1. Broken line - SGU 124(判断点与多边形的关系)

    题目大意:RT 分析:构造一条射线,如果穿越偶数条边,那么就在多边形外面,如果穿越奇数条边,那么就在多边形里面. 代码如下: ===================================== ...

  2. java 解析xml文件案例

    package xmlTest; import javax.xml.parsers.*; import org.w3c.dom.*; public class GetXml { public stat ...

  3. jQuery自定义多选下拉框

    项目中需要自定义一个下拉框多选插件,业务问题还是自己实现比较好 通过$.fn 向jQuery添加新的方法 下拉数据通过参数传递进去,通过调用该插件时接收,选择后的确定与取消事件采用事件传递方式 代码如 ...

  4. JSON 和 JSONP

    本文转载:http://www.cnblogs.com/shanyou/archive/2009/12/13/1623163.html JSON 和 JSONP  浏览器安全模型规定,XMLHttpR ...

  5. java中获取系统属性以及环境变量

    java中获取系统属性以及环境变量 System.getEnv()和System.getProperties()的差别 从概念上讲,系统属性 和环境变量 都是名称与值之间的映射.两种机制都能用来将用户 ...

  6. Spring Data MongoDB example with Spring MVC 3.2

    Spring Data MongoDB example with Spring MVC 3.2 Here is another example web application built with S ...

  7. FastDFS配置说明(中英文)

    FastDFS配置说明 1)tracker.conf # is this config file disabled # false for enabled # true for disabled di ...

  8. git 删除远程master 分支

    ➜  fekit-extension-yo git:(dev) git push origin :master remote: error: By default, deleting the curr ...

  9. PHP 5.6启动失败failed to open configuration file '/usr/local/php/etc/php-fpm.conf'

    PHP编译安装完毕,启动失败,提示 [-Jun- ::] ERROR: failed to open configuration ) [-Jun- ::] ERROR: failed to load ...

  10. insert当 sql语句里面有变量 为字符类型的时候 要3个单引号

    set @InsertStr='INSERT INTO [dbo].[T_SchoolPercentMonth]([SchoolID],[MonthOfYear],[PercentNum]) VALU ...