Getting Started with Python (1)

Source: Internet
Author: User
Tags generator generator pear set set

Python is performed through the Python interpreter.

1. First Python program

Print "hello world" # Save As hello.py file

How does it work? Execute the Python hello.py execution at the command line.

2. Variables and arithmetic expressions

Principal = $ # Python is a weakly typed language, the variable declaration is not specified before the type rate = 0.5numyears = 5year = 1while year <= numyear S: #: generally represents the beginning of a new code block principal = Principal * (1 + rate) #python中一般以四个空格缩进来定义一个新代码块 print year, pri Ncipal # Use Print to output one line, use between multiple variables, separate year + = 1

Output variables can be formatted in Python

Print "%3d%0.2f"% (year, principal) print '%s '% "hello world"

%d represents the output integer,%s represents the output string, and%f represents the output floating-point number. you can also specify the width of the output variable

For example, 0.2f indicates that two decimal places are retained after the decimal point. %3d represents an integer width of 3, right-justified

3. Conditional Control Statements

A = 1b = 2if a < B:print "a < b" else:print "a > b" # Multiple branches are judged with if elif elseif suffix = = ". html": content = "text/html" elif suffix = = ". jpeg": content = "image/jpeg" elif suffix = = ". png": content = "image/png" Else:prin T "Unknown type" print content# uses in to determine that a value is contained in an object (string list Dictionary) str = "hello world" if "he" in str:has_he = Trueelse:h As_he = Falseprint has_he

4. Input and output of the file

f = Open ("1.txt") #打开一个文件, Returns a file object line = F.readline () #读取一行内容while line:print lines, #读取一行内容, which is used to remove the newline at the end, because print hits The default is to add a newline character at the end of line = F.readline () f.close () #关闭文件 # The process of traversing a collection of data is called an iteration, and Python provides a for iteration, so to speak, any object that can be iterated can iterate with for , the above program can also be rewritten as for-line in open ("1.txt"): print line,# writes data to a file F = Open ("1.txt", ' W '); # W stands for Write-open file f.write ("hello World") f.close () # reads data from the Python interpreter's standard input and output stream name = Raw_input ("input your Name:")

5. String

Strings in Python can be represented using "" "" ""

A string that is different from the "", which is enclosed in three quotes, preserves the format of the string, and the Single-quote double quotation mark is on one line by Default.

str = ' Hello World I am a good studenti love python ' ' Print str

In python, a list of strings as characters (indexed starting at 0) uses an index to extract a single character from Python

str = "hello world" print str[1] # E

If you extract a substring, you can use the slice

str = "01234567" str = "01234567" str1 = str[0:4] #包含开头, contains no end str2 = STR[1:]STR3 = Str[:]print str1 #0123print str2 #123456 7print STR3 #01234567

You can connect two strings using the plus sign

Print str + "89" # 0123456789

Like PHP perl, python never implicitly interprets numeric strings as numbers, and if you want to perform a numeric operation, you must do a strong

NUM1 = "num2" = "all" print int (num1) + int (num2)

Data of non-string type can be converted to string using str ()

num = 213num_str = str (num)

Format is used to reformat a value into a string of a format

Format (9.8, "0.5f") # 9.80000

A string split (delimiter) method allows you to divide a string into a list of strings based on a specified delimiter

str = "pear,apple,orange" fruit = str.split (",") ["pear", "apple", "orange"]


6. Lists in list Python are sequences of arbitrary objects

names = ["joe", "sam", "tom"]

The list can be indexed by numbers, and the index starts at 0.

Print names[0] # joenames[0] = "jeff" #将names的第一个元素改为jeffnames. append ("lam") #将lam添加到列表的末尾 ["jeff", "sam", "tom", "lam"] Names.insert (2, "han") #在指定位置添加一个元素 ["jeff", "sam", "han", "tom", "lam")

You can use slices to copy a list, with the principle of manipulating the string

Use the plus sign to connect two of lists

A = [4,5] + [+] # [1,2,3,4,5]

Create an empty list

A = [] # or a = List ()

The list can also contain a list similar to a two-dimensional array

Li = [[1,2],[3,4,5]]print li[1][2] # 5

Let's look at some of the advanced features of the list using the following procedure

Import sys #导入sys模块, used to get command line arguments if len (sys.argv)! = 2:print "please supply a filename" RA Ise systemexit (1) file = open (sys.argv[1]) lines = File.readlines () #读取所有行, Returns a list of strings file.close () fvalues = [FL Oat (line) to line in lines] #通过遍历列表 generate a list of floating-point numbers Python comprehensionprint "the max of the values", max (fvalues) print "the mi N of the values ", min (fvalues) # returns the maximum value in the list by the built-in function, the minimum value

List objects provide a number of useful ways to view the Python API on its own


7. Tuple Tuples

Tuples are immutable lists can build some simple data structures through tuples

Address = ("a") person = (first_name, second_name, Age) stock = "GOOG", ten, 90.9 #创建元组的时候, parentheses can omit a = () #创建一个空元组b = (1,) #创建一个元素的元组 Note that the parentheses cannot omit first_name, second_name, age = person #可以通过unpack一个元组同时来给多个变量复制 print person[1] #当然, You can also get the value of the tuple element by index Second_name

