变量命名方式
变量命名时需注意:
- 尽量建名知意
- 不能与系统当中已有的命令或者关键字相同
- 不能以数字开头
- 组成:字母数字,下划线。 例:firest_name、FirstName
变量类别:
#str 字符串
name = 'hanmeimei'
In [8]: type(name)
Out[8]: str
#int 整型
age = 18
In [9]: type(age)
Out[9]: int
#bool True False 波尔值
In [11]: gender = True
In [12]: type(gender)
Out[12]: bool
#float 浮点数
In [13]: hight = 172.5
In [14]: wight = 120.3
In [15]: type(hight)
Out[15]: float
#######
result = height * weight 乘积
result = result - 100 result=上面result 的值-100
In [16]: result = wight*hight
In [17]: result
Out[17]: 20751.75
In [21]: result = wight - 100
In [22]: result
Out[22]: 20.299999999999997
练习:
写脚本执行以下内容
"""
- 输入学生姓名;
- 依次输入学生的三门科目成绩;
- 计算该学生的平均成绩, 并打印;
- 平均成绩保留一位小数点;
- 计算该学生语文成绩占总成绩的百分之多少?并打印。eg: 78%;
"""
name = input('Student Name:')
Chinese = float(input('Chinese:'))
Math = float(input('Math:')) 直接转换为浮点数
English = float(input('English:'))
#SumScore
SumScore = Chinese + Math + English
#AvgScore
AvgScore = SumScore / 3
#ChinesePercent
ChinesePercent = (Chinese / SumScore) * 100
print('%s avgscore is %.1f' %(name,AvgScore)) 保留一位小数
print('ChinesePercent is %.2f%%' %(ChinesePercent)) 保留两位小数
结果:
python2中存在long类型,意为长整型:
python3中就没有了:
dir 可以查看这个变量所有的用法。
例如:
center可以使值处于中间,并定义两边的内容
类别的转换
>>> a = 1
>>> type(a)
<class 'int'>
>>>
>>> float(a) 转换为浮点型
1.0
>>>
>>> b = 2.3
>>> int(b) 转换为整型
2
>>>
>>> str(b)
'2.3'
>>> String = 'westos'
>>> float(String)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'westos'
##波尔值
为0或者空为 false 其他都为真:
>>> bool(a)
True
>>> bool(b)
True
>>> bool(0)
False
>>> bool(23.123)
True
>>> name = 'westos'
>>> bool(name)
True
>>> name = ''
>>> bool(name)
False