1. 基础语法
1.1 认识变量
变量是内存中的一块区域。对象赋值实际上是对象的引用。a=10
变量的命名: 变量名由字母,数字,下划线组成, 不能以数字开头。hello = 100, hello_world = 100, count2 =100, 1count=10(x)
Python中,变量定义时不需要指定类型的,当用变量的时候,必须要给这个变量赋值;
1.2 认识运算符
整数型:int; 布尔型:bool(true、false); 浮点数型:float(小数);复数:complex
- 整型数
打开docs 环境,输入cmd,然后输入python进入Python环境;
整数一般是10进制的,但是Python也支持八进制或十六进制来表示:
十进制转换成二进制bin(10)
十进制转换成八进制oct(10)
十进制转换成十六进制hex(10)
- 浮点数
3. 布尔值
type()查看变量类型
- 常见运算符
1)算数运算符:+,-,*,**, /, %, // **次方,%代表取余 //是整除
2)赋值运算符:=, +=, -=, /=, *=, %= =是赋值的意思;num+=1是num=1,num=num+1
3)关系运算符: >, >=, <, <=, !=, ====是判断是否相等,返回是bool类型的值
4)逻辑运算符:逻辑与and, 逻辑或or, 逻辑非not全真则真,一假则假; 全假则假,一真则真; 真是假,假是真
1.3 数据的输入和输出
- 用户输入(input)
默认输入的数据并不是整形,后面如果需要用到数据就需要对其转换使其成为需要的类型。
int()将输入的值转换为整型,float()将输入的值转换为浮点型,bool()将输入的值转换为布尔值
2.输出(print)
%表示占位符;
%s表示字符串;
%d表示整型数;
%f表示浮点数,%.2f表示小数点后2位;
%%表示字符%
format格式输出:(若要保留小数可使用上面的方法)
print(f"name:{name},age:{age},score:{score}")
**练习1:**编写程序,录入学生的姓名和三门科目的百分制成绩,计算该学生的总分和平均成绩。
输入姓名: 张三
输入语文成绩:
输入数学成绩:
输入英语成绩:
学生张三的总分为:,平均分为:
name=input("please input name: ")
chinese=int(input("please input chinese score: "))
math=int(input("please input math score: "))
english=int(input("please input english score: "))
print("name: %s\nchinese: %d\nmath: %d\nenglish: %d" %(name,chinese,math,english))
score=chinese+math+english
print("score: %d" %(score))
average=score/3
print("average: %.2f" %(average))
优化:
name = input("Please input student name:")
Chinese = int(input("Chinese score:"))
English = int(input("English score:"))
Math = int(input("Math score:"))
count = Chinese + Math + English
average = count/3
print(f'{name} total score is: {count}\naverage score is:{average}')
执行结果:
1.4 常用的函数
1). 标准类型函数(cmp, str和 type): 可以用于所有的标准类型。
2). 转换工厂函数(int, long, float, bool和 complex)
3). 功能函数(abs, divmod, pow和 round)
4). 进制转换函数(bin,hex,oct)
5). ASCII 转换函数(chr,ord)
abs求绝对值,pow求次方;round保留小数点后几位。
常用模块的导入:math ,random