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

1、 条件if

条件语句格式:python

执行语句……bash

if 判断条件:app

执行语句……函数

else:工具

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

因为 python 并不支持 switch 语句,因此多个条件判断,只能用 elif 来实现,若是判断须要多个条件需同时判断时,可使用 or (或),表示两个条件有一个成立时判断条件成功;使用 and (与)时,表示只有两个条件同时成立的状况下,判断条件才成功。spa

if 判断条件1:code

执行语句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:...
复制代码

2、循环

稍后会介绍更加奇特的迭代工具,如生成器、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 [ ]:
复制代码

转载:宽客在线

相关文章
相关标签/搜索