Note: after the tuple is created, the element content of the tuple cannot be changed.

In real programming, if you need to create a lot of small lists, it consumes a lot of memory. In order for the list to be more efficient to add elements, it is common to create a list that allocates memory a little more than the actual size when allocating Ram. This is not the case with Tuples.

If the elements of a list are ganso, a simple way to traverse

Stock = [("baidu", 10,100.2), ("google", 90,12.4), ("sina", 124.5)]for name, amount, Price in Stock:print name, Amou nt, Price


8. Set Set

Collections are often used to hold unordered collections of objects

How to create a collection using set () and pass in a list

s = set ([1, 2, 3, 4]) s = Set ("hello")

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/88/30/wKioL1frgoyiH6X5AAAdivsVwN8358.jpg-wh_500x0-wm_3 -wmp_4-s_4168590498.jpg "title=" 1.jpg "alt=" wkiol1frgoyih6x5aaadivsvwn8358.jpg-wh_50 "/>

Because the collection is unordered, you cannot use an index to get an element the value of the collection element is not duplicated, such as Hello

The collection that is actually created contains only one L

Sets the symmetric difference set of the set of intersection sets that can be performed between sets

A = set ([1, 2]) b = Set ([2, 3]) print A & B # both in A and bprint a | B # A and bprint A-b # in a but not in bprint a ^ B # in a or in B. but not both

To manipulate elements in a collection

A.add (4) # Add an element to the collection a.update ([5, 6, 7]) # Remove an element by adding multiple elements a.remove (3) #


9. Dictionary Dictionary

A Python dictionary can


An understanding of a hash table in a data structure, a collection of Key-value Pairs.

Stock = {"name": "baidu", "amount": "price": 23.2}

Working with a dictionary

stock["name"] = "google" #更新字典的值stock ["date"] = "2016-09-28" #新添加一个项

A python dictionary usually uses a string (or a number, or Tuple) as a key, and the dictionary key must be an immutable object, and lists and dictionaries cannot be keys because their contents can be Changed.

Dictionaries can be used as containers for finding Out-of-order data, and lookups are very fast.

Define an empty dictionary

Stock = {} # or stock = Dict ()

Determine if a key exists in the dictionary

Price = {"apple": ten, "pear": "peach": $, "tomato": 24}if "apple" in Price:print price["apple"]e Lse:print "no apple" # The code above can replace the print price.get with the following line of code ("apple", 0.0) # If "apple" is present, return to price["apple", otherwise return 0.0

Get all keys for a dictionary

Keys = List (price)

Remove an element from the dictionary

Del price["apple"]


10. Looping and iterating looping and iteration

The most common looping statement used in Python is the for iteration, which is typically useful for traversing all elements in a collection (set list tuple dictionary), such as

For i in [1,2,3,4,5]: print i# or for I in range (1,6): #包含开头不包含结尾 print I

Range () to return a list

Common uses of the range function

Range (1,4) # [1, 2, 3]range (5) # [0, 1, 2, 3, 4]range (0,12,3) # 3 The list generated for the stride is [0, 3, 6, 9] Note that it does not contain 12range (5, 0,-1) # [5, 4, 3 , 2, 1]

The list returned by range () allocates all of the memory for the element, and when a large list is generated, it consumes memory, so the xrange () function is usually used when a large list is needed to be generated.

The For statement can be used to traverse many types of objects (list element dictionary string files)

str = "hello world" for C in Str:print C # traverse dictionary for key in Price:print key, price[key]# traverse all the lines of the file for line in open ("1.t XT "): Print Line


11 functions

Define a function

def remainder (a, b): c = a//b # quotient d = a-b*c # remainder return (c, d) # with tuples you can return multiple values

Calling functions

quotient, remainder = remainder (10, 3)

You can set a default value for a Function's parameters

