您的位置:首页 > 编程语言 > Python开发

Python3.运算符.数据类型转换

2017-09-11 23:27 399 查看

运算符

算数运算符



赋值运算符



复合赋值运算符



复合赋值运算注意点:

a+=b-c*d ---->>> a=a+b-c*d
a*=b-c/d ---->>> a=a*(b-c/d)


⚡ root@server129  ~  python
Python 2.7.5 (default, Nov  6 2016, 00:28:07)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=1
>>> b=2
>>> c=3
>>> a+=b-c
>>> a     #a=a+b-c
0
>>> a=1
>>> d=2
>>> a+=b-c/d
>>> a     #a=a+b-c/d=1+2-3/2=2(这里的3/2=1)
2
>>> a=1
>>> a*=b-c/d
>>> a    #a=a*(b-c/d)=1*(2-3/2)=1*(2-1)=1
1
>>>


取商和取余在现实生活中的小应用:



随机输入一个数,输出这个数字的位置,按照如上图的方式进项排列:

⚡ root@server129  ~/python  cat quyu.py
#!/usr/bin/env python
#encoding=utf-8
"""
file:${NAME}.py
author:Peter
time:${DATE} ${TIME}
describe:
输入一个数对其进行取余数和商,余数和商分别代表这个数所在的行和列。
"""
A=input("请输入一个数:")
B=A%3
C=A//3
print("数字%d的位置是:%d行%d列"%(A,C,B))
⚡ root@server129  ~/python  ./quyu.py
请输入一个数:32
数字32的位置是:10行2列
⚡ root@server129  ~/python  ./quyu.py
请输入一个数:78
数字78的位置是:26行0列


数据类型转换

常用的数据类型转换



? root@server129 ? ~/python ? ipython
Python 2.7.5 (default, Nov  6 2016, 00:28:07)
Type "copyright", "credits" or "license" for more information.

IPython 3.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [3]: a=raw_input()    #字符串类型输入25
25

In [4]: a
Out[4]: '25'

In [5]:  b=input()    #输入整形20
20

In [6]: b
Out[6]: 20

In [7]: c=a-b     #字符串a和整形b相减,自然会出现下面的报错
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-7e44b1e9d8e9> in <module>()
----> 1 c=a-b

TypeError: unsupported operand type(s) for -: 'str' and 'int'

In [8]: d=int(a)    #将字符串变量a转换成为整形变量d

In [9]: d
Out[9]: 25

In [11]: c=d-b   #这次相减没有报错,正确计算c=25-20=5的结果

In [12]: c
Out[12]: 5

In [16]: a=raw_input()
26

In [17]: a
Out[17]: '26'

In [18]: type(a)   #查看变量a的数据类型
Out[18]: str       #字符串型

In [19]: b=input()
78

In [20]: b
Out[20]: 78

In [21]: type(b)
Out[21]: int    #整形数据类型

In [23]: d=int(a)

In [24]: d
Out[24]: 26

In [25]: type(d)
Out[25]: int

In [26]: c=d-b

In [27]: c
Out[27]: -52

In [28]: e=input()
3.14

In [29]: e
Out[29]: 3.14

In [30]: type(e)
Out[30]: float

In [31]: f=c-e

In [32]: f
Out[32]: -55.14

In [33]:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: