Python's learning Experience

Source: Internet
Author: User
Tags local time mathematical functions set set

First of all, I am glad that I chose this personalized elective course, it may be that I personally think that the language is very special and wonderful, the teacher is very interesting, can let us better understand the real purpose of the Python course. In the course of learning Python this time, and you can also know and learn a lot of knowledge, the following is the summary of this course:

Python is an advanced dynamic, fully object-oriented language that is quick and easy. When running the program, for example, calculate the advanced arithmetic of the Pi class as long as the import Math math.sqrt () can easily calculate the pi, Python is similar to a supercomputer.

The learning points are as follows:

1, int and float float: can perform basic operations such as 5*7=35, 7/2=3.5, 7%3=1 and other related mathematical functions similar to sin and so on in the math module

A = [1,true, ' 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, complex numbers and logical values: complex numbers and or not () related can be very fast to calculate the results of logical values such as 1>2 false, BOOL (999) is true
3, the related operation of the string: + connection, * Copy, Len length, [Start:end:step] to extract part of and and some related advanced operations such as (including example):

#字符串操作a, B = ' abc ', ' XYZ ' Print (' A ' in a) ' Print (ord (a[0])) ' Print (' R ' South Academy ') print (' \u4e2d\u6587 ')


4. Lists and tuples: Lists can add, remove, replace, and rearrange actions and some slice split operations such as:

#List列表a =[1,2,3,4]b = ab[1] = Trueprint (a) #列表元组的基本操作 # +  *  len () [] Ina=[1,2,3]a+[4]a*2len (a) 2 in a# Advanced operations for list elements Mylist=[1,2,3,4,5]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 function: Continuous sequence generator

#range函数list (range) List (range (5,10)) range (0,10) tuple (range (10))

6, Set set: Set is an unordered combination of elements, set can be used to create an empty set or set from other sequence transformation to generate sets such as

#set集合 # unordered combination of non-repeating elements a=[1,2,3,4,3,2,1]b=set (a) print (a) print (b) #upper/lower/swapcase modify Case print (T.upper ()) Print ( T.lower ()) print (T.swapcase ())

7, Dictionary dict: is the key value to index the values of the elements such as

Mydict={1: ' Mon ', ' linel ': 3332}mydict[' mon ']=3 ' Linel ' in Mydictmydict.keys () mydict.values () Mydict.items ()

8, the expression of the operation, function calls such as import math/n math.sqrt and assignment, such as A=3 is to say 3 assignment to a This logic


9. If condition statement: contains elif or multiple elif statements and an else statement consisting of a while statement is a conditional loop statement where the break statement is directly out of the loop as

#条件if #elif< logical conditions;: can be multiple elifa=12if a>10:    print ("great!") Elif a>6:    print ("middle!") else:    print ("low!") #while循环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 function: Define the function for DEF statement call function for < function name > (< parameter >) related examples such as:

def sum_list (alist): #定义一个带参数的函数    sum_temp = 0 for    i in alist:        sum_temp + = i    return sum_temp #函数返回值print (s um_list)   #查看函数对象sum_Listmy_list = [23,45,67,89,100] #调用函数, the return value is assigned to My_summy_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

def sum (n): Total    = 0for 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. Parameters and Position parameters

#参数的默认值def thank_you (name= ' everyone '):    print (' You're doing good work,%s! '%name) thank_you () thank_you (' Zhang San ')

#位置参数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 "% of age) Desc_person (' brain ', ' Kernighan ', ') Desc_person (Age=20,first _name= ' Zhang ', last_name= ' Hai ')

#混合位置和关键字参数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)

#接受任意数量的参数def example_function (num_1,num_2,*nums):    sum = num_1+num_2        #Then Add any and numbers that were sent. For    num in nums:        sum = sum + num        # Print the results.        Print ("The sum of your numbers is%d." "% sum" example_function () example_function (all in All) example_function (1,2,3,4) Example_function (1,2,3,4,5)

12. Map function: You need to do the same for each element in the list, get a new list

#mapdef Add (A, B):    return a + Blst = [1,2,3,4,5]print (Map (add,lst,lst)) Print (List (map (add,lst,lst))) #filterdef Is_ Even (x):    return x% 2 = = 0lst = [1,2,3,4,5]print (list (filter (IS_EVEN,LST))) #reduce函数对参数进行累积from Functools Import Reducedef myadd (x, y):    return x + ylst = [1,2,3,4,5]sum = reduce (myadd,lst) print (sum)

13, anonymous function lambda: can return an anonymous function expression as:lambda< parameter table >:< expression >

#lambda函数 (anonymous function) answer = Lambda x:x**2print (Answer (5)) #map (), filter () reduce () in conjunction with the lambda expression print (list (map (lambda x:x+x , [y for y in Range])) Print (list (map (lambda A, b:a+b,[x for x in range)],[y for y in range))) Print (List (fil ter (lambda a:a & 1 ==0, [x for x in range])) print (Reduce (lambda x,y:x*y, [a For a in range (1,10)]))

14, Time () function

#获取当前的时间戳time. Time () localtime = Time.localtime (Time.time ()) print ("Local times:", localtime) #格式化时间localtime = Time.asctime (Time.localtime (Time.time ())) print ("local time:", localtime) print (TIME.S)

15. Object-Oriented

#力class Force:    def __init__ (self, x, y):  #x, y-direction component        self.fx, Self.fy =x,y    def Show (self): #打印出力的值        Print ("force<%s,%s>"% (self.fx, self.fy))    def Add (self,force2): #与另一个力合成        x = self.fx + force2.fx        y = s Elf.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 = s elf.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) #生成一个力对象f1 = Force (0,1) f1.show () # Generate another force object F2 = forces (3,4) #合成为新的力f3 = F1.add (F2) f3.show ()

Class Student:    def __init__ (self, name, grade):        self.name, Self.grade = name, Grade    #内置sort函数只引用 < Comparator to determine before and after    def __lt__ (self, Other):        #成绩比other高的, in front of him        return self.grade > Other.grade    # Student's easy-to-read string represents the    def __str__ (self):        return "(%s,%d)"% (Self.name, Self.grade)    #Student的正式字符串表示, We make it easy to read the same    __repr__=__str__    #构造一个Python List Object s = List () #添加到student对象到list中s. Append (Student ("Jack", 80) ) S.append ("Jane", Student) S.append (Student ("Smith", "the") S.append (Student ("Cook")) S.append (Student ("Tom", ) Print ("Original:", s) #对list进行排序, note that this is the built-in Sort method S.sort () #查看结果, which has been ordered by the score 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 = Ten/' 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 ')

The above is my knowledge of the course of Python summary and understanding, will learn more about this aspect of the relevant to enrich themselves.

Python's learning Experience

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.