python 控制流

来源:互联网 发布:python 字典value求和 编辑:程序博客网 时间:2024/05/29 10:58

简明 Python 教程
Swaroop, C. H. 著
沈洁元  译

运算符通常由左向右结合,即具有相同优先级的运算符按照从左向右的顺序计算。例如,2 + 3 + 4被计算成(2 + 3) + 4。一些如赋值运算符那样的运算符是由右向左结合的,即a = b = c被处理为a = (b = c)

另外,注意Python如何打印“漂亮的”输出。尽管我们没有在'Area is'和变量area之间指定空格,Python自动在那里放了一个空格,这样我们就可以得到一个清晰漂亮的输出,而程序也变得更加易读(因为我们不需要担心输出之间的空格问题)。这是Python如何使程序员的生活变得更加轻松的一个例子。

我们为内建的raw_input函数提供一个字符串,我们通过int把这个字符串转换为整数

guess = int(raw_input('Enter an integer : '))

if语句的例子,注意缩进:


#Filename: if.pynumber = 23guess = int(raw_input('Enter an integer : '))if guess == number:    print 'Congratulations, you guessed it.' # New block starts here    print "(but you do not win any prizes!)" # New block ends hereelif guess < number:    print 'No, it is a little higher than that' # Another block    # You can do whatever you want in a block ...else:    print 'No, it is a little lower than that'    # you must have guess > number to reach hereprint 'Done'# This last statement is always executed, after the if statement is executedraw_input("press enter key to close..");
注:给C/C++程序员的注释
在Python中没有switch语句。你可以使用if..elif..else语句来完成同样的工作(在某些场合,使用字典会更加快捷。)

while循环语句有一个可选的else从句:

# Filename: while.pynumber = 23running = Truewhile running:    guess = int(raw_input('Enter an integer : '))    if guess == number:        print 'Congratulations, you guessed it.'        running = False # this causes the while loop to stop    elif guess < number:        print 'No, it is a little higher than that'    else:        print 'No, it is a little lower than that'else:    print 'The while loop is over.'    # Do anything else you want to do hereprint 'Done'
给C/C++程序员的注释
记住,你可以在while循环中使用一个else从句。

for..in是另外一个循环语句:


# Filename: for.pyfor i in range(1, 5):    print ielse:    print 'The for loop is over'

我们所做的只是提供两个数,range返回一个序列的数。这个序列从第一个数开始到第二个数为止。例如,range(1,5)给出序列[1, 2, 3, 4]。默认地,range的步长为1。如果我们为range提供第三个数,那么它将成为步长。例如,range(1,5,2)给出[1,3]。记住,range向上 延伸到第二个数,即它包含第二个数。

给C/C++/Java/C#程序员的注释
Python的for循环从根本上不同于C/C++的for循环。C#程序员会注意到Python的for循环与C#中的foreach循环十分类似。Java程序员会注意到它与Java 1.5中的for (int i : IntArray)相似。
在C/C++中,如果你想要写for (int i = 0; i < 5; i++),那么用Python,你写成for i in range(0,5)。你会注意到,Python的for循环更加简单、明白、不易出错。

break语句是用来 终止 循环语句的,即哪怕循环条件没有称为False或序列还没有被完全递归,也停止执行循环语句。

一个重要的注释是,如果你从forwhile循环中 终止 ,任何对应的循环else块将执行。

例:

# Filename: break.pywhile True:    s = raw_input('Enter something : ')    if s == 'quit':        break    print 'Length of the string is', len(s)print 'Done'

continue语句被用来告诉Python跳过当前循环块中的剩余语句,然后 继续 进行下一轮循环。

# Filename: continue.pywhile True:    s = raw_input('Enter something : ')    if s == 'quit':        break    if len(s) < 3:        continue    print 'Input is of sufficient length'    # Do other kinds of processing here...

注意,continue语句对于for循环也有效。



原创粉丝点击