1、进行数据类型转换
>>> int('123')
123
>>> int(12.34)
12
>>> float('12.34')
12.34
>>> str(1.23)
'1.23'
>>> str(100)
'100'
>>> bool(1)
True
>>> bool('')
False
2、定义函数
在Python中,定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回。
def myFun(x):
if x>3:
return x
elif x>1:
return 1
else :
return 0
3.定义空函数,使用pass关键字
def pop():
pass
4.类型判断
def my_abs(x):
if not isinstance(x, (int, float)): # 进行判断x的类型,是否属于int float
return '炸鸡'
if x >= 0:
return x
else:
return -x
5、#返回多个参数
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==",x," y==",y)
6、传递的参数可以是集合
def calc(x):
sum = 0
for n in x:
sum = sum + n * n
return sum
print(calc([1, 2, 3]))
print(calc((1, 3, 5, 7)))
7、设置可变参数
#进行设置可变参数,那么传递的参数就不用使用list进行表示
def calc(*x):
sum = 0
for n in x:
sum = sum + n * n
return sum
print(calc(1, 2, 3)) //这里减少了[...]
print(calc(1, 3, 5, 71, 3, 5, 7))
8、#这里的*kw表示的是可变参数
def person(name, age, *kw):
print('name:', name, 'age:', age, 'other:', kw)
person("嗯嗯呃",12,["eee",'eefv'])
person("嗯嗯呃",12,"eee",'efvf')
#这里的**kw表示的是键值对的形式
def person2(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)
person2("嗯嗯呃",12, gender='M', job='Engineer')
上面的写法可以进行简化
extra = {'city': 'Beijing', 'job': 'Engineer'}
person2('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}