1. 注释的三种形式
# print('hello world')
'''
print('hello world')
'''
"""
print('hello world')
"""
2. 基本数据类型
整形,浮点数,字符串,布尔值,空值,
print(type(20))
# 字符串
str1 = 'abc'
str2 = "abc"
str3 = '''abc'''
print(type(str1))
print(type(str2))
print(type(str3))
# 布尔值
print(type(True))
# 空值
print(type(None))
3. 变量
a = 1
print(a)
a = 'abc' # Python是弱类型语言
print(a)
4. 常量 Python 中没有真正的常量,只是按照编程习惯,把全部用大写字母表示的量作为常量,不去修改它
PI = 3.1415926
5. list
classmates = ['Michael','Bob','Tracy']
# 长度
len(classmates)
# 取值
classmates[0]
classmates[-1]
# 追加
classmates.append('adam')
# 插入元素
classmates.insert(2,'bob')
# 删除尾部元素
classmates.pop()
classmates.pop(2)
# 修改
classmates[1] = 'haha'
6. tuple 元组一旦初始化就不能修改
classmates = ('Michael','Bob','Tracy')
# 定义一个元素
t = (1,) # 不能 t = (1)
7. 条件判断
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
8. 循环
# for
names = ['Michael','Bob','Tracy']
for name in names:
print(name)
sum = 0
for x in range(101):
sum += x
print(sum)
# while
n = 1
while n <= 100:
print(n)
n = n + 1
print('END')
# break
n = 1
while n <= 100:
if n > 10:
break
print(n)
n = n + 1
print('END')
# continue
n = 0
while n < 10:
n += 1
if n % n == 0:
continue
print(n)
9. dict
d = {'Michael':95,'Bob':97}
# 取值
d['Bob']
# 添加
d['Adam'] = 79
# 判断 key 是否在 dict 中
print('Thomas' in d)
print(d.get('Thomas'),-1) # 判断 key 是否在 d中,不在就返回 -1
10. set 里面有重复的就会自动过滤掉,是无序无重复元素的集合
s = set([1,2,3])
# 添加
s.add(4)
# 删除
s.remove(4)
# 不可变对象和可变对象
# list 是可变对象
a = ['c','b','a']
a.sort()
# 可变对象
a = 'abc'
a1 = a.replace('a','A')
print(a) # abc
print(a1) # Abc
11. 函数
# 定义函数
def my_abs(x):
if not isinstance(x,(int,float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x
# 位置参数: 按照位置顺序依次给x ,n 赋值
def power(x,n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
# 默认参数
def enroll(name,gender,age = 6,city = 'beijing'):
print(name,gender,age,city)
'''
1.必选参数在前,默认参数在后
2.多个默认参数,不按顺序调用时,要把参数名写上 enroll('Bob','F',city='shangqiu')
3.默认参数必须指向不变对象
'''
# 可变参数 可变参数组成一个tuple
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
calc(1,2,3)
num = [1,2,3]
calc(*num)
# 关键字参数 可变参数组成一个dict
def person(name,age, **kv):
print('name',name,'age:',age,'other:',kv)
extra = {'city':'beijing','job':'Engineer'}
person('bob',25,**extra)
# 命名关键字参数
def person(name,age,*,city,job):
print(name,age,city,job)
12.高级特性
# 切片
L = range(100)
# 1:切片的起始位置,30切片的终止位置,4是切片的步长
for x in L[1:30:4]:
print(x)
print('ABCDEDF'[:3])
# 列表生成式
L = [x * x for x in range(1,11)]
for x in L:
print(x)
# 加入判断
[x * x for x in range(1,11) if x % 2 == 0]
# 双层循环
[m + n for m in 'ABC' for n in 'XYZ']