Simple Python Tutorial Study Notes

Source: Internet
Author: User

Http://www.bkjia.com/shouce/pythonjc/index.html help (sys) help (int) help (list) help (dict) help (str) help (file) sys module print sys. _ doc _ help (sys. exit) help (sys. stdin) help (sys. stdout) help (sys. stderr) 1. operators are usually combined from left to right, that is, operators with the same priority are calculated from left to right. For example, 2 + 3 + 4 is calculated as (2 + 3) + 4. Some operators such as the value assignment operator are combined from the right to the left, that is, a = B = c is processed as a = (B = c ). 2.-25.5% 2.25 = 1. 53. ** is a power operation. boolean (not, or, and) logic (&, |, ^ ,~) 4. output Variable area = 5 print 'area is ', arew.ea is 5 [automatically output 1 space] 5.if condintion1: func1elif condition2: func2else: func3 note: the if statement contains a colon at the end, which tells Python to follow a statement block. 6. guess = int (raw_input ('enter an integer: '). We provide a string for the built-in raw_input function, which is printed on the screen and waiting for user input. Once we enter something and press the Enter key, the function returns the input. The raw_input function is a string. We use int to convert the string to an integer and store it in the variable guess. 7. True, False, and None cannot start with lowercase letters. 8. # whilewhile condtion1: func1else: func2 # forfor I in range (): func1else: func2 Note: else clauses can be used without comments #9. range (begin, end, step) ranges extend to end with step, but it does not contain end. 10. [Python's for loop is simpler, clearer, and less error-prone .] In C/C ++, if you want to write for (int I = 0; I <5; I ++), use Python, you can write for I in range (0, 5 ). 11. def sayHello (): print 'Hello world! 'Sayhello () 12. global x, y, z13.print 'zhanghe '* 514. if a function has many parameters and you only want to specify a part of them, you can assign values to these parameters by name. This is called a key parameter. We use the name (keyword) instead of specifying the real parameter for the function (the method we used previously. Func (50, c = 100) first according to the key parameters, in Order 15. Unless you provide your own return statement, each function contains a return None statement at the end. 16. The pass statement indicates an empty statement block in Python. 17. The document string is a multi-line string. Its first line starts with an uppercase letter and ends with a full stop. The second line is empty, and the detailed description starts from the third line. We strongly recommend that you follow this Convention when using document strings in your functions. 18. each Python module has its _ name __. if it is '_ main _', this indicates that this module is run independently by users and can be properly operated. 19. Use the built-in dir function to list the identifier defined by the module. Identifiers include functions, classes, and variables. >>> Import sys >>> dir (sys) # get list of attributes for sys module >>> dir () # get list of attributes for current module >>> a = 5 # create a new variable 'A' >>> dir () >>> del a # delete/remove a name >>> dir () 20. list # Filename: using_list.pyshoplist = ['apple', 'mango', 'carrot', 'bana'] print 'I hava', len (shoplist), 'items to purchase. 'print 'these items are: ', # Notice that comma at end of the linefor item in Shoplist: print item, # These items are: apple mango carrot banana print '\ nI also have to buy rice. 'shoplist. append ('Rice ') print 'my shopping list is now', shoplist # My shopping list is now ['apple', 'mango', 'carrot', 'Banana ', 'Rice '] print' I will sort my list now 'shoplist. sort () print 'sorted shopping list is ', shoplist print 'the first item I will buy is', shoplist [0] olditem = shoplist [0] del shopl Ist [0] print 'I bought the', olditemprint 'my shopping list is right ', shoplist21. we use a comma at the end of the print statement to remove the line break automatically printed by each print statement. 22. tuples are very similar to lists, except that tuples and strings are immutable and you cannot modify them. # Filename: using_tuple.pyzoo = ('Wolf ', 'elephant', 'penguin') print 'number of animals in the zoo is', len (zoo) new_zoo = ('monkey ', 'dolfen', zoo) print 'number of animals in the new zoo is ', len (new_zoo) print 'All animals in new zoo are ', new_zooprint 'animals brought from old zoo are ', new_zoo [2] print 'last animal brought from old zoo is', new_zoo [2] [2] output: number of animals in the zoo is 3 Number of Imals in the new zoo is 3All animals in new zoo are ('monkey', 'dolfen', ('Wolf ', 'elephant', 'penguin ')) animals brought from old zoo are ('Wolf ', 'elephant', 'penguin ') last animal brought from old zoo is penguin if you want a tuples containing project 2, you must be followed by a comma in the first (unique) project, you should specify singleton = (2 ,). 23. the most common usage of tuples is to use them in the print statement age = 22 name = 'swaroop 'print' % s is % d years old '% (name, age) print 'Why is % s playing with that python? '% Name24. the dictionary is an instance/object key-value pair of the dict class. In the dictionary, mark: d = {key1: value1, key2: value2} in this way }. Note that their key/value pairs are separated by colons, and each pair is separated by commas, all of which are included in curly brackets. Remember that key/value pairs in the dictionary have no order. If you want a specific sequence, you should sort them before use. # Filename: using_dict.py # 'AB' is short for 'A' ddress 'B' ook AB = {'swaroop ': 'swaroopch @ byteofpython.info', 'Larry ': 'Larry @ eall.org ', 'matsumo': 'matz @ ruby-lang.org', 'spammer ': 'spammer @ hotmail.com' # The last para has no ', '} print "Swaroop's address is % s" % AB ['swaroop'] # Adding a key/value pair Rab ['guid'] = 'guido @ python.org '# Deleting key/value pairdel AB ['pemer'] print '\ nThere are % D contacts in the address-book \ n' % len (AB) for name, address in AB. items (): print 'Contact % s at % s' % (name, address) if 'guide' in AB: # OR AB. has_key ('guido ') print "\ nGuido's address is % s" % AB ['guido'] 25. the sequence list, tuples, and strings are all sequences, but what are sequences? Why are they so special? The two main features of a sequence are index operators and slice operators. The magic of sequences is that you can access tuples, lists, and strings in the same way. # Filename: seq. py shoplist = ['apple', 'mango', 'carrot', 'bana'] # Indexing or 'subnotification' operationprint 'item 0 is ', shoplist [0] print 'item 1 is ', shoplist [1] print 'item 2 is', shoplist [2] print 'item 3 is ', shoplist [3] print 'item-1 is ', shoplist [-1] print 'item-2 is ', shoplist [-2] # Slicing on a listprint 'item 1 to 3 is ', shoplist [] print 'item 2 to end is', shoplist [2:] print 'item 1 To-1 is ', shoplist [1:-1] [notice that] print 'item start to end is', shoplist [:] [notice that] # Slicing on a stringname = 'swaroop 'print 'characters 1 to 3 is ', name [] print 'characters 2 to end is', name [2:] print 'characters 1 to-1 is ', name [1:-1] print 'characters start to end is', name [:] output: item 0 is appleItem 1 is mangoItem 2 is carrotItem 3 is bananaItem-1 is bananaItem-2 is carrotIte M 1 to 3 is ['mango', 'carrot'] Item 2 to end is ['carrot', 'bana'] Item 1 to-1 is ['mango ', 'carrot'] [notice that] Item start to end is ['apple', 'mango', 'carrot ', 'bana'] [notice that] characters 1 to 3 is wacharacters 2 to end is aroopcharacters 1 to-1 is waroocharacters start to end is swaroop 26. reference when you create an object and assign it a variable, this variable only refers to that object, rather than the object itself! That is to say, the variable name points to the memory of the object stored in your computer. This is called name-to-object binding. # Filename: reference. pyprint 'simple Assignment 'shoplist = ['apple', 'mango', 'carrot ', 'bana'] mylist = shoplist # mylist is just another name pointing to the same object del shoplist [0] print 'shoplist is ', shoplistprint 'mylist is ', mylist # notice that both shoplist and mylist both print the same list without # the 'apple' confirming that they point to the same object print 'Copy by making a full slice 'Mylist = shoplist [:] # make a copy by doing a full slicedel mylist [0] print 'shoplist is ', shoplistprint 'mylist is ', mylist # notice that now the two lists are different 27. string str class #! /Usr/bin/python # Filename: str_methods.py name = 'swaroop '# This is a string object if name. startswith ('swa'): print 'this string starts with "Swa" 'If 'A' in name: print 'this string contains the string "a" 'If name. find ('war ')! =-1: print 'this string contains the string "war" 'delimiter = '_ * _' mylist = ['Brazil ', 'Russia', 'India ', 'China'] print delimiter. join (mylist) 28. class methods have only one special difference from common functions-they must have an additional first parameter name, but you do not assign a value to this parameter when calling this method, python provides this value. This special variable refers to the object itself, which is named self by convention. The 29 _ init ____ init _ method runs immediately when an object of the class is created. This method can be used to initialize your object. Note that the start and end of the name are double underscores. 30. There are two types of classes and object variables: class variables and object variables. They are differentiated based on whether the class or object has this variable. Class variables are shared by all objects (instances) of a class. Only one class variable is copied, so when an object changes the class variable, this change will be reflected on all other instances. The object variables are owned by each object/instance of the class. Therefore, each object has its own copy of this domain, that is, they are not shared. In different instances of the same class, although the object variables have the same name, however, they are unrelated. # Filename: objvar. py class Person: ''' Represents a person. '''population = 0 def _ init _ (self, name): ''' Initializes the person's data. '''self. name = name print '(Initializing % s)' % self. name # When this person is created, he/she # adds to the population Person. population + = 1 def _ del _ (self): ''' I am dying ''' print '% s says bye. '% self. name Person. population-= 1 if Person. population = 0: print' I am the last one 'else: print 'There are still % d people left. '% Person. population def sayHi (self): ''' Greeting by the person. really, that's all it does. '''print 'Hi, my name is % s. '% self. name def howation (self): ''' Prints the current population. '''if Person. population = 1: print 'I am the only person here. 'else: print 'We have % d persons here. '% Person. population swaroop = Person ('swaroop ') swar Oop. sayHi () swaroop. howMany () kalam = Person ('Abdul kalam') Kalam. sayHi () kalam. howoop () swaroop. sayHi () swaroop. howMany () kalam. _ del _ () swaroop. _ del _ () 31. python requirements: All class members (including data members) in Python are public and all methods are valid. Only one exception: if you use a data member name with a double-underline prefix such as _ privatevar, the Python name management system will effectively use it as a private variable. Common practice: if a variable only needs to be used in a class or object, it should be prefixed with a single underscore. Other names are public and can be used by other classes/objects. Remember that this is just a convention and is not required by Python (different from the double-underline prefix ). 32. A child type can be replaced with the parent type in any case where the parent type is required, that is, the object can be considered as an instance of the parent class. This phenomenon is called polymorphism. 33. Python does not automatically call the constructor of the basic class. You have to call it in person. We call the child-type tell method instead of the tell method of the SchoolMember class. It can be understood that Python always finds the corresponding type of method first, which is the case in this example. If it cannot find the corresponding method in the export class, it will start to search for it one by one in the basic class. 34. Python provides a standard module called pickle. Using it, You can store any Python object in a file, and then you can retrieve it completely. This is called a persistent storage object. Another module, cPickle, has the same functions as the pickle module, except that it is written in C, so it is much faster (1000 times faster than pickle ). You can use either of them, and here we will use the cPickle module. Remember, we can refer to the two modules as pickle modules. Dump () Storage load () Fetch storage 35. To handle exceptions, we can use the try... handle T statement to handle exceptions. We place the common statements in the try-block and the error handling statement in the Fail T-block. Each try clause must have at least one correlated limit t clause. You can also associate the try... catch Block with an else clause. When no exception occurs, the else clause is executed. 36. You can use the raise statement to raise an exception. You must also specify the error/Exception name and the exception object triggered with the exception. The errors or exceptions you can cause should be a direct or indirect export class of the Error or Exception class. 37. try... finally what should you do if you want to close the file in case of exceptions? This can be done using finally blocks. Note: In a try block, you can use the limit t clause and the finally block. If you want to use them at the same time, you need to embed one into another. Import timetime. sleep (2) 38. when running the program, press Ctrl-c to interrupt/cancel the program. 39. sys module 40. OS module this module contains common operating system functions. This module is especially important if you want your program to be unrelated to the platform. That is, it allows a program to run in Linux and Windows without any changes or any problems. In one example, OS. sep can replace the path delimiter specified by the operating system. >>> Import OS >>> str = 'path' >>> print OS. getenv (str) C: \ Windows \ system32; C: \ Windows \ System32 \ Wbem; C: \ Windows \ System32 \ WindowsPowerShell \ v1.0 \; E: \ Java \ jdk1.6.0 _ 21 \ bin; C: \ Python27; the following lists some useful parts in the OS module. Most of them are simple and clear. The OS. name string indicates the platform you are using. For example, for Windows, it is 'nt ', and for Linux/Unix users, it is 'posix '. The OS. getcwd () function obtains the current working directory, that is, the directory path of the current Python script. The OS. getenv () and OS. putenv () functions are used to read and set environment variables respectively. OS. listdir () returns all files and directory names in the specified directory. The OS. remove () function is used to delete an object. The OS. system () function is used to run shell commands. The OS. linesep string specifies the row Terminator used by the current platform. For example, in Windows, '\ r \ n' is used, in Linux,' \ n' is used, and in Mac, '\ R' is used '. The OS. path. split () function returns the directory name and file name of a path. The OS. path. isfile () and OS. path. isdir () functions verify whether the given path is a file or a directory. Similarly, the OS. path. existe () function is used to check whether the GIVEN path actually exists. 41. Special method: __init _ (self,...) This method is called before the newly created object happens to be returned for use. _ Del _ (self) is called just before the object is deleted. _ Str _ (self) is called when we use the print statement for the object or str. _ Lt _ (self, other) is called when the less than operator (<) is used. Similarly, all operators (+,>, and so on) have special methods. _ Getitem _ (self, key) is called when the x [key] index operator is used. _ Len _ (self) is called when the built-in len () function is used for the sequence object. 42. Single statement block: [butuijianshiyong if True: print 'yes' 43. The list is integrated with the list to export a new list from an existing list. For example, you have a list of numbers, and you want to get a corresponding list, so that all the numbers greater than 2 are two times the original number. For such applications, list synthesis is the most ideal method. 44. Receiving tuples and lists in a function when you want the function to receive parameters in the form of tuples or dictionaries, there is a special method, which uses the * And ** prefixes respectively. This method is particularly useful when the function needs to obtain variable numbers of parameters. There is a * prefix before the variable. All redundant function parameters are prefixed with ** before the variable as a tuples. All redundant function parameters are used as Dictionary key/value pairs. 45. lambda statements are used to create new function objects and return them at runtime. Lambda requires a parameter followed by a single expression as the function body, and the value of the expression is returned by the newly created function. The exec Statement of 46.exe c is used to execute Python statements stored in strings or files. Exec 'print "Hello World" 'eval statement eval statement is used to calculate the valid Python expression stored in the string. The eval ('2 * 3') assert statement is used to declare that a condition is true. For example, if you are very sure that a list you are using has at least one element, and you want to test this and cause an error when it is not true, the assert statement is an ideal statement applied in this case. The repr function is used to obtain the standard string representation of an object. Backquotes (also called Conversion characters) can accomplish the same function. The repr function and backquotes are used to obtain the printable representation of an object. You can define the _ repr _ method of the class to control the content returned when your object is called by the repr function. >>> I = [] >>> I. append ('item') >>> 'I' "['item']" >>> repr (I) "['item']" [QQ: 1203456195] [blog address: http://www.cnblogs.com/cheesezh]

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.