Python学习笔记1:Python起步

1.程序输出:

和C中printf很像:
>>> print "%s is number %d." % ("Python", 1)
Python is number 1.
将输出重定向到系统标准错误:
>>> import sys
>>> print >> sys.stderr, 'fatal error.'
fatal error.
将输出重定向到一个文件:
>>> logfile = open('./out.log', 'a')
>>> print >> logfile, 'hello world'
>>> logfile.close()

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

>>> user = raw_input('Enter your name:')
Enter your name:chenjianfei
>>> passwd = raw_input('Enter your password:')
Enter your password:123456
内建函数int()可将数字字符串转化为int:
>>> num = raw_input('Input a num:')
Input a num:100
>>> print '2*num = %d' % num*2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
>>> print '2*num = %d' % (int(num)*2)
2*num = 200
从交互式解释器中获取帮助:
>>>help(raw_input)

3.注释

# 后面是注释

文档字符串注释:可以在模块,类,或者函数的开始添加一个字符串,起到在线文档的作用.
def foo():
	"This is a doc string."
	return True;

4.运算符

+ - 

/ 传统除法(地板除)
// 浮点除法(四舍五入)
% 取余
** 乘方(优先级最高)

比较运算符:
< <= > >= == != <>

逻辑运算符:
and or not
注意下面是合法的:
>>> 3 < 4 < 5
True
>>> 3 < 4 and 4 < 5
True

5.变量和赋值:

Python中变量名规则和C一样.python是动态类型语言,也就是说不需要预先声明变量的类型.变量的类型和值在赋值的被初始化.
>>> count = 0
>>> miles = 10.5
>>> name = 'bob'
>>> kilometers = miles*1.609
增量赋值:
+= *= ...
python不支持++和--

6.数字

五种基本类型:
int 有符号整数:-234, 0x80, -0x80
long 长整数:-234L, 0x888L
bool 布尔类值:True(1), False(0)
float 浮点值:3.1415, -4.2E-10, 4.2e10
complex 复数:3+10j, -123-838.33J
从长远来看int和long将会无缝结合.在Python2.3以后再也不会报整型溢出的错误,结果会自动转化长整型.所有L后缀可有可无.

7.字符串:

Python使用成对的单引号或是双引号,三引号可以用来包含特殊字符.使用[]和[ : ]得到子字符串.[ index : count]
字符串有其特有的索引规则:第一个索引号是0,最后一个是-1.
加号(+)用来字符串连接运算.乘号(*)用于字符串的重复.
>>> pystr = 'Python'
>>> iscool = 'is cool!'
>>> pystr[0]
'P'
>>> pystr[2:5]
'tho'
>>> iscool
'is cool!'
>>> iscool[:2]
'is'
>>> iscool[3:]
'cool!'
>>> iscool[-1]
'!'
>>> pystr + iscool
'Pythonis cool!'
>>> pystr + ' ' + iscool
'Python is cool!'
>>> pystr * 2
'PythonPython'
>>> '-' * 20
'--------------------'
>>> pystr = '''python 
... is cool'''
>>> pystr
'python \n is cool'
>>> print pystr
python 
... is cool
>>> 

8.列表和元组

列表元素用[]包裹,元组元素用()包裹.
列表元素的个数和元素的值都可以改变.
元组可以看成是只读的列表.通过切片运算([], [:])可以得到子集.
列表操作:
>>> aList = [1, 2, 3, 4]
>>> aList
[1, 2, 3, 4]
>>> aList[0]
1
>>> aList[2:]
[3, 4]
>>> aList[:3]
[1, 2, 3]
>>> aList[1] = 5
>>> aList
[1, 5, 3, 4]
元组操作:
>>> aTuple = ('chenjianfei', 25, 170, 'hello')
>>> aTuple
('chenjianfei', 25, 170, 'hello')
>>> aTuple[:3]
('chenjianfei', 25, 170)
>>> aTuple[1] = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

9.字典

