小白學python之練習記錄2

2021-10-08 14:56:47 字數 2846 閱讀 2435

本篇文章包含了python基礎的大部分練習,也是我學習python的練習記錄,我是小白,所以我更懂得小白該怎麼學習,勤加練習是成為大牛的必經之路,希望我的練習能對你學習python有所幫助

"""列表的排序"""

lst =[6

,2,7

,4,1

,3,5

]print

(sorted

(lst)

)#sorted 函式按照長短、大小、英文本母的順序給每個列表中的元素進行排序

print

(sorted

(lst,reverse=

true))

#使用預設引數reverse後列表可以按照逆序整理

"""列表解析式和普通寫法效率比較"""

import time

a =[

]t0 = time.clock(

)for i in

range(1

,20000):

print

(time.clock(

)- t0,

"seconds process time"

)t1 = time.clock(

)b =

[i for i in

range(1

,20000)]

print

(time.clock(

)- t1,

"seconds process time"

)"""列表推導式的理解"""

a =[i**

2for i in

range(1

,10)]

c =[j+

1for j in

range(1

,10)]

k =[n for n in

range(1

,10)if n %2==

0]z =[letter.lower(

)for letter in

'abcdefghigklmn'

]print

(a,c,k,z,sep=

"\n"

)#sep="\n"可使輸出的結果一次行多行顯示

"""字典的推導式必須滿足鍵——值兩個條件"""

d =g =

h =print

(d,g,h,sep=

"\n"

)""""顯示字母的位置,用到python中特有的函式enumerate"""

letters =

['a'

,'b'

,'c'

,'d'

,'e'

,'f'

,'g'

]for num,letter in

enumerate

(letters)

:print

(letter,

'is'

,num +1)

"""物件導向"""

#1class

cocacola

: formula =

['caffeine'

,'sugar'

,'water'

,'soda'

]def

__init__

(self)

:for element in self.formula:

print

('coke has {}!'

.format

(element)

)#format在括號內填入

defdrink

(self, how_much)

:if how_much ==

'a sip'

:print

('cool~'

)elif how_much ==

'whole bottle'

:print

('headache!'

)if __name__ ==

'__main__'

: ice_coke = cocacola(

) ice_coke.drink(

'a sip')#2

class

project

:def

__init__

(self,subject)

: self.subject=subject

class

teacher

:def

__init__

(self,name,subject)

: self.name=name

self.subject=subject

defcheck

(self,sub,stu)

:print

(stu.name,stu.grade,sub.subject)

class

student

:def

__init__

(self,name,grade)

: self.name=name

self.grade=grade

defwrite

(self)

: sub=project(

"數學"

) t = teacher(

"張三"

,"數學"

) t.check(sub,self)

if __name__ ==

'__main__'

: stu=student(

"里斯"

,"四年級"

) stu.write(

)

小白學python(2)之常見的Python函式

函式 描述abs x 返回x的絕對值 max x1,x2,返回數列中的最大值 min x1,x2,返回數列中的最小值 pow a,b 返回a的b次方的值,類似a b round x 返回與x的值最接近的整數,如果x與兩個整數接近程度相同,則返回偶數值 round x,n 同round x 只不過會保...

小白學python之使用 slots

本文以廖雪峰的官方 為參考來學習python的。其學習鏈結為廖雪峰小白學python教程。本文是學習到python的例項屬性和類屬性。參考鏈結廖雪峰python使用 slot 嘗試給例項繫結乙個屬性 class student object pass s student s.name michael...

小白學Python 之函式 二

定義乙個函式 defgetname name print 請叫我 format name return def getitem k b 0 for i in k b b i print b returnb 呼叫getname 小王 k 1,2,34,5,3,56,45,6,56,767,98 get...