python 基本语法
1. 变量
1.1 定义变量
# 定义变量
a = 10
b = "hello"
print(a)
print(b)
1.2 变量的命名规则
- 变量名由字母、数字和下划线组成,不能以数字开头。
- 变量名不能包含空格,可以使用下划线来连接多个单词。
- 变量名区分大小写。
- 变量名不能使用Python中的关键字,如
class、if等。
1.3 变量的类型
Python中变量的类型不需要提前声明,可以随时改变变量的类型。
# 定义变量
a = 10
print(type(a)) # <class 'int'>
a = "hello"
print(type(a)) # <class 'str'>
2. 数据类型
2.1 整数类型
a = 10
print(type(a)) # <class 'int'>
2.2 浮点类型
b = 9.44
print(type(b)) # <class 'float'>
2.3 字符串类型
c = "hello"
print(type(c)) # <class 'str'>
2.4 布尔类型
d = True
print(type(d)) # <class 'bool'>
2.5 列表类型
e = [1, 2, 3]
print(type(e)) # <class 'list'>
2.6 元组类型
f = (4, 5, 6)
print(type(f)) # <class 'tuple'>
2.7 字典类型
g = {"name": "zhangsan", "age": 18}
print(type(g)) # <class 'dict'>
2.8 集合类型
h = {1, 2, 3}
print(type(h)) # <class 'set'>
2.9 类型转换
# 类型转换
a = str(10)
b = int("9")
c = float(9.44)
print(type(a)) # <class 'str'>
print(type(b)) # <class 'int'>
print(type(c)) # <class 'float'>
3. 运算符
3.1 算术运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
| + | 加法 - 两个对象相加 | a + b 将得到 30 |
| - | 减法 - 左操作数减去右操作数 | a - b 将得到 -10 |
| * | 乘法 - 两个数相乘的结果 | a * b 将得到 200 |
| / | 除法 - 分子除以分母 | b / a 将得到 2.0 |
| % | 取模 - 返回除法的余数 |
4. 条件语句
4.1 if语句
# if语句
a = 10
b = 20
if a > b:
print("a大于b")
else:
print("a小于等于b")
4.2 elif语句
# elif语句
a = 10
b = 20
c = 30
if a > c:
print("a大于c")
elif b > c:
print("b大于c")
else:
print("a、b均不大于c")
4.3 else语句
# else语句
a = 10
b = 20
if a > b:
print("a大于b")
else:
print("a小于等于b")
5. 循环语句
5.1 while循环
# while循环
count = 0
while count < 9:
print(count)
count += 1
5.2 for循环
# for循环
for i in range(10):
print(i)
if i == 5:
break
elif i == 7:
continue
print("i:", i)
6. 函数
6.1 定义函数
def 函数名(参数):
函数体
return 返回值
# return 语句可以返回函数调用
# return 语句也可以省略,此时函数调用返回None
# return语句可以返回多个值
# 空函数
def my_empty():
pass
# 无返回值
def my_print(name):
print('Hello', name)
# 有返回值
def my_sum(x, y):
s = x + y
print('s-->', s)
return s
# 不定长参数
def my_variable(*params):
for p in params:
print(p)
# 匿名函数
my_sub = lambda x, y: x - y
7. 类和对象
7.1 定义类
class 类名:
属性
...
方法
...
class Cat:
# 属性
color = 'black'
# 构造方法
def __init__(self, name):
self.name = name
# 自定义方法
def eat(self, food):
self.food = food
print(self.name, '正在吃'+food)
7.2 创建对象
cat = Cat('Tom')
print(cat.name) # Tom
print(cat.color) # black
7.3 调用方法
cat.eat('fish') # Tom正在吃fish
7.4 继承
class Dog(Cat):
def __init__(self, name):
super().__init__(name)
self.color = 'white'
print('Dog的构造方法')
print('name:', self.name)
print('color:', self.color)
def run(self):
print(self.name, '正在跑')
super().run()
print('Dog的run方法')
print('name:', self.name)
print('color:', self.color)
8.错误和异常
8.1 错误
# 语法错误
print('Hello World')
# NameError: name 'a' is not defined
print(a)
# TypeError: must be str, not int
print('Hello', 2020)
8.2 异常
1.常规异常 try: 可能出现异常的代码 except: 更改异常
2.指定异常 try: 异常代码 except ...as e: 更改 else: 没出现异常 finally: 有无异常都输出
try:
print(a)
except NameError as e:
print(e)
finally:
print("执行完成")