字典是Python中的映射数据类型.类似Perl中的关联数组和哈希表,有(key-value)对构成.用大括号{}包括.
>>> aDict = {'host': 'localhost'}
>>> aDict
{'host': 'localhost'}
>>> aDict['port'] = 8080
>>> aDict
{'host': 'localhost', 'port': 8080}
>>> aDict.keys()
['host', 'port']
>>> aDict['host']
'localhost'
>>> for key in aDict:
...     print key, aDict[key]
... 
host localhost
port 8080
>>> aDict['host'] = 33
>>> aDict
{'host': 33, 'port': 8080}

10.代码块和缩进对齐

代码块通过缩进对齐表达代码逻辑而不是使用大括号。

11.if语句

if expression:
	if_suite
如果expression的值是True或是非零,则代码组if_suite被执行。否则不执行。
代码组是Python中的术语,它由一条或是多条语句组成,表示一个子代码块。
if语句的形式还有两种:
if expression:
	if_suite
else:
	else_suite

if expression:
	if_suite
elif expression2:
	elif_suite
else:
	else_suite

12.while语句

while expression:
	while_suite

13.for语句和range()内建函数

Python中的for循环和传统的for循环(计数器循环)不一样,它更像shell中的foreach。
>>> for x in [1, 2, 3, 4]:
...     print x
... 
1
2
3
4
>>> for x in [1, 2, 3, 4]:
...     print x,
... 
1 2 3 4
>>> 
在print后面加逗号,表示打印之后不换行,只加一个空格。
>>> print 'We are the %s who say %s' % \
... ('knights', ('Ni!' + ' ')*4)
We are the knights who say Ni! Ni! Ni! Ni! 
>>> 
range()内建函数:
>>> for x in range(3):
...     print x
... 
0
1
2
>>> 
对字符串来说:
>>> foo = 'abc'
>>> for c in foo:
...     print c
... 
a
b
c
range()经常和len()函数一起用于字符串索引。在这里我们要显示每一个元素及其索引值:
>>> foo = 'abc'
>>> for x in range(len(foo)):
...     print foo[x], '(%d)' % x
... 
a (0)
b (1)
c (2)
>>> 
enumerate()函数可以更好的实现这个功能:
>>> for i, ch in enumerate(foo):
...     print ch, '(%d)' % i
... 
a (0)
b (1)
c (2)


14.列表解析

你可以在一行中用一个for循环将所有值放到一个列表中:
>>> squared = [x **2 for x in range(4)]
>>> for i in squared:
...     print i
... 
0
1
4
9
>>> 
列表解析还能做更复杂的事,比如挑选出符合要求的值放入列表:
>>> sqd = [x ** 2 for x in range(8) if not x%2]
>>> for i in sqd:
...     print i
... 
0
4
16
36
>>> 

15.文件和内建函数open(),file()

如何打开文件:
handle = open(file_name, access_mode='r')
其中:file_name表示文件名称;access_mode可以是r(read),w(write),a(append)。还有一些特殊的,比如‘+’表示读写,‘b’表示二进制访问。如果未提供access_mode表示读取。
open成功之后,我们就可以通过handle去操作文件了。文件方法属性必须通过句点属性标识法访问:
>>> filename = raw_input('Enter the file name:')
Enter the file name:tmp.txt
>>> fileobj = open(filename, 'r')
>>> for eachline in fileobj:
...     print eachline,
... 
1 hello
2 world
3 !
>>> fileobj.close()
上面的例子适用于文件大小适中的文件。
file()内建函数的功能等于open().不过file()函数的名字更像一个工厂函数,类似于int()生成整数对象,dict()函数生成字典对象。


16.错误和异常:

编译时会检查语法错误,不过 Python 也允许在程序运行时检测错误。当检测到一个错误,Python 解释器就引发一个异常, 并显示异常的详细信息。程序员可以根据这些信息迅速定位问题并进行调试, 并找出处理错误的办法。
try-except语句:
try:
	fileobj = open(filename, 'r')
	for eachline in fileobj:
		print eachline,
	fileobj.close()
