幫助你快速入門的python知識(shí)點(diǎn)
時(shí)間:
伯超1226由 分享
幫助你快速入門的python知識(shí)點(diǎn)
下面是小編為大家精心收集整理的有關(guān)于Python的一些學(xué)習(xí)知識(shí)點(diǎn),希望能夠幫助到大家。如果你喜歡記得分享給身邊的朋友哦!學(xué)習(xí)的知識(shí)點(diǎn)如下:
1、 整型int與浮點(diǎn)型float:可以進(jìn)行基本的運(yùn)算 如5*7=35 、7/2=3.5、7%3=1等 一些相關(guān)的數(shù)學(xué)函數(shù)類似于sin之類都在math模塊中
a=[1,Ture,’ab’]
a+[“Hello”]
a+[false]
a+[false]
print(len(a))
print(a[1:3])
print(a[0:3:2])
print(a[::-1])
a+a
2、復(fù)數(shù)計(jì)算與邏輯值:復(fù)數(shù)的與或非()相關(guān)的都可以很快捷的運(yùn)算出結(jié)果 邏輯值如1>2為false、 bool(999)為true
3、 字符串的相關(guān)操作:+連接、 *復(fù)制、len長(zhǎng)度、[start:end:step]用來(lái)提取一部分和以及一些相關(guān)高級(jí)操作 如下:
#字符串操作
a,b=’abc’,’xzy’
print(‘a’ in a)
print(ord(a[0]))
print(chr(65))
print(r’學(xué)習(xí)啦’)
print(‘u123’ )
4、.列表與元組:列表可以增加、刪除、替換和重排的作用和一些切片拆分的操作 如下:
#List列表
a=[1,2,3,4]
b = a
b[1] = Ture
print(a)
#列表組的基本操作 # + * len()[] in
a=[1,2,3]
a+[4]
a*2
len(a)
2 in a
#列表元素的高級(jí)操作
mylist=[1,2,3,4,5]
mylist[1:4]
mylist[1:4]
mylist[2:5]
mylist[-3::-1]
mylist[::2]
#切片
s='abcdefg12345'
print(s[3:9])
print(s[5:])
print(s[-1:-6:-1])
print(s[:10:2])
#拆分
t='Mike and Tom'
print(t.split(' '))
5、range函數(shù):是連續(xù)序列生成器
#range函數(shù)
list(range(10))
list(range(5,10))
range(0,10)
tuple(range(10))
6、集合set:集合是不重復(fù)元素的無(wú)序組合、用set可以創(chuàng)建空集也可用set從其他序列轉(zhuǎn)換生成集合 如下
#set集合
#不重復(fù)元素的無(wú)序組合
a=[1,2,3,4,3,2,1]
b=set(a)
print(a)
print(b)
#upper/lower/swapcase修改大小寫
print(t.upper())
print(t.lower())
print(t.swapcase())
7、字典dict:是通過key值來(lái)索引values元素 如下
mydict={1:'Mon','linel':3332}
mydict['Mon']=3
'linel' in mydict
mydict.keys()
mydict.values()
mydict.items()
8、運(yùn)算表達(dá)式,函數(shù)調(diào)用如 import math /n math.sqrt 和賦值 如a=3 是講3賦值給a這個(gè)邏輯
9、if條件語(yǔ)句:包含elif或多條elif語(yǔ)句和一條else語(yǔ)句組成 while語(yǔ)句是條件循環(huán)語(yǔ)句 其中break語(yǔ)句是直接跳出循環(huán) 如下
#條件if
#elif<邏輯條件>:可以多個(gè)elif
a=12
if a>10:
print("Great!")
elif a>6:
print("Middle!")
else:
print("Low!")
#while循環(huán)
numbers=[12,37,5,42,8,3]
even = []
odd = []
while len(numbers) > 0:
number = numbers.pop()
if(number % 2 == 0):
even.append(number)
else:
odd.append(number)
print('even:',even)
print('odd:',odd)
10、函數(shù)function :定義函數(shù)為def語(yǔ)句 調(diào)用函數(shù)為<函數(shù)名>(<參數(shù)>) 相關(guān)例子如下:
def sum_list(alist): #定義一個(gè)帶參數(shù)的函數(shù)
sum_temp = 0
for i in alist:
sum_temp += i
return sum_temp #函數(shù)返回值
print(sum_list) #查看函數(shù)對(duì)象sum_List
my_list = [23,45,67,89,100] #調(diào)用函數(shù),講返回值賦值給my_sum
my_sum = sum_list(my_list)
print("sum of my List;%d" % (my_sum,))
def func(n):
total = 1
for i in range(1, n+1):
total = total+1
return total
def sum(n):
total = 0
for i in range(1,n + 1):
total += func(i)
print(sum)
sum(3)
def func_test(key1,key2,key3=23):
print("k1=%s,k2=%s,k3=%s" % (key1,key2,key3))
print("====fun_test")
func_test('v1','v2')
func_test('ab','cd',768)
func_test(key2='kk',key1='k')
11、參數(shù) 及位置參數(shù)
#參數(shù)的默認(rèn)值
def thank_you(name='everyone'):
print('You are doing good work ,%s!' %name)
thank_you()
thank_you('李四')
#位置參數(shù)
def desc_person(first_name,last_name,age):
print("First name: %s" % first_name.title())
print("Last name: %s" % last_name.title())
print("Age: %d" % age)
desc_person('brain','kernighan',30)
desc_person(age=20,first_name='zhang',last_name='hai')
#混合位置和關(guān)鍵字參數(shù)
def desc_person(first_name,last_name,age=None,favorite_language=None):
print("First name: %s" % first_name.title())
print("Last name: %s" % last_name.title())
if age:
print("Age :%d" % age)
if favorite_language:
print("Favorite language : %s" % favorite_language)
desc_person('brian','kernighan',favorite_language='C')
desc_person('ken','thompson',age=22)
#接受任意數(shù)量的參數(shù)
def example_function(num_1,num_2,*nums):
sum = num_1+num_2
#Then add any other numbers that were sent.
for num in nums:
sum = sum + num
# Print the results.
print("The sum of your numbersis %d." % sum)
example_function(1,2)
example_function(1,2,3)
example_function(1,2,3,4)
example_function(1,2,3,4,5)
12、map函數(shù):需要對(duì)列表中每個(gè)元素做一個(gè)相同的處理,得到新列表
#map
def add(a,b):
return a + b
lst = [1,2,3,4,5]
print(map (add,lst,lst))
print(list(map(add,lst,lst)))
#filter
def is_even(x):
return x % 2 == 0
lst = [1,2,3,4,5]
print(list(filter(is_even,lst)))
#reduce函數(shù)對(duì)參數(shù)進(jìn)行累積
from functools import reduce
def myadd(x , y):
return x + y
lst = [1,2,3,4,5]
sum = reduce(myadd,lst)
print(sum)
13、匿名函數(shù)lambda:可以返回一個(gè)匿名函數(shù) 表達(dá)式為:lambda<參數(shù)表>:<表達(dá)式>
#lambda函數(shù)(匿名函數(shù))
answer = lambda x:x**2
print(answer(5))
#map(),filter() reduce()結(jié)合lambda表達(dá)式
print(list(map( lambda x: x+x, [y for y in range(10)])))
print(list(map( lambda a, b: a+b,[x for x in range(10)],[y for y in range(10)])))
print(list(filter( lambda a: a & 1 ==0 , [x for x in range(10)])))
print(reduce(lambda x,y : x*y , [a for a in range(1,10)]))
14、time()函數(shù)
#獲取當(dāng)前的時(shí)間戳
time.time()
localtime = time.localtime(time.time())
print("本地時(shí)間為:",localtime)
#格式化時(shí)間
localtime = time.asctime(time.localtime(time.time()))
print("本地時(shí)間為:",localtime)
print(time.s)
15、面向?qū)ο?br /> #力
class Force:
def __init__(self, x, y): #x,y方向分量
self.fx, self.fy =x,y
def show(self): #打印出力的值
print("Force<%s,%s>" % (self.fx, self.fy))
def add(self,force2): #與另一個(gè)力合成
x = self.fx + force2.fx
y = self.fy + force2.fy
return Force(x,y)
#類定義中的特殊方法
def __str__(self):
return 'Force<%r, %r>' % (self.x, self.y)
def __mul__(sel,n):
x, y = self.x * n, self.y *n
return Force(x,y)
def __add__(self, other):
x ,y = self.x + other.x, self.y + other.y
return Force(x, y)
def __eq__(self, other):
return(self.x == other.x) and (self.y == other.y)
def __repr__(self):
return 'Force({0.x!r},{0.y!r})'.format(self)
#生成一個(gè)力對(duì)象
f1 = Force(0,1)
f1.show()
#生成另一個(gè)力對(duì)象
f2 = Force(3,4)
#合成為新的力
f3 = f1.add(f2)
f3.show()
class Student:
def __init__(self, name, grade):
self.name, self.grade = name, grade
#內(nèi)置sort函數(shù)只引用<比較符來(lái)判斷前后
def __lt__(self, other):
#成績(jī)比other高的,排在他前面
return self.grade > other.grade
#Student的易讀字符串表示
def __str__(self):
return "(%s,%d)" % (self.name, self.grade)
#Student的正式字符串表示,我們讓它跟易讀表示相同
__repr__=__str__
#構(gòu)造一個(gè)Python list對(duì)象
s = list()
#添加到student對(duì)象到list中
s.append(Student("Jack",80))
s.append(Student("Jane",75))
s.append(Student("Smith",82))
s.append(Student("Cook",90))
s.append(Student("Tom",70))
print("Original:", s)
#對(duì)list進(jìn)行排序,注意這是內(nèi)置sort方法
s.sort()
#查看結(jié)果,已經(jīng)按照成績(jī)排好序
print("Sorted:",s)
class Car:
def __init__(self, name):
self.name = name;
self.remain_mile = 0
def fill_fule(self, miles):
self.remain_mile = miles
def run(self, miles):
print (self.name,end=':')
if self.remain_mile >= miles:
self.remain_mile -= miles
print("run %d
miles!" % (miles,))
else:
print("fuel out!")
class GasCar(Car):
def fill_fuel(self,gas): #加汽油gas升
self.remain_mile = gas * 6.0 #每升跑6英里
class ElecCar(Car):
def fill_fuel(self, power): #充電power度
self.remain_mile = power * 3.0 #每度電3英里
gcar=GasCar("BMW")
gcar.fill_fuel(50.0)
gcar.run(200.0)
ecar=ElecCar("Tesla")
ecar.fill_fuel(60.0)
ecar.run(200.0)
try:
print('try...')
r = 10 / 'xyz'
print('result:',r)
except TypeError as e:
print('TypeError:',e)
except ZeroDivisionError as e:
print('no error!')
else:
print('no error!')
finally:
print('finally...')
print('END')