变量名只有在第一次出现才是定义变量(变量名再次出现,不是定义变量,而是直接使用之前定义的变量) 在 python 中,每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建 等号(=)用来给变量赋值 =左边是一个变量名 =右边是存储在变量中的值
在 python 中定义变量是不需要指定类型(在其他很多高级语言中都需要) 数据类型可以分为数字型和非数字型 (1)数字型 整型(int), 浮点型(float),布尔型(bool):真 True 非 0 数 ( 非 0 即真) (2)非数字型 字符串,列表,元组,字典
整型转换为浮点型
所谓输入,就是用代码获取用户通过键盘输入的信息 在 python 中可以使用 input 函数从键盘等待用户的输入,用户输入的任何内容 python 都认为是一个字符串 即以下的num,name和sums均为字符串
语法格式:
print ‘格式化字符串’ % 变量 1 print ‘格式化字符串’ % (变量 1,变量 2…)单注释 ctrl+/ 批量注释,选中需要进行注释的所有行 按 ctrl+/ 实现全部注释 ctrl+/ 批量取消注释,选中已经被注释的所有行 按 ctrl+/ 实现全部取消注释
块注释
""" a= 1 b =2.8 int (b) """input():接收任意数据类型 全部都以字符串对待
>>> input ('num: ') num: 2 '2' >>> import getpass >>> num = getpass.getpass('please input password: ') please input password: >>> num 'redhat'-input():只支持正确的数值类型 -raw_input():支持数值类型和字符串类型
[root@localhost opt]# python Python 2.7.5 (default, Aug 2 2016, 04:20:16) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> input ('Num:') Num:2 2 >>> input ('Num:') 正确的字符串都是可以的 Num:'redhat' 'redhat' >>> input ('Num:') Num:redhat 这里没有输入字符串错误的 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'redhat' is not defined >>> raw_input('Num:') 只支持字符串和数值 Num:redhat 'redhat' >>>求平均成绩(python3解释器) #- 输入学生姓名; #- 依次输入学生的三门科目成绩;(语文 数学 英语) #- 计算该学生的平均成绩, 并打印; #- 平均成绩保留一位小数点; #- 计算该学生语文成绩占总成绩的百分之多少?并打印。eg: 78%;
代码串
# _*_coding:utf-8_*_ name = input('please put your name: ') math = float(input('please put your math:')) chinese = float(input('please put your chinese grade: ')) english = float(input('please put you english grade: ')) pinjun=(math+chinese+english)/3 print('%s the pj grade %.1f' %(name,pinjun)) zhanbi = chinese/(math+chinese+english) print('the zb is %d%%' %(zhanbi * 100)) ~效果展示
[root@localhost mnt]# /usr/local/python3/bin/python3 chengji.py please put your name: lcc please put your math:98 please put your chinese grade: 89 please put you english grade: 99 lcc the pj grade 95.3 the zb is 31%