码迷,mamicode.com
首页 > 编程语言 > 详细

Python 每天一小时(10.16)

时间:2014-10-16 12:37:42      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   使用   ar   for   sp   数据   

模版的导入:

import somemodule
from somemodule import somefunction
from somemodule import somefunction,anotherfunction,threefunction
from somemodule import *
from somemodule as somename

bool值:False None 0 ‘‘ {} () [] 都会认为是False,其他的一切都会被解释为真。

条件语句:if else elif while for (这里比较不写了和以前了解的基本一样)

              is 和 ==的区别  is判断是否是同一 == 表示是否相等

一些迭代工具:

    在python中迭代对象的时候,内建函数是非常有用的。

zip可以将两个序列‘压缩在一起’然后返回一个元组列表。

>>> names = [hanxingzhi,zhengli,zhangli]
>>> ages = [12,32,43]
>>> for i in range(len(names)):
    print names[i],is,ages[i],years old

    
hanxingzhi is 12 years old
zhengli is 32 years old
zhangli is 43 years old
>>> for name,age in zip(names,ages):
    print name,is,age,years old

    
hanxingzhi is 12 years old
zhengli is 32 years old
zhangli is 43 years old
>>> 

其中zip的返回值是

>>> zip(names,ages)
[(hanxingzhi, 12), (zhengli, 32), (zhangli, 43)]

另外要了解的是zip可以应用任意多的序列,对应不同长度的序列当最短的序列用完的时候zip方法就会停止。

循环中的else语句:

import math

num = 0
for i in range(101,200):
    k = int(math.sqrt(i))
    for j in range(2,k + 1):
        if i % j == 0:
            break;
    else:
        num += 1
        print %-4d % i
print the total num is,num

上面的语句是查找101到200之间的所有的素数,可以好好体会一下else的使用。

在循环内部使用break常常是因为找到了某个事物或者某个事件发生了,在跳出之前做一些事情,如果我们要在没有找到某个事物或者没有发生某个事件的时候做一些事情。

一种方式是使用bool变量在循环之前设置为False,当在循环中发生了事情的时候将起设置为True然后在循环的外部使用if来判断循环是否跳出了。

另一种方式是使用else关键字,在循环的外面添加else,如果在循环的内部没有发生break语句,那么在循环结束就会执行else中的语句。

 

列表推倒式:(已经了解过了在了解一下了当巩固了)

     是利用其他列表创建新的列表

>>> [x*x for x in range(0,10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

   在后面可以添加条件:

>>> [x*x for x in range(0,10) if x % 3 == 0]
[0, 9, 36, 81]

    还可以添加更多的for循环

>>> [(x,y) for x in range(0,10) if x % 3 == 0 for y in range(3)]
[(0, 0), (0, 1), (0, 2), (3, 0), (3, 1), (3, 2), (6, 0), (6, 1), (6, 2), (9, 0), (9, 1), (9, 2)]

 

走马观花三个语句:pass del exec

    pass :有些时候程序什么都不做,那么就使用pass,相当与在c#中使用的空语句。

name = han
if name == some:
    print name is %s % name
elif name == sb:
    pass
else:
    print name is han

   del:Python会删除那些不在使用的对象,del语句用来删除变量,或者数据结果中一部分,但是不用用来删除值。

   exec:语句用来执行与python程序相同的字符串。

     

Python 每天一小时(10.16)

标签:style   blog   color   io   使用   ar   for   sp   数据   

原文地址:http://www.cnblogs.com/someoneHan/p/4028227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!