python基础之数据类型及格式化输入输出

整型

>>> a = 1
>>> print(a)
1

查看变量的数据类型

>>> type(a)
<class 'int'>

浮点型

>>> b=1.2
>>> print(b)
1.2
>>> type(b)
<class 'float'>

字符串型

>>> c = westos
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'westos' is not defined
>>> c='westos'
>>> print(c)
westos
>>> type(c)
<class 'str'>

bool型(只有两个值:True False 非0即真)

注意:只有为空和“0”时为false

>>> a = 1
>>> bool(a)
True
>>> bool(0)片
False

####################
>>> bool(' ')
True
>>> bool('')
False
####################
>>> bool('redhat')
True
>>> bool(1234567)
True

数据类型的转换

>>> a = 1
>>> type(a)
<class 'int'>
>>> float(a)
1.0
>>> type(a)
<class 'int'>
>>> b=2,0
>>> print(b)
(2, 0)
>>> b=2.0
>>> int(b)
2

>>> c='linux'
>>> int(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'linux'

>>> c='123'
>>> int(c)
123
>>> b=345
>>> str(b)
'345'
>>> e=12.6
>>> str(e)
'12.6'
>>> a
1
>>> a
1

在内存中删除一个变量

>>> del a
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
defined

在这里插入图片描述

python的输入输出

python2.x
-input:只支持数值类型
-raw_input:支持数值类型和字符串类型

在这里插入图片描述
3.0版本以后不需要加raw_
在这里插入图片描述

输入密码不回显
import getpasswd ##导入python第三方模块库
在这里插入图片描述

%s:字符串 %d:整型
在这里插入图片描述
%f:代表浮点型
在这里插入图片描述

整型总占位,不够位数的前面补0
在这里插入图片描述

显示百分比
在这里插入图片描述

如果接收到的数值要进行比较的时候,一定要转换为同种数据类型

>>> age = raw_input('请输入年龄:')
请输入年龄:18
>>> age
'18'
>>> age > 19
True
>>> type(age)
<type 'str'>
>>> int(age)
18
>>> age > 19
True
>>> int(age)>19
False

练习:

#求平均成绩(python3解释器)

#- 输入学生姓名;
#- 依次输入学生的三门科目成绩;(语文 数学 英语)
#- 计算该学生的平均成绩, 并打印;
#- 平均成绩保留一位小数点;
#- 计算该学生语文成绩占总成绩的百分之多少?并打印。eg: 78%;

Name = (input('Name:'))
Chinese = float(input('Chenese Score:'))
Math = float(input('Math Score:'))
English = float(input('English Score:'))
sum = Chinese+Math+English
arv = sum/3
print('%s的平均成绩为%.1f' %(Name,arv))
ChinesePercent = (Chinese/sum)*100
print('ChinesePercent%.2f%%' %(ChinesePercent))

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44416500/article/details/88549431