head first python 第三章

Help on method_descriptor:

一 - find(…)

S.find(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.
   Return -1 on failure.
  • str.find()。find是str类的一个函数

  • 找不到返回的是-1

  • 另外python的string 类型是关键字是“str

-

二 python里的判断语句if

not关键字

>>> a=10
>>> b=9
>>>> if not a<b:
    print("Hello World")


Hello World

not相当于其他语言里面的!

三 三元运算符

>>> x,y=4,3
#2.5以前的版本
>>> smaller=(x<y and [x] or [y])[0]
>>> print(smaller)
3
#在2.5版本更新后,可以写如下简单的条件表达式
>>> smaller=x if x<y else y
>>> smaller
3

三 for 循环
一般for循环语法

for iter_var in iterable:
    suite_to_repeat

3.1用于序列类型
如下代码返回的字符串的每个字符。对iterable执行迭代

>>> for eachLetter in 'Names':
    print ('curren letter:',eachLetter)

curren letter: N
curren letter: a
curren letter: m
curren letter: e
curren letter: s

3.1.1通过序列项迭代

>>> nameList=['walter','nicole','steve','henry']
>>> for eachName in nameList:
    print(eachName)


walter
nicole
steve
henry

3.1.2用序列索引迭代
C++,java属性的方式

>>> nameList=['walter','nicole','steve','henry']
>>> for index in range(len(nameList)):
    print(nameList[index])


walter
nicole
steve
henry

3.1.3使用项和索引迭代

class enumerate(object)
 |  enumerate(iterable[, start]) -> iterator for index, value of iterable
 |  
 |  Return an enumerate object.  iterable must be another object that supports
 |  iteration.  The enumerate object yields pairs containing a count (from
 |  start, which defaults to zero) and a value yielded by the iterable argument.
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...

使用enumerate()函数

>>> for index,each_name in enumerate(nameList):
    print ("%d %s Lee"%(index+1,each_name))


1 walter Lee
2 nicole Lee
3 steve Lee
4 henry Lee

print在3.0 才加的外扩号。
在3.0里面 xrange被去掉。并且range返回的不再是一个list而是一个range object

四 pass语句

由于python没有大括号,有些需要用大括号来结束的地方。如果没写语言解释器会报语法错误,于是pass 就来填充这种情况。

五 while else语句

在循环中使用else语句时,else子句只在循环完成后执行,也就是说break语句会跳过else块。

对比代码~
python
求最大约数。先对num进行折半,得到count。然后取num与count的余数,当count>1并且取余为0是,此时的count即为最大公约数。

这里的代码,else在每次执行完循环;也就当count<=1时,执行。

def showMaxFactor(num):
    count=int(num/2)
    while count>1:
        if num % count == 0:
            print('the lagest factor of %d is %d'%(num,count))
            break
        count-=1
    else:
        print(num,"is prime")


for eachNum in range(10,21):
    showMaxFactor(eachNum)
#这里有个点 关于python的/运算符
>>> 10/2
5.0
>>> 11/2
5.5
>>> 10%5
0
>>> 11%5.5
0.0
#可以看到返回的时候一个浮点类型,而取余运算根据参与运算的类型来判断返回类型 
#这里要做转换
>>> int(11/2)
5

再来看没有while else的C++代码

void showMaxFactor(int num){
    int count = num/2;
    while(count>1){
        if(num%count==0){
                printf("the lagest factor of %d is %d \n",num,count);
                break;
        }
        else{
            count--;
        }
    }
//python简化了代码,在结构上减少了一次判断,并使程序的逻辑变的清晰。
    if(count<=1){
        printf("%d is prime\n",num);
    }
}


int main(int argc, char** argv) {
    for(int i=10;i<21;i++){
        showMaxFactor(i);
    }
    showMaxFactor(2);
    return 0;
}

以上代码输出结果均为:
这里写图片描述

第三章代码:

import os

try:
#getcwd返回当前运行路径
    os.getcwd()
#chdir(url)变更运行路径至url
    os.chdir('D:/python/chapter3')
#打开文件,如果文件不存在会跑出IOError异常
    data = open('sketch.txt')
#readline()读出一行文件,返回一个str这里将end=''原因是每读出的一行后面有一个'\n',用strip('\n')可以删掉头尾的换行。
    print(data.readline(),end='')
    print(data.readline(),end='')
#seek(0)返回文件的初始位置    
    data.seek(0)
    for each_line in data:
            try:
#split返回的是一个list。这里定义的应该是一个元祖?
                (role,line_spoken) = each_line.split(':',1)
                print(role,end='')
                print('said:',end='')
                print(line_spoken,end='')
            except ValueError:
                pass
    data.close()
except IOError:
    print('The data file is missing')

try……expect在语法细节上与2.X也有些变化。暂且不表
这段代码要补充的就是文件读写关操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值