python起步

python有两种主要的方式来完成你的要求:语句和表达式(函数.算术表达式等)

程序输出,print语句和hello word

核心笔记:在交互式解释器中显示变量的值

>>> my_str = "morning"
>>> print my_str
morning
>>> my_str
'morning'

注释: 仅使用变量名时,输出的字符串是被用单引号括起来的

程序输入和raw_input()内建函数

从用户那里得到数据最容易的方法是使用raw_input()内建函数.他读取标准输入,并将读取到的数值赋值给指定变量.

>>> user = raw_input('Enter you name: ')
Enter you name: root
>>> print 'Your login is:',user
Your login is: root

上面例子中只能用于文本输入,下面输入一个数值字符串(并将字符串转换为整数)

>>> num = raw_input('Now enter a number: ')
Now enter a number: 88
>>> print 'Dubling your number: %d' % (int(num)*2)
Dubling your number: 176

核心笔记: 从交互式解释器中获取帮助

通过函数名作为help(的参数就能得到相应的帮助信息)

>>> help(raw_input)
Help on built-in function raw_input in module __builtin__:

raw_input(...)
    raw_input([prompt]) -> string
    
    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.
/tmp/tmpn4M32b (END)

####运算符

算术运算符

/ 用于传统除法,// 用于浮点除法

+ - * / // % **

比较运算符

<
<=
>
>=
==
!=  不等于
<>  不等于(不常用)

逻辑运算符(and or not)

#使用逻辑运算符可以将任意表达式连接在一起,并得到一个布尔值:
>>> 2 < 4 and 2 == 4
False
>>> 2 > 4 or 2 < 4
True
>>> not 6.2 <= 6
True
>>> 3 < 4 < 5
True

核心风格:适当的使用括号,可增强代码的可读性

变量和赋值

python是动态类型语言,也就是说不需要预先声明变量的类型.变量的类型和值在赋值那一刻被初始化.变量赋值通过等号来执行

>>> counter = 0
>>> miles = 1000.0
>>> name = 'xiaoxiao'
>>> kilometers = 1.609 * miles
>>> print '%f miles is the same as %f km' % (miles,kilometers)
1000.000000 miles is the same as 1609.000000 km

####数字

python 支持五种基本数字类型,其中三种是整数类型.

  1. int(有符号整数)
  2. long(长整数)

python长整数仅受限于用户计算机的虚拟内存总数

  1. bool(布尔值)

布尔值是特殊的整数,尽管布尔值由常量True和False来表示,如果将布尔值放到数值上下文环境中(比如讲True与一个数字相加),True会被当成整数值1,而False则会被当成整数值0.复数(包括-1的平方根,即所谓的虚数)在其它语言中通常不被直接支持(一般通过类来实现).

  1. float(浮点值)
  2. complex(复数)

####字符串

python中字符串被定义为引号之间的字符合集.python支持使用单引号或双引号,三引号可以用来包含特殊字符.使用索引运算符([])和切片运算符([:])可以得到字符串.字符串有器特有的索引规则:第一个字符的索引是0,最后一个字符的索引是-1

加号(+)用于字符串连接运算,星号(*)则用于字符串重复,下面是几个例子:

>>> pystr = 'python'
>>> iscool = 'is cool'
>>> pystr[0]
'p'
>>> pystr[2:5]
'tho'
>>> iscool[3:]
'cool'
>>> iscool[-1]
'l'
>>> pystr + iscool
'pythonis cool'
>>> pystr + ' ' + iscool
'python is cool'

####列表和元组

相同点: 可以将列表和元组当成普通的"数组",它能保存任意数量任意类型的python对象,和数组一样,通过从0开始的数字索引访问元素,但是列表和元组可以存储不同类型的对象.

不同点: 列表元素用中括号([])包裹,元素的个数及元素的值可以改变.元组用小括号(())包裹,不可改变.元组可以看成是只读列表.通过切片运算([]和[:])可以得到子集,与字符串的使用方法相同.

>>> alist = [1,2,3,4]
>>> alist
[1, 2, 3, 4]
>>> alist[0]
1
>>> alist[1:2]
[2]
>>> alist[1] = 5
>>> alist
[1, 5, 3, 4]

元组也可以进行切片运算,得到的结果也是元组(不可被修改):

>>> atuple = ('xiaoxiao',55,33,'liu')
>>> atuple
('xiaoxiao', 55, 33, 'liu')
>>> atuple[3]
'liu'
>>> atuple[:3]
('xiaoxiao', 55, 33)
>>> atuple[3:]
('liu',)
>>> atuple[1] = 5
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    atuple[1] = 5
TypeError: 'tuple' object does not support item assignment

