条件,循环以及其他语句(下)

5.4、条件和条件语句

  5.4.1 关于bool值

  在学习条件语句的过程中,我们首先应该学习关于bool值。

  我们知道,用作bool表达式(如用if条件语句的条件),下面的值都将被解释器视为假:

  False   None  “” ()  []   {}

  换句话说,标准值False和None、各种类型(包括浮点数、复数等)的数值为0、空序列(如空元组等)以及空的映射(如空字典)都被视为假,而其他各种值都视为真,包括特殊值(True)。

 5.4.2  if语句、if...else语句、if....elif(多个)...else语句

 关于if语句、if....else语句、if....elif...else语句看下面一段代码就知道了:

 

name=input('What is your name')
if name.endwith('Gumby'):
    print("Hello,Mr.Gumby")

 

name=input('What is your name'if name.endwith('Gumby'):
    print("Hello,Mr.Gumby")
else:
    print('hehe')
num=int(input('Enter a number'))
if num>0:
    print('The number is positive')
elif num<0
    print('The number is negative')
else:
    print('The number is zero")

  5.4.5  代码块嵌套

  下面穿差点额外的内容,你可将if语句放在其他if语句快中。

name=input('what is your name?')
if name.endwith('Gumby'):
    if name.startswith('Mr.'):
        print('Hello,Mr.Gumby')
    elif name.startswith('Mrs.'):
        print('Hello,Mrs.Gumby')
    else:
        print('Hello,Gumby')
else:
    print('Hello,stranger')

 5.4.6 更复杂的条件

  1.关于比较判断符

                         表达式                                                                                       描述


                          x==y                                                                          x等于y

                          x<y                                                                             x小于y

                     x>y                                                                             x大于y

                     x>=y                                                                           x大于或者等于y

                     x<=y                                                                           x小于或者等于y

                     x!=y                                                                          x不等于y

                     x is y                                                                           x和y都是同一对象

                     x is not y                                                                     x和y不是同一对象

                     x in y                                                                           x是容器y(如序列)的成员

                     x not in y                                                                     x不是容器(如序列)的成员


    python也是支持链式比较的:可用多个比较运算符:如0<age<100

    需要注意的地方是:

    1.==与=前者可以用来比较,或者是用来赋值。

    2.is与==的区别,看下面的例子就能看出来:

>>>x==y=[1,2,3]
>>>z=[1,2,3]
>>>x==y
True
>>>x==z
True
>>>x is y
True
>>>x is z
False

 

     3.关于in这个成员资格运算符

name=input('what is your name?')
if 's' in name:
    print('your name contains the letter "s"')
else:
    print('your name is not contains the letter "s"')

     4.字符串与序列的比较(略)

    5.布尔运算符

     其中包含and、or、not这三个布尔运算符

  5.4.7 断言

   设置断言的目的在于让程序错误条件出现时立即崩溃胜过于以后崩溃。关键字为assert。而且在后面加上一个字符串,在报错的时候能够做出说明:

age=100
assert 0<age<10,'The age must be realistic'

 

报错为:

Traceback (most recent call last):
  File "E:/py_project/work/Test.py", line 4, in <module>
    assert 0<age<10,'The age must be realistic'
AssertionError: The age must be realistic

5.5 循环

  5.5.1 while循环

  关于while循环,看下面一个例子即可:

name=''
while not name:
    name=input('请输入您的姓名:')
    print('Hello,%s!'%name)

 

  5.5.2 for循环

   看一个简单的例子即可:

words=['this','is','an','ex','porrot']
for word in words:
    print(word)

 

结果为:

this
is
an
ex
porrot

   5.5.3  迭代字典

    下面讲的为如何迭代字典的两种方式:

d={'x':1,'y':2,'z':3}
for k in d:
    print(k,'correspods to',d[k])
d={'x':1,'y':2,'z':3}
for key,value in d.items():
    print(key,'correspods to',value)

 

 

 两者的效果是一样的:

x correspods to 1
y correspods to 2
z correspods to 3

 

   5.5.4一些迭代工具

    1.并行迭代

name=['anne','beth','george','damon']
ages=[12,45,32,102]
for i in range(len(name)):
    print(name[i],'is',ages[i],'years old')

 

结果为:

anne is 12 years old
beth is 45 years old
george is 32 years old
damon is 102 years old

   还有一种很有用的并行迭代工具是内置函数zip,它将两个序列“缝合”起来,并返回一个由元组组成的序列。返回的值是一个适合迭代的的对象,要查看其内容,可使用list将其转换成列表

name=['anne','beth','george','damon']
ages=[12,45,32,102]
print(list(zip(name,ages)))
for i in zip(name,ages):
    print(i)

 

从而产生结果

[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
('anne', 12)
('beth', 45)
('george', 32)
('damon', 102)

 

  注意,当序列长度不一致的时候,函数zip将在最短序列用完后停止“缝合” 。

  2.迭代时获取索引

  在这里我提一下关于序列的一个关键字enumerate,这个很有用;举个例子,

age=(12,13,14,7,9,20,34)
for index,value in enumerate(age):
    print(index,value)

 

从而,我们知道有结果为:

0 12
1 13
2 14
3 7
4 9
5 20
6 34

 

  3.反向迭代和排序后再迭代

  大致了解一些,关于reverse和sorted两种方法,注意其与列表的reverse和sort两种方法类似;但可用于任何序列或者可迭代对象 ,且不是就地修改对象,而是返回反转和排序后的版本。sorted返回的是一个列表,而reversed像zip一样返回的是一个更神秘的可迭代对象,如果需要查看,使用list对其对象进行转换,而且,需要注意的是,关于reversed返回的是一个可迭代对象,所以,我们直接在for或者join中使用即可。

print(sorted([4,2,1,3,7,6]))
print(list(reversed('Hello,word')))
print(''.join(reversed(['1','2','3','4','5'])))
print(''.join(reversed('hello,world')))

从而,结果为:

[1, 2, 3, 4, 6, 7]
['d', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'H']
54321
dlrow,olleh

   5.5.5跳出循环

  这部分我们主要讲解三个部分:break、continue、while True/break成例 ,其实都很简单,看一段代码就清楚了。

  1.break

from math import  sqrt
for n in range(10,0,-1):
print(n) root
=sqrt(n) if root==int(root): print(n) break

 

 从而,产生的结果为:

10
9
9

 

  2.continue

  把上段代码修改一下,我们可以看出,continue的作用:

 

from math import  sqrt
for n in range(10,0,-1):
    root =sqrt(n)
    print(n)
    if root==int(root):
        print(n)
        continue

 

 

 

  从而,产生结果为:

10
9
9
8
7
6
5
4
4
3
2
1
1

 

  3.while True/break成例

  举个简单的例子你就懂了:

while True:
    word=input('Please enter a word:')
    if not word:break
    print('The word was',word)

 

  5.5.6 循环中的else的子句

  else子句可以在for循环语句或者while循环语句中使用,它是在正常情况下执行else子句,而在break跳出的语句中是执行不了的.

from math import  sqrt
for n in range(99,81,-1):
    root=sqrt(n)
    if root==int(root):
        print(n)
        break
else:
    print('Didn\'t find it')

 

 从而,我们知道,得到的结果为:

Didn't find it

5.6  简单推导

从下面几个例子我们可以了解如何简单推导:

print([x*x for x in range(10)])
print([x*x for x in range(10) if x%3==0])
print([(x,y)for x in range(10)for y in range(10)])
girls=['alice','bernice','clarice']
boys=['chris','arnold','bob']
print([girl+'+'+boy for girl in girls for boy in boys if girl[0]==boy[0]])

 

 从而,结果为:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 9, 36, 81]
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (6, 9), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 7), (7, 8), (7, 9), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (8, 8), (8, 9), (9, 0), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8), (9, 9)]
['alice+arnold', 'bernice+bob', 'clarice+chris']

 

  5.7 三人行

  这三个分别代表pass、del、exec和eval,让我们分别来看看这三部分:

  5.7.1 什么也不做

   pass用在未完成的不会

x=input('请输入你的操作:)
if x==1:
print('heh')
else:
#在这个部分未完成,如果执行,会直接跳过,执行下面的代码
pass

 

 

 

   5.7.2 使用del来删除

  关于这个部分,我觉得有必要提一下,python解释器中存在垃圾回收机制,但我们删除的时候,只是将变量名在内存地址中删除,然后系统会自动的启动回收机制。举个简单的例子:

x=y=1
del x
print(y)

 

     从而,我们知道,得到的结果为:

1

 关于这个,我们知道删除的是x在内存的地址,并非删除1的存储,当y也被删除了,那么没有名称与它相互关联,系统就会自动启动垃圾回收机制,删除存储1的内存。而本身我们自己做不到这一点。

 5.7.3 使用exec和eval执行字符串以及计算器结果

  略

 

posted @ 2019-04-29 20:47  niwahanzi  阅读(235)  评论(0编辑  收藏  举报