1.格式化 %s,%d,%f
name = '测试'
age = 18
salary = 100.98
my_format = '他的名字是%s,他的年龄是%d,他的工资是%f' %(name,age,salary)
print(my_format)
2.列表 append、insert、pop
classmates = ['hh','ee','uu']
classmates.append('kk')
classmates.insert(1,'mm')
classmates.pop(0)
print(classmates)
3.元组 一旦初始化就不能修改
classmates = ('aa','ss','dd')
4.条件判断 if
s = input('birth:')
birth = int(s)
if birth < 2000:
print('00前')
else:
print('00后')
5.循环 for in、 while
range()可以生成一个整数序列,再通过list()函数可以转换为list
sum = 0
for x in range(101):
sum = sum +x
print(sum)
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
6.dict 字典
d = {'Michael':95,'Bob':75,'Tracy':85}
d.pop('Tracy')
print(d)
set 一组key的组合,但不存储value,key不能重复
s = set([1,2,3])
s.add(4)
s.remove(1)
print(s)
7.定义函数 def
数据类型检查可以用内置函数isinstance()实现
def my_abs(x):
if x >= 0:
return x
else:
return -x
print(my_abs(-99))
import math
def move(x,y,step,angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx,ny
x, y = move(100,100,60,math.pi / 6)
print(x,y)
必选参数在前,默认参数在后,默认参数必须指向不变对象
可选参数:*nums 表示把nums这个list的所有元素作为可变参数传进去
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n*n
return sum
print(calc(1,2))
关键字参数:**kw 在调用该函数时,可以只传入必选参数,也可以传入任意个数的关键字参数
def person(name,age,**kw):
print('name',name,'age',age,'other',kw)
person('Michael',30,city='Beijing')
8.递归函数
def fact(n):
if n == 1:
return 1
return n*fact(n-1)
print(fact(5))
9.切片 Slice
L[0:3] 表示从索引0开始取,直到索引3为止,但不包括索引3,即索引0,1,2,正好3个元素。
如果第一个索引是0,还可以省略 L[:3]
L[-1]取倒数第一个元素 L[-2:]
10.迭代 for in
for x,y in [(1,1),(2,4),(3,9)]:
print(x,y)
列表生成式
list(range(1,11))