Python简单入门

来源:互联网 发布:php 点击增加添加表单 编辑:程序博客网 时间:2024/05/16 12:43

Python 10 分钟入门

文中用到很多print,要注意的是3.0以上版本需这样使用:print(xxx)

总结:

help(<object>)  //获取帮助

dir(<object>)     //显示该对象的所有方法

<object>.__doc__    //会显示其文档


单行注释以井号字符(#)开头

多行注释则以多行字符串的形式出现,eg:

"""

"""


可以在一行上使用多个变量:  myvar, mystring = aaa, bbb 


Python具有列表 [list]、元组(tuple)和字典{dictionaries}三种基本的数据结构

元组是不可变的一维数组

负数索引值能够从后向前访问数组元素,-1表示最后一个元素。数组元素还能指向函数


运算符访问数组中的某一段,如果:左边为空则表示从第一个元素开始,同理:右边为空则表示到最后一个元素结束。负数索引则表示从后向前数的位置(-1是最后一个项目),eg:

>>> mylist = ["List item 1", 2, 3.14]

>>> print mylist[:]
['List item 1', 2, 3.1400000000000001]
>>> print mylist[0:2]              //从第0项开始,包(括)左不包(括)右

['List item 1', 2]                 

>>> print mylist[-3:-1]
['List item 1', 2]

>>> print mylist[::2]               //从第0项开始,每间隔2取值
['List item 1', 3.14]


>>>print "Name: %s\              //%s(或者%(key)s)为占位符  ,\表示字符串还没输入完,占位符内容以后面%加上(元组)顺序内容或者{字典}对应value代替
Number: %s\
String: %s" % (myclass.name, 3, 3 * "-")
Name: Poromenos
Number: 3
String: ---

>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}

This is a test.


Python中可以使用if、for和while来实现流程控制。Python中并没有select

rangelist = range(10)                    
>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for number in rangelist:       //for用法

if number in (3, 4, 7, 9):       //if-else用法

elif 判断条件 :                     

else:

while rangelist[1] == 1:       //while用法


函数通过“def”关键字进行声明,Lambda函数是由一个单独的语句组成的特殊函数,参数通过引用进行传递,但对于不可变类型(例如元组,整数,字符串等)则不能够被改变

def funcvar(x): return x + 1   等同于   funcvar = lambda x: x + 1


可选参数以集合的方式出现在函数声明中并紧跟着必选参数,可选参数可以在函数声明中被赋予一个默认值。已命名的参数需要赋值。函数可以返回一个元组(使用元组拆包可以有效返回多个值)。

# an_int 和 a_string 是可选参数,它们有默认值
# 如果调用 passing_example 时只指定一个参数,那么 an_int 缺省为 2 ,a_string 缺省为 A default string。如果调用 passing_example 时指定了前面两个参数,a_string 仍缺省为 A default string。
# a_list 是必备参数,因为它没有指定缺省值。
def passing_example(a_list, an_int=2, a_string="A default string"):    //赋值的可选参数an_int、a_string在必选参数a_list
a_list.append("A new item")
an_int = 4
return a_list, an_int, a_string


>>> my_list = [1, 2, 3]
>>> my_int = 10
>>> print passing_example(my_list, my_int)
([1, 2, 3, 'A new item'], 4, "A default string")
>>> my_list                        //列表传递地址,可修改
[1, 2, 3, 'A new item']
>>> my_int                       //数值不能修改
10


Python支持有限的多继承形式。私有变量和方法可以通过添加至少两个前导下划线和最多尾随一个下划线的形式进行声明(如“__spam”,这只是惯例,而不是Python的强制要求)。当然,我们也可以给类的实例取任意名称。

class MyClass(object):                //定义了一个类
common = 10                            //变量
def __init__(self):                         //私有方法
self.myvariable = 3
def myfunction(self, arg1, arg2):     //方法
return self.myvariable


