Python入门(5)——条件与循环:if、while、for

一、 条件if

条件语句格式:

执行语句……

if 判断条件:

执行语句……

else:

当if有多个条件时可使用括号来区分判断的先后顺序,括号中的判断优先执行,此外 and 和 or 的优先级低于>(大于)、<(小于)等判断符号,即大于和小于在没有括号的情况下会比与或要优先判断。


由于 python 并不支持 switch 语句,所以多个条件判断,只能用 elif 来实现,如果判断需要多个条件需同时判断时,可以使用 or (或),表示两个条件有一个成立时判断条件成功;使用 and (与)时,表示只有两个条件同时成立的情况下,判断条件才成功。

if 判断条件1:

执行语句1……

elif 判断条件2:

执行语句2……

elif 判断条件3:

执行语句3……

else:

执行语句4……

In [1]:

num = 5     if num == 3:            # 判断num的值
    print 'boss'        elif num == 2:
    print 'user'elif num == 1:
    print 'worker'elif num < 0:           # 值小于零时输出
    print 'error'else:
    print 'roadman'     # 条件均不成立时输出
roadman

 

1.1 and、or

对or而言,Python会由左到右求算操作对象,然后返回第一个为真的操作对象。

Python会在其找到的第一个真值操作数的地方停止,通常叫短路计算。

In [2]:

2 < 3, 3 < 2

Out[2]:

(True, False)

In [3]:

2 or 3, 3 or 2

Out[3]:

(2, 3)

 

如果左边的操作数为假(空对象),Python只会计算右边的操作数并将其返回

In [4]:

[] or 3

Out[4]:

3

In [5]:

[] or {}

Out[5]:

{}

and 会停在第一个为假的对象上

In [6]:

2 and 3, 3 and 2

Out[6]:

(3, 2)

In [7]:

[] and {} #空 list 本身等同于 False

Out[7]:

[]

In [ ]:

#由于一个空 list 本身等同于 False,所以可以直接:if mylist:
  # Do something with my listelse:
  # The list is empty

 

1.2 神奇的布尔值

从一个固定大小的集合中选择非空的对象,只要将其串在一个or表达式即可

In [ ]:

X = A or B or C or None #会把X设为A、B以及C中第一个非空(为真)的对象,或者所有对象都为空就设为None

In [ ]:

X = A or default # 如果A为真(或非空)的话将X设置为A,否则,将X设置为default

In [ ]:

if f1() or f2():...# 如果f1返回真值(非空),Python将不再执行f2,若要保证两个函数都执行,需要在or之前调用他们,如tmp1, tmp2 = f1(), f2()if tmp1 or tmp2:...

 

二、循环

稍后会介绍更加奇特的迭代工具,如生成器、filter和reduce。现在先从最基础的学起。

Python提供了for循环和while循环(在Python中没有do...while循环),for循环一般比while计数器循环运行得更快

break语句,在语句块执行过程中终止循环,并且跳出整个循环

continue语句,在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环。

pass语句,是空语句,是为了保持程序结构的完整性。不做任何事情,一般用做占位语句。

循环else块,只有当循环正常离开时才会执行(也就是没有碰到break语句)

 

2.1 while

In [8]:

count = 0while (count < 9):
   print 'The count is:', count
   count = count + 1

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8

 

2.2 for

是一个通用的序列迭代器,可以遍历任何有序的序列对象内的元素。可用于字符串、列表、元组、其他内置可迭代对象等

In [ ]:

for iterating_var in sequence:
   statements(s)

In [10]:

for letter in 'Python':     # 第一个实例
   print '当前字母 :', letterfruits = ['banana', 'apple',  'mango']for fruit in fruits:        # 第二个实例
   print '当前字母 :', fruit

当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h
当前字母 : o
当前字母 : n
当前字母 : banana
当前字母 : apple
当前字母 : mango

In [11]:

T = [(1,2), (3,4), (5,6)]for (a,b) in T:
    print (a,b)

(1, 2)
(3, 4)
(5, 6)

In [12]:

D = {'a':1,'b':2,'c':3}for key in D:
    print (key,'=>',D[key])

('a', '=>', 1)
('c', '=>', 3)
('b', '=>', 2)

In [13]:

D.items()

Out[13]:

[('a', 1), ('c', 3), ('b', 2)]

In [14]:

for (key,value) in D.items():
    print (key,'=>',value)

('a', '=>', 1)
('c', '=>', 3)
('b', '=>', 2)

嵌套的结构可以自动解包

In [15]:

for ((a,b),c) in [((1,2),3),((4,5),6)]: print (a,b,c)

(1, 2, 3)
(4, 5, 6)


 

2.3 break

In [16]:

for letter in 'Python':     # First Example
   if letter == 'h':
      break
   print 'Current Letter :', letter

Current Letter : P
Current Letter : y
Current Letter : t

 

2.4 continue

In [17]:

for letter in 'Python':     # 第一个实例
   if letter == 'h':
      continue
   print '当前字母 :', letter

当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : o
当前字母 : n

 

2.5 pass

In [18]:

for letter in 'Python':
   if letter == 'h':
      pass
      print '这是 pass 块'
   print '当前字母 :', letter

当前字母 : P
当前字母 : y
当前字母 : t
这是 pass 块
当前字母 : h
当前字母 : o
当前字母 : n

In [ ]:

 

免责声明:信息仅供参考,不构成投资及交易建议。投资者据此操作,风险自担。
如果觉得文章对你有用,请随意赞赏收藏
相关推荐
相关下载
登录后评论
Copyright © 2019 宽客在线