变量与对象
Python中不能单独定义某个变量,变量必须依附于某个对象。 例:a=3
变量和对象建立起来的关系称为引用。
变量对调:
>>>a=3
>>>b=4
>>>a,b=b,a
同时给多个变量赋值
>>>x,y,z=1,2,3
一、整数、浮点数
查询是否是相同的对象,返回内存地址
>>>id(3)
2059594852720
>>>id(3.0)
2059599090416
内置除法函数
>>> divmod(5,2)
(2,1)
>>>5/2
2.5
>>>5//2
2
>>>5%2
1
转换成二进制来进行计算,进制转换导致的问题
>>>0.1+0.2
0.30000000000000004
>>>round(o.1+0.2,1)
o.3
>>>round(1.2345,3)
1.234
标准库中的math模块的使用
>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
>>> math.pi
3.141592653589793
>>> math.pow(2,3)
8.0
>>> help(math.pow)
Help on built-in function pow in module math:
pow(x, y, /)
Return x**y (x to the power of y).
>>> 2**3
8
python中的数据溢出问题,整数运算不会出现溢出,而浮点数会
>>> 2**1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
>>> 2**1000*0.1
1.0715086071862674e+300
>>> 2**10000*0.1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: int too large to convert to float
以计算合力大小为例的代码
#coding:utf-8
'''
my first program.
filename:force.py
'''
import math
f1=20
f2=10
alpha=math.pi/3
x_force=f1+f2*math.sin(alpha)
y_force=f2*math.cos(alpha)
force=math.sqrt(x_force*x_force+y_force**2)
print('The result is',round(force,2),'N')
二、字符串
字符和二进制数之间通过字符编码对应
>>> ord('t')
116
>>> bin(116)
'0b1110100'
定义
单引号或双引号包裹字符组成字符串
序列及其基本操作
序列:
基本操作:
(1)连接
(2)重复元素
>>> m="python"
>>> n="book"
>>> m+n
'pythonbook'
>>> m*3
'pythonpythonpython'
>>> 'p'in m
True
>>> 'a'in m
False
索引和切片
>>>r="abcdefgh"
>>>len(r)
11
>>>r[0:4:1]
abcd
>>>r[-8:-4:1]
abcd
>>>r[0:4:2]
ac
自左向右的第一个索引值为0
自右向左的第一个索引值为-1
两个内置函数print 和input
age=input(“your age is:”)
注意这里的age是字符串类型,如需要进行运算需要类型转换
字符串的常用属性和方法
在字符串中使用变量
(1)python3.6前用format()方法
full_name="{} {}".format(first_name,last_name)
注:在圆括号内列出要使用的变量,对于每个变量,都通过一对花括号来引用,按顺序将花括号替换为圆括号内列出的变量值
>>> "i like {0} and {1}".format("Java","Python")
'i like Java and Python'
(2)python3.6后f字符串
first_name="blake"
last_name="griffin"
full_name=f"{first_name} {last_name}"
print(full_name.title())
Blake Griffin
[Finished in 0.1s]
删除字符串空白
rstrip()方法 删除字符串末尾空白
lstrip()方法 删除字符串开头空白
strip()方法 删除字符串两边 空白