####字典

字典是python中的映射数据类型,工作原理类似Perl中的关联数组或哈希表,由键值(key-value)对构成,几乎所有类型的python对象都可以用作键,一般以数字或者字符串最为常用,值可以使任意的python对象,字典元素用大括号({})包裹

#创建一个字典
>>> adict = {'host':'localhost'}
#给字典添加一个元素
>>> adict['port'] = 80
>>> adict
{'host': 'localhost', 'port': 80}
#取字典当中的values
>>> adict.values()
['localhost', 80]
#取字典当中的key
>>> adict.keys()
['host', 'port']
>>> adict['host']
'localhost'
#遍历字典并打印
>>> for i in adict:
...     print i,adict[i]
...     
... 
host localhost
port 80

####代码块缩进对齐

####if语句

标准if条件语句的语法如下:

#expression:表达式[ikˈspreSHən]
#suit:合适的[so͞ot]
if expression:
    if_suite

如果表达式的值非0或者布尔值True,则代码组if_suite被执行;负责执行下一条语句.

与其他语言不同,条件表达式并不需要括号括起来.

if x < 0:
    print '"x" must be atleast 0!'
#
if expression:
    if_suit
else:
    else_suit
#
if expression1:
    if_suit
elif expression2:
    elif_suit
....
else:
    else_suit

####while循环

while expression:
    while_suit

语句while_suit会被连续不断的循环执行,直到表达式的值变成0或False;接着python会执行下一句代码.

>>> counter = 0
>>> while counter < 3:
...     print 'loop #%d' % (counter)
...     counter += 1
...     
... 
loop #0
loop #1
loop #2

####for循环和range()内建函数

python中的for循环与传统的for循环不太一样,他更像shell脚本里的foreach迭代,python中的for接收可迭代对象(例如序列或迭代器)作为其参数,每次迭代其中一个元素

>>> for item in ['xx','lyh','ly']:
...     print (item)
...     
... 
xx
lyh
ly

print 语句默认会给每一行添加一个换行符,在print后加一个逗号(,),就能避免这种情况

>>> for item in ['xx','lyh','ly']:
...     print (item),
...     
... 
xx lyh ly

使用带逗号的print语句输出,会有空格出现,可以通过格式化输出来解决这一问题

>>> who = "你"
>>> do = "喜欢"
>>> something = "pa"
>>> print who, do, something
你 喜欢 pa
>>> print who, do, something,something
你 喜欢 pa pa
>>> print who, do, '%s' %(something * 3)
你 喜欢 papapa

rang() 获取一个递增的序列

Help on built-in function range in module __builtin__:

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers
    
    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.

range()函数经常和len()函数一起用于字符串索引

>>> foo = 'abc'
>>> for i in range(len(foo)):
...     print foo[i],'%d' %(i)
...     
... 
a 0
b 1
c 2

上述循环有一个问题,只能循环索引,或者循环元素,下面介绍enumerate()函数

# enumerate:枚举[iˈn(y)o͞oməˌrāt]
# iterable:可迭代
 
Help on class enumerate in module __builtin__:

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]), ...
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |  
 |  next(...)
 |      x.next() -> the next value, or raise StopIteration
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T
>>> for i , ch in enumerate(foo):
...     print i , ch
...     
... 
0 a
1 b
2 c
>>> for i , ch in enumerate(foo,1):
...     print i , ch
...     
... 
1 a
2 b
3 c

####列表解析

可以在一行中使用一个for循环将所有值放到一个列表当中:

>>> squared = [x ** 2 for x in range(4)]
>>> for i in squared:
...     print i
...     
... 
0
1
4
9
>>> sqdevens = [x ** 2 for x in range(8) if not x % 2]
>>> for i in sqdevens:
...     print i
...     
... 
0
4
16
36

####被狗吃了
####文件和内建函数open() file()

open()

handle = open(file_name,access_mode = 'r')
file_name 变量包含我们希望打开的文件的字符串名字,access_mode中
'r'表示读取
'w'表示读写
'a'表示添加
'+'表示读写
'b'表示二进制访问
Help on built-in function open in module __builtin__:

open(...)
    open(name[, mode[, buffering]]) -> file object
    
    Open a file using the file() type, returns a file object.  This is the
    preferred way to open a file.  See file.__doc__ for further information.
    