# This is the class instantiation
>>> classinstance = MyClass()                    //新建实例(对象)
>>> classinstance.myfunction(1, 2)
3
# This variable is shared by all classes.
>>> classinstance2 = MyClass()                //新建实例(对象)
>>> classinstance.common
10
>>> classinstance2.common
10
# Note how we use the class name
# instead of the instance.
>>> MyClass.common = 30                   //修改类中变量的值,所有该类的实例的值修改
>>> classinstance.common
30
>>> classinstance2.common
30
# This will not update the variable on the class,
# instead it will bind a new object to the old
# variable name.
>>> classinstance.common = 10            //修改实例中变量的值后,类中变量的值的修改不影响该实例
>>> classinstance.common
10
>>> classinstance2.common
30
>>> MyClass.common = 50
# This has not changed, because "common" is
# now an instance variable.
>>> classinstance.common
10
>>> classinstance2.common
50


类的形参可为另一个类

class OtherClass(MyClass):

def __init__(self, arg1):
self.myvariable = 3
print arg1


>>> classinstance = OtherClass("hello")
hello
>>> classinstance.myfunction(1, 2)
3

>>> classinstance.test = 10                //实例没有test这个变量,但也可以临时加上去
>>> classinstance.test
10


Python中的异常由 try-except [exceptionname] 块处理

def some_function():
try:                                                                //try
# Division by zero raises an exception
10 / 0
except ZeroDivisionError:                             //catch except
print "Oops, invalid."
else:                                                              //如果没有except
# Exception didn't occur, we're good.
pass
finally:                                                           //finally
# This is executed after the code block is run
# and all exceptions have been handled, even
# if a new exception is raised while handling.
print "We're done with that."

>>> some_function()
Oops, invalid.
We're done with that.


外部库可以使用 import [libname] 关键字来导入。同时,你还可以用 from [libname] import [funcname] 来导入所需要的函数。


Python针对文件的处理有很多内建的函数库可以调用。

import pickle
mylist = ["This", "is", 4, 13327]

myfile = open(r"C:\\binary.dat", "w")            //打开文件,可w(write)
pickle.dump(mylist, myfile)                           把数组mylist写到文件myfile
myfile.close()

myfile = open(r"C:\\text.txt", "w")
myfile.write("This is a sample string")            //直接写进字符串
myfile.close()

myfile = open(r"C:\\text.txt") 
>>> print myfile.read()
'This is a sample string'
myfile.close()

# Open the file for reading.
myfile = open(r"C:\\binary.dat")
loadedlist = pickle.load(myfile)
myfile.close()
>>> print loadedlist
['This', 'is', 4, 13327]


  • 数值判断可以链接使用,例如 1<a<3 能够判断变量 a 是否在1和3之间。
  • 可以使用 del 删除变量或删除数组中的元素。                //del mylist[2]
  • 列表推导式(List Comprehension)提供了一个创建和操作列表的有力工具。列表推导式由一个表达式以及紧跟着这个表达式的for语句构成,for语句还可以跟0个或多个if或for语句。
>>> lst1 = [1, 2, 3]
>>> lst2 = [3, 4, 5]
>>> print [x * y for x in lst1 for y in lst2]         //1*(3,4,5),2*(3,4,5),3*(3,4,5)
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print [x for x in lst1 if 4 > x > 1]               //lst1数组中大于1小于4的元素
[2, 3]


>>> any([i % 3 for i in [3, 3, 4, 4, 3]])               //any是条件判断,只要条件有一个达到即可    4%3 == 1,1为True,0为false
True

>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)
2


全局变量在函数之外声明,并且可以不需要任何特殊的声明即能读取,但如果你想要修改全局变量的值,就必须在函数开始之处用global关键字进行声明,否则Python会将此变量按照新的局部变量处理(请注意,如果不注意很容易被坑)。

//不知道是不是我理解的问题,但是我在3.4版本试好像不加global也没影响

number = 5

def myfunc():
# This will print 5.
print number

def anotherfunc():
# This raises an exception because the variable has not
# been bound before printing. Python knows that it an
# object will be bound to it later and creates a new, local
# object instead of accessing the global one.
print number
number = 3                                         

def yetanotherfunc():
global number
# This will correctly change the global.
number = 3

0 0
原创粉丝点击