python学习笔记(一)基本数据类型

来源:互联网 发布:mysql golang 编辑:程序博客网 时间:2024/05/04 07:17

1. 用内建函数 id()可以查看每个对象的内存地址,即身份。

>>> id(3)140574872>>> id(3.222222)140612356>>> id(3.0)140612356
2. 使用type()能够查看对象的类型。<type ‘int’>,说明 3 是整数类型(Interger);<type ‘float’>则告诉我们那个对象是浮点型(Floating point real number)。与 id()的结果类似,type()得到的结果也是只读的。

>>> type(3)<type 'int'>>>> type(3.0)<type 'float'>>>> type(3.222222)<type 'float'>
3.常用数学函数和运算优先级

>>> import math
>>> math.pi3.141592653589793

这个模块都能做哪些事情呢?可以用下面的方法看到:

>>> dir(math)['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

Python 是一个非常周到的姑娘,她早就提供了一个命令,让我们来查看每个函数的使用方法。

>>> help(math.pow)

在交互模式下输入上面的指令,然后回车,看到下面的信息:

Help on built-in function pow in module math:pow(...)    pow(x, y)    Return x**y (x to the power of y).
>>> math.sqrt(9)3.0>>> math.floor(3.14)3.0>>> math.floor(3.92)3.0>>> math.fabs(-2)    # 等价于 abs(-2)2.0>>> abs(-2)2>>> math.fmod(5,3)    # 等价于 5%32.0>>> 5%32

4. 字符串

不过在写这个功能前,要了解两个函数:raw_input 和 print

这两个都是 Python 的内建函数(built-in function)。关于 Python 的内建函数,下面这个表格都列出来了。所谓内建函数,就是能够在 Python 中直接调用,不需要做其它的操作。

Built-in Functions

abs()divmod()input()open()staticmethod()all()enumerate()int()ord()str()any()eval()isinstance()pow()sum()basestring()execfile()issubclass()print()super()bin()file()iter()property()tuple()bool()filter()len()range()type()bytearray()float()list()raw_input()unichr()callable()format()locals()reduce()unicode()chr()frozenset()long()reload()vars()classmethod()getattr()map()repr()xrange()cmp()globals()max()reversed()zip()compile()hasattr()memoryview()round()import()complex()hash()min()set()apply()delattr()help()next()setattr()buffer()dict()hex()object()slice()coerce()dir()id()oct()sorted()intern()

这些内建函数,怎么才能知道哪个函数怎么用,是干什么用的呢?

不知道你是否还记得我在前面使用过的方法,这里再进行演示,这种方法是学习 Python 的法宝。

>>> help(raw_input)
5.Python 中如何避免中文是乱码

Python 中如何避免中文是乱码

这个问题是一个具有很强操作性的问题。我这里有一个经验总结,分享一下,供参考:

首先,提倡使用 utf-8 编码方案,因为它跨平台不错。

经验一:在开头声明:

# -*- coding: utf-8 -*-

有朋友问我-*-有什么作用,那个就是为了好看,爱美之心人皆有,更何况程序员?当然,也可以写成:

# coding:utf-8

经验二:遇到字符(节)串,立刻转化为 unicode,不要用 str(),直接使用 unicode()

unicode_str = unicode('中文', encoding='utf-8')print unicode_str.encode('utf-8')

经验三:如果对文件操作,打开文件的时候,最好用 codecs.open,替代 open(这个后面会讲到,先放在这里)

import codecscodecs.open('filename', encoding='utf8')
原创粉丝点击