>>> filename = raw_input('enter file name: ')
enter file name: expect.sh
>>> fobj = open(filename,'r')
>>> for i in fobj:
...     print i

核心笔记:

属性是与数据有关的项目,属性可以是简单的数据值,也可以是可执行对象,比如函数和方法.可以使用句点属性标识法,such as: object.attribute

file()后面会有介绍

####错误和异常

给代码添加错误检测及异常处理,需要将他们封装在try-except语句中,try之后的代码组,是需要管理的代码,expect 之后的代码组,是要处理的错误代码

异常类型描述
NameError尝试访问一个没有申明的变量
ZeroDivisionError除数为0
SyntaxError语法错误
IndexError索引超出序列范围
KeyError请求一个不存在的字典关键字
IOError输入输出错误(比如你要读的文件不存在)
AttributeError尝试访问未知的对象属性
ValueError传给函数的参数类型不正确,比如给int()函数传入字符串形
try:
<语句>        #运行别的代码
except <名字>:
<语句>        #如果在try部份引发了'name'异常
except <名字>,<数据>:
<语句>        #如果引发了'name'异常,获得附加的数据
else:
<语句>        #如果没有异常发生
finally:
<语句>

####函数

Python中的函数使用小括号()调用,函数在调用之前必须先定义,如果函数中没有return语句,就会返回None对象.

如何定义函数

定义一个函数的语法由def关键字及紧随其后的函数名再加上该函数需要的几个参数组成

def function_name([arguments]):
    "optional documentation string"
    function_suite
默认参数

函数的参数可以有一个默认值,如果提供有默认值,在函数定义中,参数以赋值语句的形式提供,当安徽省农户调用时如果没有提供这个参数,它就取这个值做为默认值.

>>> def foo(debug=True):
...     if debug:
...         print 'in debug mode'
...     else:
...         print 'done'
...         
>>> foo()
in debug mode
>>> foo(False)
done

####类

类是面向对象编程的核心,它扮演相关数据及逻辑的容器角色.它们提供了创建"真实"对象(也就是实例)的蓝图

如何定义类

使用class关键字定义类,可以提供一个可选的父类或者说基类;如果没有合适的基类,那就使用object作为基类,class行之后是可选的文档字符串,静态成员定义,及方法定义.

class ClassName(base_class[es]):
    "optional documentaion string"
    static_member_declarations
    method_declarations
>>> class FooClass(object):
...     version = 0.1
...     def __init__(self,nm='xiaoxiao'):
#nm:默认参数
...         self.name = nm
...         print "Created a class instance for", nm
...     def showname(self):
...         print "Your name is", self.name
...         print "My name is", self.__class__.__name__
...     def showver(self):
...         print self.version
...     def addMe2Me(self, x):
...         return x + x
如何创建类实例
>>> fool = FooClass()
Created a class instance for xiaoxiao

上面输出信息正是自动调用__init__()方法的结果.当一个实例被创建,init()就会被自动调用.不管这个__init__()是自定义的还是默认的.

创建一个类实例就像调用一个函数,它们都是可调用对象.类实例使用同样的函数运算符调用一个函数或方法.

>>> fool.name
'xiaoxiao'
>>> fool.showname
<bound method FooClass.showname of <__console__.FooClass object at 0x283f090>>
>>> fool.showname()
Your name is xiaoxiao
My name is FooClass
>>> fool.version
0.1
>>> fool.showver
<bound method FooClass.showver of <__console__.FooClass object at 0x283f090>>
>>> fool.showver()
0.1
>>> fool.addMe2Me(4)
8
>>> fool.addMe2Me('xiao')
'xiaoxiao'

在showname()方法中,显示self._class_.__name__变量的值.对于一个实例来说,这个变量表示实例化它的类的名字.

####模块

如何导入模块
import module_name
如何访问一个模块函数或访问一个模块变量

一旦导入完成,一个模块的属性(函数和变量)可以通过.句点属性标识法访问.

module.function()
moudule.variable

####实用的函数

函数描述
dir([obj])显示对象的属性,如果没有提供参数,则显示全局变量的名字
help(obj)显示帮助信息
int(obj)将一个对象转化为整数
len(obj)返回对象的长度
open(file_name,mode)以mode(‘r’=读,‘w’=写)的方式打开文件
range([[start,]stop[,step])返回一个整数列表.起始值为start,结束值为stop-1;start默认值为0,step默认值为1
raw_input(str)等待用户输入一个字符串,可以提供一个可选的参数str用作提示信息
str(obj)将一个对象转化为字符串
type(obj)返回对象的类型
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值