# -*- coding: utf-8 -*-
# @Time : 2020/1/21 23:04
# @Author : Fighter.Lu
list 集合
simple=["one","two","three"] #list集合存储数据
#print(len(simple)) #list集合数据个数
#print(simple[0]) #list集合中的第一个元素u
#print(simple[-1]) #list集合中最后一个元素
#simple.append('four') #list集合在尾部添加元素
#simple.insert('3','ten')
#simple.pop() #从尾部删除元素
#simple.pop(1) #从指定位置删除元素
#simple[3]='ten' 根据下标替换list集合中元素
#s=['one','two',['three','four'],'five',simple] #list集合插入另一个list集合
#print(s)
tuple 元组
#classmate=('one','two') #初始化元素
#print(classmate)
# classmates这个tuple不能变了,它也没有append(),insert()这样的方法。其他获取元素的方法和list是一样的,你可以正常地使用classmates[0],classmates[-1],但不能赋值成另外的元素。
#定义空元组
#student=()
#print(student)
#student=(1)
#student[0]='zhangsan'
#print(student)
# L = [
# ['Apple', 'Google', 'Microsoft'],
# ['Java', 'Python', 'Ruby', 'PHP'],
# ['Adam', 'Bart', 'Lisa']
# ]
# print(L[0][0])
# print(L[1][1])
# print(L[2][2]) BMI = 體重(公斤) / 身高2(厘米)
#用户输入
#s=input("请输入您的年龄:")
#字符串转整型
# s=int(s)
# if s>20:
# print("你是成年人")
# elif s<5:
# print(s)
# else:
# print()
#print(55/(1.67*1.67))
#for遍历
# for i in simple:
#
# print('集合:'+i)
# sum=0
#range 函数生成序列 range(4)=[0,1,2,3]
# for i in range(101):
# sum=sum+i;
# print(sum)
#dict 字典 类似于 map
scoreinfo={'zhangsan':11,'lisi':33,'wangwu':33}
#scoreinfo["zhaoliu"]=22 #如果key存在就修改 如果不存在就添加
#print(scoreinfo['zhangsan']) #查询某个key -value
#scoreinfo['zhangsan']=111 #修改字典scoreinfo中key为zhangsan的value
#print(scoreinfo['zhangsan'])
#print('zhangsan' in scoreinfo) #判断key在字典中是否存在
#通过dict提供的get方法判断key在集合中是否存在;不存在就返回none,否则返回value
#print(scoreinfo.get("zhangsan"))
#通过下标判断
#print(scoreinfo.get("lisi",-1))
#删除字典scoreinfo中key
#scoreinfo.pop("zhangsan")
#print(scoreinfo)
#list和字典dict区别
#1、dict查询和插入的速度很快,不会随着key增多而变慢;需要占用大量的内存,内存浪费严重
#2、list查询和插入随着集合的元素添加,速度变慢
set和dict很相似,也是一组key的集合,只存储key的集合,set不能重复key存在,如果有重复set会自动剔除
id=set([1,2,3])
print(id)
# id=set({1,11,2,3,2,3})
# print(id)
# {3, 1, 2, 11}
#set 无序集合
#set 添加元素
id.add(4)
print(id)
#如果id重复添加相同的key,不会有效果
# id
{3, 1, 2, 11}
# id.add(3)
# id
#{3, 1, 2, 11}
#id 删除key
#id.remove(3)
#>>> id
#{1, 2, 11}
#查询两个set集合重叠的元素
# id
# {1, 2, 11}
# >>> id1
# {3, 4, 5, 6, 7}
# >>> id &id1
# set()
# >>> id |id1
# {1, 2, 3, 4, 5, 6, 7, 11}
# >>>
#dict 和set区别
没有存储对应的value,但是,set的原理和dict一样,所以,同样不可以放入可变对象,因为无法判断两个可变对象是否相等,也就无法保证set内部“不会有重复元素”。试试把list放入set,看看是否会报错
函数
1、调用函数
1.1 取正数:abs(x) 注意:只能有一个参数,且参数只能是数字
1.2 取最大值:max(x,y,z) 可以多个参数,参数只能是数字
1.3 整型转化:int('222') 只能是数字类型的字符串 (int('222')、str(22))
>>> 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、自定义函数
使用关键字:def
例如:
def my_abs(x):
if x >= 0:
return x
else:
return -x
调用函数:my_abs(-1) 结果:1
注意:函数中如果没有加返回值,显示none
3、空函数:当你暂时不知道写什么,可以在函数里面加入pass,这表示什么都不做
def show():
pass
注意:如果函数里面没东西,同时也没加pass,会报错
4、参数检查
调用函数时,如果参数个数不对,Python解释器会自动检查出来,并抛出TypeError
:
>> my_abs(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: my_abs() takes 1 positional argument but 2 were given
参数类型不对:
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x
my_abs('A') :参数类型错误,就会出错误
>> my_abs('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in my_abs
TypeError: bad operand type
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
r=move(100,100,60,math.pi/6)
print(r)
(151.96152422706632, 70.0)
原来返回值是一个tuple!但是,在语法上,返回一个tuple可以省略括号,而多个变量可以同时接收一个tuple,按位置赋给对应的值,所以,Python的函数返回多值其实就是返回一个tuple,但写起来更方便。
请定义一个函数quadratic(a, b, c)
,接收3个参数,返回一元二次方程 ax^2+bx+c=0ax2+bx+c=0 的两个解。
def quadratic(a,b,c):
return (-b+math.sqrt(b*b-4*a*c))/2*a,(-b-math.sqrt(b*b-4*a*c))/2*a
6、函数的参数
6.1、位置参数:传入有且只有一个参数
计算x平方的函数
def power(x):
return x*x
power(2)
传入多个参数:立方、平方 x^2 x^3
def power(x,n):
s=1
while n>0:
n=n-1
s=s*x
return s
power(2,3)
6.2、默认参数:函数中有默认参数,传入的参数被函数中默认的参数代替
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
power(5) -->25
power(5,3) -->25
6.3、可变参数:参数可传入集合、元组
计算a^2+b^2+c^3
def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
>>> calc([1, 2, 3])
14
>>> calc((1, 3, 5, 7))
84
>>> calc(1, 2, 3)
14
>>> calc(1, 3, 5, 7)
84
定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*
号。在函数内部,参数numbers
接收到的是一个tuple,因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数:
>>> calc(1, 2)
5
>>> calc()
0
如果已经有一个list或者tuple,要调用一个可变参数怎么办?可以这样做:
>>> nums = [1, 2, 3]
>>> calc(nums[0], nums[1], nums[2])
14
这种写法当然是可行的,问题是太繁琐,所以Python允许你在list或tuple前面加一个*
号,把list或tuple的元素变成可变参数传进去:
>>> nums = [1, 2, 3]
>>> calc(*nums)
14
关键字参数
在对用户注册的过程中,在对参数个数的控制情况下,传入多个属性值,就会用到字典
示例1:
def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)
>>> person('Michael', 30)
name: Michael age: 30 other: {}
>> person('Bob', 35, city='Beijing')
name: Bob age: 35 other: {'city': 'Beijing'}
>>> person('Adam', 45, gender='