python入门

来源:互联网 发布:收购淘宝客户资料 编辑:程序博客网 时间:2024/06/06 23:59

1.不需要显式声明数据类型

a=100.0b=201.1c=2343print (a+b+c)/c

2.字符串访问

word="abcdefg"b=word[1:3]print "b is: "+b # index 1 and 2 elements of word.f=word[-1]print "f is: "+f # The last elements of word.g=word[-4:-2]print "g is: "+g # index 3 and 4 elements of word.
3.函数定义

# Define and invoke function.def sum(a,b):    return a+bfunc = sumr = func(5,6)print r# Defines function with default argumentdef add(a,b=2):    return a+br=add(1)print rr=add(1,5)print r
4.读写文件

spath="D:/baa.txt"f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist.f.write("First line 1.\n")f.writelines("First line 2.")f.close()f=open(spath,"r") # Opens file for readingfor line in f:    print linef.close()
5.类与继承

class Base:    def __init__(self):    #initial function        self.data = []    def add(self, x):        self.data.append(x)    def addtwice(self, x):        self.add(x)        self.add(x)# Child extends Baseclass Child(Base):    def __init__(self):   #子类可不定义inital函数而默认调用基类        self.data=[2]    def plus(self,a,b):        return a+boChild =Child()     #objectoChild.add("str1")print oChild.dataprint oChild.plus(2,3)
6. 每一个.py文件称为一个module,module之间可以互相导入

# a.pydef add_func(a,b):    return a+b
# b.pyfrom a import add_func # Also can be : import aprint "Import add_func from module a"print "Result of 1 plus 2 is: "print add_func(1,2)    # If using "import a" , then here should be "a.add_func"
比较简单的例子是两个module放在同一目录下







0 0
原创粉丝点击