跳转到内容

Python 编程入门/Python 编程 - 控制结构

来自维基教科书,自由的教科书,共建自由世界

4. 控制结构

[编辑 | 编辑源代码]

一组动作定义了事件流,由流程图决定。在 Python 编程中,所有非“None”的值都返回 True,而具有“None”值的变量则返回 False。

4.1. if 语句

[编辑 | 编辑源代码]

最简单的控制 if 语句在条件满足时返回 True 值。有一个简单的单行 if 条件,接着是 if-else,然后是 if-elif 语句。

   >>> var = 100
   >>> if var==100:

print "yay! 变量确实是 100!!!"

   yay! the variable is truly 100!!!
   >>>
   >>> 
   >>> if (var==100): print "value is 100, its looks great!"
   value is 100, its looks great!
   >>>
   var = 100
   if var == 100:
       print "yay! the variable is truly 100"
   else:
       print "Nope! Better luck next time!!!!"
   >>>var=10
   >>> if var == 100:
           print "yay! the variable is truly 100"
       else:
           print "Nope! Better luck next time!!!!"
   Nope! Better luck next time!!!!

4.2. for 循环

[编辑 | 编辑源代码]

Python 中的“for”循环会对一个代码块执行已知次数的迭代。Python 中“for”循环的特殊之处在于,可以对列表、字典、字符串变量中的项目数量进行迭代,以特定步骤数对特定范围的数字进行迭代,以及对元组中存在的项目数量进行迭代。

   >>> a=(10,20,30,40,50)
   >>> for b in a:
   print "square of " + str(b) + " is " +str(b*b)
   square of 10 is 100
   square of 20 is 400
   square of 30 is 900
   square of 40 is 1600
   square of 50 is 2500
   >>> c=["new", "string", "in", "python"]
   >>> for d in c:
           print "the iteration of string is %s" %d
   the iteration of string is new
   the iteration of string is string
   the iteration of string is in
   the iteration of string is python
   >>>
   >>> for i in range(10):

print " "+str(i)+" 的值为 "+str(i)

   the value of 0 is 0
   the value of 1 is 1
   the value of 2 is 2
   the value of 3 is 3
   the value of 4 is 4
   the value of 5 is 5
   the value of 6 is 6
   the value of 7 is 7
   the value of 8 is 8
   the value of 9 is 9
   >>> a={'a':10,'b':20,'c':30}
   >>> for k in a:
       	print "the key is %s and the value is %d" %(k,a[k])
   the key is a and the value is 10
   the key is c and the value is 30
   the key is b and the value is 20

4.3. while 循环

[编辑 | 编辑源代码]

while 循环在条件语句返回 true 时执行。在执行代码块之前,每次都会评估条件语句,并且在条件语句返回 false 的那一刻,执行就会停止。

   >>> count = 0
   >>> while (count<9):
       print "the count is at iteration %d" %count
       count+=1
   the count is at iteration 0
   the count is at iteration 1
   the count is at iteration 2
   the count is at iteration 3
   the count is at iteration 4
   the count is at iteration 5
   the count is at iteration 6
   the count is at iteration 7
   the count is at iteration 8
华夏公益教科书