python基础学习(1)

来源:互联网 发布:手机机顶盒遥控器软件 编辑:程序博客网 时间:2024/06/05 08:31

在python编程入门一书中的一些个人笔记

1. // 在python中表示整除
**>>>**3 // 2
1

2. 导入模块时,有两种导入方法
>>> import math
>>> from math import *

两种方式皆可导入math模块,但使用import math 方式更为安全,因为它不会覆盖任何既有的函数,from math import * 会覆盖现有与math函数中重名的函数
在第一种模块导入时候,使用模块内函数需要带上模块名,第二种则不需要。
在多人团队开发的时候,别用第二种,因为可能不同模块中可能会存在相同的函数名,使用第一种导入模块的时候,带上模块名的函数调用不会让程序出错,否则第二种同名函数会被覆盖

3.‘ ’ 和 ” ” 都可以表示字符串,一般 ‘ 不用shift按键,更为方便, “”” “””三引号表示的是多行字符串,且保留换行符,单引号和双引号嵌套可以实现特殊需求。

>>> a = “””hello
World
“””
>>> a
“hello\nWorld\n”
>>> print(“I’m student”)
I’m student
>>> print(‘She said “Yes!”’)
She said “Yes!”

4. 字符串拼接结果为另一字符串,因此可以在任何需要使用字符串的地方使用字符串拼接,例如:

>>> len(‘house’ + ‘boat’) * ‘12’
‘121212121212121212’

5. 获取帮助时,当导入模块后,可以使用dir(模块名) 方法显示此模块所有方法

>>> import math
>>> dir(math)
[‘_doc_‘, ‘_loader_‘, ‘_name_‘, ‘_package_‘, ‘_spec_‘, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atan2’, ‘atanh’, ‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘e’, ‘erf’, ‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’, ‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’, ‘gcd’, ‘hypot’, ‘inf’, ‘isclose’, ‘isfinite’, ‘isinf’, ‘isnan’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’, ‘log1p’, ‘log2’, ‘modf’, ‘nan’, ‘pi’, ‘pow’, ‘radians’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘tau’, ‘trunc’]

或者使用help( ) ,将显示所有模块清单,有关函数和关键字

>>> help(math)
Help on built-in module math:
NAME
math
DESCRIPTION
This module is always available. It provides access to the
mathematical functions defined by the C standard.
FUNCTIONS
acos(…)
acos(x)
Return the arc cosine (measured in radians) of x.
acosh(…)
acosh(x)
Return the inverse hyperbolic cosine of x.
asin(…)
asin(x)
Return the arc sine (measured in radians) of x.
–more—

或者打印函数文档的字符串:
>>> print(math . tanh . _ doc _)
tanh(x)
Return the hyperbolic tangent of x.

6. 圆整,round( ) 函数在python中作用是计算四舍五入,在python中round(8.5)结果为8,而round(7.5) 结果也为8

>>> round(8.5)
8
>>> round(7.5)
8

因为总是向上圆整带来的偏差可能导致计算的不准确,python中采用:将小数部分 . 5 的数字圆整到最接近的偶数(有时被称作银行家圆整)。
Python中常用的处理数字的方法有trunc( ) (直接割取整数部分);floor( ) (取不超过它的最大整数);ceil( ) (取大于它的最小整数)

7. 变量名只是引用,赋值也就是引用创建的对象,重新赋值只是改变变量名的引用对象,原有不在使用的对象将被回收删除,也印证了一句话:数字和字符串是不可变的。
多重赋值要保证一一对应
>>> x , y , z = 1 , ‘two’ , 3.0
>>> x , y , z
(1 , ‘two’ , 3.0)

多重赋值在变量交换值的时候能更为方便的进行简化代码
>>> a , b = 9 , 5
>>> a , b
(9, 5)
>>> a , b = b , a
>>> a , b
(5 , 9)

0 0