def connect (hostname, port, timeout = +): passconnect ("80) # When setting a default value for a parameter, the parameter can be omitted

The scope of the variable defined inside the function is local, and when the function returns, the variable is Destroyed. If you want to modify a global variable inside a function, you can do this

Count = 0def Foo (): global count count + = 1foo () Print count # changed to 2


12 Generator Generator

Through the yield statement, the function can generate a list of results

If a function uses the yield statement, then this function is called a generator, and by invoking a generator function you can return an object by invoking the next () function of the object consecutively to get a list of results

# Generator.pydef Countdown (n): print "counting" while n > 0:yield n n-= 1

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/88/36/wKiom1fro_2yT0wOAABEdXaLZLs282.jpg-wh_500x0-wm_3 -wmp_4-s_3950884516.jpg "title=" 2.jpg "alt=" wkiom1fro_2yt0woaabedxalzls282.jpg-wh_50 "/>

But in practice, we don't usually call the next () function manually, but instead use the for to access the list of results returned by the Generator.

For I in Countdown (5): print i, # 5 4 3 2 1

Generators are useful in pipeline, data flow processing. For example, the following generator function mimics the TAIL-F command in Linux

Tail-f is typically used to detect a log file's dynamic growth process.

Import timedef tail (f):     f.seek (0, 2)   #将文件指针定位到文件尾部      while true:        line = f.readline ()         if not line:             time.sleep (1)              continue        yield line#  The following generator is used to check if a string list contains a keyword Def grep (lines, searchtext):     for line in  lines:        if searchtext in line:             yield line#  next, by combining two generators, Dynamically monitor whether the information generated by access.log contains the Python keyword wwwlog = tail (open ("access.log")) pylines = grep (wwwlog,   "python") for line in pylines:     print line 


13 Collaborative Program Coroutines

Normally the function is executed by accepting a series of single fixed parameters, and the function can be executed as a process by dynamically accepting the pass (the process is blocked before passing the parameter) to give his arguments to execute this function is called a synergistic program, which is implemented by expression (yield)

# coroutine.pydef print_matches (matchtext): print ' Looking for ', matchtext while true:line = (yield) # Waiting for the parameter to be accepted Number if matchtext in Line:print line


Next we first call this function through next (), when the function blocks at yield, at which point we pass the arguments to the function by sending, and once the function is executed, it blocks to yield again and waits for the Send argument to

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/88/36/wKiom1frqv3Q3jPEAAB3h2WHvdU931.jpg-wh_500x0-wm_3 -wmp_4-s_3835698060.jpg "title=" 3.jpg "alt=" wkiom1frqv3q3jpeaab3h2whvdu931.jpg-wh_50 "/>

A synergistic program is useful when writing based on a producer-consumer concurrency Program. Our program here is obviously as a consumer ("consumption" Data)

The following example combines a generator with a synergistic Program.

matchers = [print_matches ("python"), print_matches ("jython"), print_matches ("java")]for matcher in Matchers: Matcher.next () wwwlog = tail (open ("access.log")) for-line in wwwlog:for m-matchers:m.send (line)


14 Objects and classes

All values used in a program are called objects an object consists of its internal data and the methods of manipulating the data, for example, we have seen many methods of string and list objects Before.

Use the Dir function to see all the methods of an object

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/88/32/wKioL1frryeQXNKLAACrGnZW6gU024.jpg-wh_500x0-wm_3 -wmp_4-s_2835400940.jpg "title=" 1.jpg "alt=" wkiol1frryeqxnklaacrgnzw6gu024.jpg-wh_50 "/>

Class is used to define a class of objects

Class Stack (object): # object is the base class for all Classes def __init__ (self): #注意, All data operations on the class must use SELF. reference self.stack = [] # __ini The T__ method is used to initialize the class object, similar to the constructor def push (self, Object) in C + + java: self.stack.append (object) def pop (self): retur N self.stack.pop () return self.stack.pop () s = Stack () # New object of a class S.push ("hanguodong") s.push ("bullshit") s.push ([1, 2, 3]) top = s.pop () print Top # [1, 2, 3]top = s.pop () print Top # Bullshit

Because the stack is similar to the Python built-in list, you can implement the Stack class directly by inheriting list

Class Stack (list): def push (self,object): Self.append (object)

In general, methods defined within a class are generally applicable to objects of that class. we can also use decorators (decorator) to modify static methods in C + + or Java

Class EventHandler (object): @staticmethod def dispatcherthread (self): #静态方法 while True: # wait fo R Requests Passeventhandler.dispatchthread () # The static method can be called directly from the class name, not an Object.

15 Exception Exception

If there is an error in the Python program, an exception is thrown and the stack information is Printed.

Stack information usually prints where the error occurs and the type of error

We can use the try except statement to catch exceptions and then handle Them.

try:f = open ("text.txt", "r") except IOError as E:print E

When the IOError is present, the error details are passed to e, which is then referred to the except block for Processing.

If there is no exception, the except code block is ignored

The raise statement is used to manually throw an exception

Raise RuntimeError ("go to Hell")

Of course we can also customize our own exceptions by inheriting the exception class.


In addition, when dealing with exception handling of system resources (locks, files, Network connections, etc.), using the WITH statement can simplify the handling of exceptions such as

Import Threadingmessage_lock = Threading. Lock () Pass with Message_lock:messages.add (message)

When the program executes to the with statement, the program obtains the lock and, after executing the WITH statement block, releases the LOCK. If an exception occurs, the lock is freed when the control leaves the context code BLOCK.

The With statement is typically used for system resource management (locks, files, network CONNECTIONS) and users can customize their own processes through context-management protocols.


Modules Module 16

The module is a Python file, and with the import of this Python file, we can use the variables, functions, classes, and so on in This. py File. For example

# Div.pydef Division (a, b): return a//b

If you import a Module. There are three main ways of

    1. Import Div # note, do not add the. py suffix

A = Div.division (10, 4)

2. From DIV Import Division

A = Division (10, 3)

3. from DIV Import *

A = Division (12, 5)


17 How to get Help

Consult the API documentation

This article is from the "thick product thin hair" blog, Please make sure to keep this source http://joedlut.blog.51cto.com/6570198/1857503

Getting Started with Python (1)

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.