200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > python学习笔记(一)基本数据类型

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

时间:2019-06-21 23:54:17

相关推荐

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

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

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

不知道你是否还记得我在前面使用过的方法,这里再进行演示,这种方法是学习 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')

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。