except IOError, e:
	print 'file open error:', e
我们也可以用raise语句故意引发一个异常。


17.函数

def func_name([arguments]):
	"optional documentation string."
	func_suite
例子:
>>> def addMe2Me(x):
...     "apply + operation to argument"
...     return (x+x)
... 
>>> addMe2Me('abc')
'abcabc'
>>> addMe2Me(12)
24
>>> addMe2Me([10, 'chen'])
[10, 'chen', 10, 'chen']
>>> 
默认参数:
>>> def foo(debug=True):
...     "determine if in debug mode with default argument"
...     if debug:
...             print 'In debug mode.'
...     print 'done'
... 
>>> foo()
In debug mode.
done
>>> foo(True)
In debug mode.
done
>>> foo(False)
done
>>> 

18.类class

Python并不强求你以面向对象的方式编程。定义类:
class ClassName(base_class[es]):
	"optional documentation string"
	static_member_declarations
	method_declarations
base_class是可选的父类或是基类,可以是多个。class行之后是可选的文档字符串,静态成员定义,及方法定义。
例子:
class FooClass(object): 
	"""my very first class: FooClass""" 
	version = 0.1 # class (data) attribute 
	def __init__(self, nm='John Doe'): 
		"""constructor""" 
		self.name = nm # class instance (data) attribute 
		print 'Created a class instance for', nm 
	def showname(self): 
		"""display instance attribute and class name""" 
		print 'Your name is', self.name 
		print 'My name is', self.__class__.__name__ 
	def showver(self): 
		"""display class(static) attribute""" 
		print self.version # references FooClass.version 
	def addMe2Me(self, x): # does not use 'self' 
		"""apply + operation to argument""" 
		return x + x 
在上面的例子中,我们定义了一个静态变量version,它将被所有的实例和四个方法共享。
当一个类实例被创建的时候,__init__()方法会自动执行,在类实例创建完毕后执行,类似于构建函数。__init__() 可以被当成构建函数, 不过不象其它语言中的构建函数, 它并不创建实例--它仅仅是你的对象创建后执行的第一个方法。它的目的是执行一些该对象的必要的初始化工作。通过创建自己的 __init__() 方法, 你可以覆盖默认的 __init__()方法(默认的方法什么也不做),从而能够修饰刚刚创建的对象。
如何创建类实例:
>>> foo1 = FooClass()
Created a class instance for John Doe
>>> foo1.showname()
Your name is John Doe
My name is FooClass
>>> 

19.模块

Python源文件的名字*.py,模块的名字就是不带.py后缀的文件名。一个模块创建之后,你可以在另一模块中使用import导入到这个模块来使用。
一旦import成功,就可以通过句点属性表示法访问。
import module_name
module_name.variable
module_name.func_name()
例子:
>>> import sys
>>> sys.stdout.write("hello world.\n")
hello world.
>>> sys.platform
'linux2'
>>> sys.version
'2.6.6 (r266:84292, Feb 22 2013, 00:00:18) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)]'
>>> 

PEP(Python Enhancement Proposal)Python增强提案。具体请看:http://www.python.org/dev/peps/

20.常用的函数

函数 描述
dir([obj]) 显示对象的属性,如果没有提供参数, 则显示全局变量的名字
help([obj]) 以一种整齐美观的形式 显示对象的文档字符串, 如果没有提供任何参数, 则会进入交互式帮助。
int(obj) 将一个对象转换为整数
len(obj) 返回对象的长度
open(fn, mode) 以 mode('r' = 读, 'w'= 写)方式打开一个文件名为 fn 的文件
range([[start,]stop[,step]) 返回一个整数列表。起始值为 start, 结束值为 stop - 1; start 默认值为 0, step默认值为1。
raw_input(str) 等待用户输入一个字符串, 可以提供一个可选的参数 str 用作提示信息。 
str(obj) 将一个对象转换为字符串
type(obj) 返回对象的类型(返回值本身是一个 type 对象!)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值