1.运算符
+、 -、 *、 /、 %(取余数)、 **(幂运算)、//(商取整)
2.循环
:后缩进是循环体
内置函数range(1,n,1) 表示的是步长为1,1到n-1。
3.判断(if / if-else/ if-elif-else)
if判断的条件可以连写。 例如:
x = 1
y = 2
z = 3
if x < y < z:
print("x is less than y, and y is less than z")
结果:
x is less than y, and y is less than z
4.def函数
函数默认参数
def sale_car2(price2, colour2='red', brand2='benci', is_second2=False):
print(
'price:', price2,
'colour:', colour2,
'brand:', brand2,
'is_second:', is_second2,
)
# 如果不写参数=? 默认按照定义函数内的参数顺序
sale_car2(10000, 'BMW')
sale_car2(10000, brand2='BMW')
结果:
price: 10000 colour: BMW brand: benci is_second: False
price: 10000 colour: red brand: BMW is_second: False
5.全局&局部变量
一般在函数体外定义的变量成为全局变量,在函数内部定义的变量称为局部变量。
全局变量所有作用域都可用,局部变量只能在本函数可用,在函数中优先使用局部变量。局部变量不能用在全局中。
在函数内部可以用global来定义全局变量
#局部变量与全局变量
def fun():
a = 10
print(a)
return a + 100 # 相当于输出
a = fun()
print(a)
# 函数优先使用局部变量
str = 'global'
def func1():
str = 'local'
print(str)
func1()
print(str)
结果:
10
110
local
global
其中函数内部的a是局部变量,外部的a为全局变量。
如果想在函数内使用全局变量,或改变全局变量的值
6.文件读写
text = 'This is my first test.\nThis is next line.'
print(text)
# w-write r-read
my_file = open('my_file.txt', 'w')
my_file.write(text)
# 打开的文件一定要关上,否则容易死机
my_file.close()
#文件内部追加内容
append_text = '\nThis is appended file.'
# a-append追加
my_file = open('my_file.txt', 'a')
my_file.write(append_text)
# 打开的文件一定要关上,否则容易死机
my_file.close()
read :全部输出
readline :逐行输出
readlines :全部输出放在一个list中
file = open('my_file.txt', 'r')
content = file.read()
print(content)
结果:
This is my first test.
This is next line.This is appended file.
This is appended file.
file = open('my_file.txt', 'r')
content = file.readline()
print(content)
结果:
This is my first test.
file = open('my_file.txt', 'r')
content = file.readlines()
print(content)
结果:
['This is my first test.\n', 'This is next line.This is appended file.\n', 'This is appended file.']
7.class类
在Python中,定义类是通过class
关键字,class
后面紧接着是类名,类名通常是大写开头的单词,紧接着是(object)
表示类的继承父类。通常,如果没有合适的继承类,就使用object
类,这是所有类最终都会继承的类。
创建实例是通过类名+()实现的,由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。通过定义一个特殊的__init__
方法,在创建实例的时候,就把类属性绑上去。
注意:特殊方法“__init__”前后分别有两个下划线!!!
__init__
方法的第一个参数永远是self
,表示创建的实例本身,有了__init__
方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__
方法匹配的参数。
class Calculator:
# name = 'One' # 类属性
# price = 18
def __init__(self, name, price, hight, width, weight):
self.name = name
self.price = price
self.hight = hight
self.width = width
self.weight = weight
def add(self, x, y): # 函数是类功能
print(self.name) # 通过self.使用类属性
result = x + y
print(result)
def minus(self, x, y):
result = x - y
print(result)
def times(self, x, y):
print(x*y)
def divide(self, x, y):
print(x/y)
# calu = Calculator()
# 用__init__的类实例化需要写入相应参数
calu = Calculator('Two', 50, 12, 18, 20)
print(calu.name)
calu.minus(20, 10)
结果:
Two
10