Python programming language Quick Start tutorial

Source: Internet
Author: User
Tags php example switch case chrome developer chrome developer tools vps amazon cloud services
Originally intended to find an introductory tutorial online, but because Python is rarely the first time the programmer has learned the language of the program, so the existing online tutorials are not very basic, or decide to write down their own.

If there is no basis for the program, you may feel that this article covers a bit more content. Compared with the teaching speed of the C language taught in the university, this article has about four or five lessons; compared with the online program class video tutorial, roughly the equivalent of two or three hours of content; For a book to turn a program, it's about one hours. Therefore, if there is a deep study of the intention, in order to efficiency or recommend reading.

It doesn't matter if you don't understand some of the content in this article for the time being, because it's a basic knowledge that's often used, and it's always going to happen in the process of actually writing code. There will be about two or three articles written about the code of practice, and you can choose to deepen your impressions of that knowledge at that time.

But if the technology is not necessary for SEO and not interested in this article, how many plans will seo as their career? If you're going to really do it well, it's reasonable to take a few hundred hours to learn from it, at least for tens of thousands of hours.

If you are unable to understand any of the articles that have not been stated clearly, please make sure to help. The first time to write a more complete tutorial class, there are inevitably omissions.

Why learn Python

If you decide to learn some technology to help SEO, for the programming language at least in my opinion Python is the preferred.

First , Python is relatively simple to get started

If a person who has been exposed to C language in the university curriculum but does not know much about the program, may feel that the program is like C so troublesome, in fact, learned the beauty of the Python code will know the C code and smelly and long. It doesn't matter if you haven't touched the program at all, Python itself is a good choice for getting started with the program.

Although I have written a program very early, but at that time is the interest, never in-depth, the formal contact program is contact with SEO after the thing, about a few hours after learning to write some simple collection procedures, to now as long as the need to think of a few technology can not be achieved. So there is no basis for the problem, no matter what the foundation is to lay down their own.

Secondly, Python code is very flexible

Look at a very common code example, if there is no program based on the words will not understand the code, but it does not matter, look at the number of lines of code can also compare the code of simplicity.

Php:

The code is as follows:


$list _1 = array (up);
$list _2 = Array ();
foreach ($list _1 as $current) {
Array_push ($list _2, $current + 1);
}
Print_r ($list _2);
?>


Python:

The code is as follows:


List_1 = [up]
List_2 = [current+1 for current in list_1]
Print List_2


The 2nd line of Python code is called "list derivation," which provides a lot of language features like this to make the code very concise.

Although grammatical flexibility is not always a good thing, flexible code notation means that each person writes out code that tends to be very different in style, widening the level gap between team members and not benefiting team development. But for small SEO application requirements are generally personal development, the writing efficiency of the code is more important than teamwork.

its third, Python uses a wide range of

Python's popularity in the programming language is about 5-10 bits or so. Before it was C #, Java, PHP, etc., but many times not because they are more powerful, but because of the reasons mentioned earlier, their code is relatively not very flexible and suitable for team development, so it is more popular.

In general, most of the Web services that provide the API provide Python interfaces (such as Baidu Internet, Amazon Cloud services, etc.), while others that are more powerful than python do not have such broad support, such as the Go language, where the code is more flexible. (The API interfaces for most Web services are: C #, PHP, Java, Python, Ruby, Perl, so choose at least one language to learn in general)

Python has a lot of modules, and there are many existing modules that mean you can do much less. For example, to download a Web page, you need 5-10 lines of code in many languages, and Python requires only two lines:

The code is as follows:


Import Urllib2
Print Urllib2.urlopen (' http://g.cn/'). Read ()


It's also interesting that Google has previously restricted its own internal use of Python language for development. There are 2:1 reasons for the high efficiency of Python writing, which was used too much before, and the Python language was slow to execute. But for SEO, it is the most need to focus on writing efficiency and generally do not care about the efficiency of implementation.

At this point a lot of nonsense, but interest is often the best motivation to learn, I hope there is no white crap.

installation Environment and configuration

Python program and ordinary program slightly different, usually do not directly under Windows double-click Run EXE file, although not can not be compiled into EXE but relatively troublesome, practical application rarely go to such operations.

A python program is a text code that is saved in a file with a suffix called. py. You can run the Py file after the computer has installed the Python runtime environment. (in fact, many programs are dependent on the operating environment, the most common is the. NET Framework, but this is preinstalled on windows, generally not feel it)

For Windows systems to install a running environment, the Linux system typically comes with Python without configuration.

The download link for the Python Runtime environment is: http://python.org/getit/

On this page, usually on the first download link, find and download: Python 2.7.x windows Installer (Windows binary-does not include source)

Note that it is best to download the 2.7.x version (X for any number, 2.7 is similar to the large version), while Python version 3 and above differs greatly from the previous version, and is not recommended for beginners.

Install after download, there is no need to pay special attention to the place. Generally installed in the default path, that is, c:\python27\, do not put it in a directory-level deep folder, or run the time is more troublesome.

Operating System

As mentioned earlier, Python can run under Windows and Linux systems, it also supports more systems, such as Macs, and even writes and runs Python programs on devices such as jailbroken iphones.

But because one of the main strengths of Python is the support of its modules, there are many things that can be done conveniently with modules. The configuration of the module in Windows and other systems are often a bit cumbersome, Linux is often much easier, so after the introduction phase, it is recommended to develop in the Linux environment.

There are three options for building a Linux environment:

1. Install the Linux system natively. People who work for a long time under Linux need to have a good understanding of the basics of Linux. The main drawback is that there are always some windows inside to run the program, occasionally need to switch the system. I work mainly in this kind of environment.

2. Install virtual machines such as VMware in Windows and install Linux in the virtual machine. Suitable for beginners, but because of the relationship between the virtual machine, unless the computer configuration is very good, otherwise the operating efficiency of both systems will be relatively low. And the virtual machine is not conducive to shaping the atmosphere of learning Linux, because when the virtual machine encountered problems, most people will prefer to use Windows instead of Linux, it is more difficult to familiarize with it. This option is not recommended by individuals.

3. Buy a Linux VPS, using SSH remote operation. The main advantage is that in the work and home can be very convenient to connect to the server, not every day to the program, data and so on with the U disk and so on, you can use Linux without affecting the use of Windows. But the shortcomings are equally obvious, no graphical interface is unfriendly to beginners, because of the network delay, the efficiency of writing code is often affected and so on. For beginners, this solution is recommended by individuals.

As for the purchase of VPS, recommended Linode or PHOTONVPS, etc., about a month 50-150RMB can buy a can be used to write running a common program of the VPS, can also be placed on the top two or three small sites.

Linux has a number of distributions that you can choose to install, such as Ubuntu,fedora.

For Linux environments built on this machine, it is recommended to install Fedora because it has a graphical interface and is primarily intended for work. It and the server's most commonly used CentOS system with the Red Hat, a lot of places closer, familiar with it is also useful for the familiar with CentOS.

If you install it natively and sometimes use the Linux system as a way to watch video and other entertainment, it is recommended for Ubuntu, which has a slightly better use of fedora than any other day.

For a VPS built with Linux, the CentOS system is recommended because it is the most widely used, so the support of various software is often better.

corresponding to the Linux environment Solution 1, generally use a USB stick to load the ISO image for installation, for solution 2, generally directly by the virtual machine software loading ISO image installation; For Solution 3, the general VPS can be directly selected in the rear of the operating system without their own installation, more convenient.

Editor

Before writing the code, you need to have a suitable editor first. Although Windows comes with a notepad that is not available, it is very uncomfortable when you write a program.

For the editor of Windows system, the simpler I recommend notepad++, of course, can also choose more popular ultraedit.

You can also use the IDE, a general term for the integrated environment used to develop a software project, which has a large advantage in developing large projects, but may seem slightly inflexible when dealing with small requirements. The IDE is better with Eclipse, plus the Pydev plugin to develop Python programs, which are available in both Windows and Linux.

If you usually need to write a large amount of code, or for your ability to learn more confident, for Linux recommended vim,windows is recommended Gvim (Vim graphical interface). It differs greatly from the normal editor's writing code, often requiring a few days of study time and a few months of proficiency, but the efficiency of writing code can generally be much faster.

Start Writing Programs

Hello world!

The first source of "Hello world" is one of the most classic books in the field of computer science-the C programming Language, which was later widely adopted. The purpose of the "Hello World" program is simply to output a "Hello World" on the screen, although it is simple enough to have a big meaning when it is the first program written by everyone.

Open Editor, enter a line: (Friendship tip: Copy and paste bad memory)

The code is as follows:


Print "Hello world!"


Complete. Save the file to c:\hello.py (path optional).

Press Win + R shortcut key, open "Run", enter CMD, return, open command line prompt. (Linux graphical interface is ctrl+alt+t to open the terminal)

Input:

(Windows)
C:\python27\python.exe c:\hello.py

(Linux)
Python path/hello.py

You can see that the program is running and displays a line of "Hello world!". At this point, the first program is complete.

Variables and Assignments

The code is as follows:


s = ' Hello world! '
Print S



Program output:
Hello world!

The above code, S is called a variable; the first line is called assignment.

One more example to deepen the impression:

The code is as follows:


A = 1
b = 2
Print A + b



Program output:
3

Function

The code is as follows:


def hello (name):
s = ' Hello ' + name + '! '
return s
Print hello (' world ')
Print hello (' semwatch ')


Program output:
Hello world!
Hello semwatch!

A function is used to wrap a series of behaviors by passing one or more arguments into the function (Def hello), and then the function returns a computed value (return s).

So print hello (' world ') is equivalent to the output of the result of the Hello function running, that is, the output Hello world!

You can look at this example to deepen your understanding:

The code is as follows:


Def add_num (A, B)
Return a + b
Print Add_num (1, 2)
Print Add_num (2, 3)


Program output:
3
5

Cycle and judgment

The For loop, while loop, and if judgment mentioned later are the basis of all programming languages and must be fully mastered.

(Python does not have a do-while loop in other languages, nor does the switch case judge)

For loop:

PHP Example:

The code is as follows:


for ($i =0; $i <10; $i + +) {
echo "$i \ n";
}
?>


A php example is given here because the for loop in most programming languages is a similar syntax to this example, first in this form.

It should be easier to understand that the variable i is assigned a value of 0 ($i =0), each time the loop +1 ($i + +), at the time I is less than 10 has been circulating ($i <10), so the loop 10 times.

The Echo statement is responsible for outputting the digital output at each time of the loop, which in turn outputs 0-9 of these numbers, but there is no need to study echo syntax, just understand the concept of the For loop.

Python's for-loop syntax is a bit more alternative, but also concise:

The code is as follows:


For I in range (10):
Print I



These two statements will output 0-9 of these numbers sequentially, and the print statement will automatically wrap after each output.

While loop:

The code is as follows:


i = 0
While I < 10:
i = i + 1
Print I



The code means that I is assigned a value of 0, and then when I is less than 10, the contents of the loop body are continuously executed. This is to add the value of I to 1 and output I.

The results of the run-after output are 0-9 numbers in turn.

If judgment:

The code is as follows:


i = 1
If I < 2:
Print "I<2"
Else
Print "i>=2"


Program output:
I<2

The program first assigns I a value of 1, and then determine whether I is less than 2, if less than 2 output i<2, otherwise output i>=2.

In addition, the judgment symbol that equals and does not equal is as follows:

The code is as follows:


i = 1
if i = = 1:
Print "I=1"
elif I! = 1:
Print "I!=1"



equals = = Symbol, which is easily confused. Using the = symbol creates some problems in most languages, and in Python it is directly considered a code error. Instead of the sign is! =, you can also use <&gt, but the <> is less used in today's programming languages and may be deprecated in Python later versions, so it is generally recommended to use! =.

The third line of elif in the above code is shorthand for else if. If the i==1 is not satisfied, continue to judge whether I!=1 is satisfied.

Lists and dictionaries

Most languages have an "array", which is a variable with multiple values. And Python does not, similar to "list" and "dictionary" and so on.

If you have a PHP base, you can quickly understand them by looking at the following comparisons:

List:

Php

The code is as follows:


$l = Array (+/-);
?>



Python

The code is as follows:

L = [n/A]



Dictionary:

Php

The code is as follows:


$d = Array (
' A ' = 1,
' B ' = 2,
' C ' = 3,
);
?>


Python

The code is as follows:


D = {
' A ': 1,
' B ': 2,
' C ': 3,
}



If there is no other language basis, it may be more appropriate to understand the list and the dictionary by the actual code.

List:

The code is as follows:


L = [n/A]
For current in L:
Print current


The results of the run will output 1-3 of these numbers sequentially. (Python does not have the foreach syntax for PHP, all using for completion)

Dictionary:

The code is as follows:


D = {
' A ': 1,
' B ': 2,
' C ': 3,
}
For key in D:
Print key
Print D[key]


The results of the run are output a1b2c3, shown in six rows.

Explain the dictionary, the structure of the dictionary is this:

Dict = {key:value, key2:value2, ...}

The For loop can assign the corresponding key to the variable at each loop, and if you want to access the corresponding value, you need to use something like Dict[key], which is to find the value of the key in the Dict.

Similarly, the list also has similar operations, such as:

The code is as follows:


L = [n/A]
Print L[1]


Run output:
2

It means the 1th item of the output list L. It is important to note that the majority of programming languages are calculated from the beginning of item No. 0. That is, here l[0] is 1,l[1] is 2,l[2] is 3.

Strings and slices

A string, such as its name, is a string of characters. such as print "Hello world!" is the output string Hello world!. Python has a special string, which is the same as a list of sequence types, many of which are used in the same way as lists.

The code is as follows:


s = "abc"
Print S[1]



The result of the run is output B.

Based on this feature, some concise code usage can be derived. For example, to output "Hello world!" For the first 5 characters of this string, most languages will be similar to PHP:

The code is as follows:


$s = "Hello world!";
Echo substr ($s, 0,5);
?>



And Python is much simpler:

The code is as follows:


s = "Hello world!"
Print S[:5]



Both pieces of code will output hello.

S[:5] uses Python's "slice" feature, the complete notation should be s[0:5], but 0 can be omitted, this represents the output of the sequence index number from 0 to 5 before the content.

Of course, the list can also be used for slicing, such as:

The code is as follows:


L = [n/A]
Print L[1:]


Post-run output [2,3].

This means that starting at index number 1, the output is to the end of the list.

Summary of Knowledge points

Combine all the previous content with some new knowledge points to fuse into a piece of code. Think carefully about how the results of each output are coming out, and you can understand them better. Because more knowledge points, can temporarily superficial understanding, but these are any programming language inside the basic content, and ultimately must be mastered.

In the code, #号意味着注释的开始, the content will not be run.

In addition, the first line of code declares that the code is encoded as Utf-8. Because non-English characters appear in the comments, you need to specify the encoding, or the program will error.

The code is as follows:


#-*-Coding:utf-8-*-
str_1 = ' Hello '
str_2 = ' world! '

#以下语句都会输出Hello world!

#print语句中的逗号意味着不换行, they are separated by spaces
Print str_1, str_2

#以下和上面一句是同样的效果
Print str_1,
Print str_2

#同样可以用字符串连接符
Print str_1 + ' + str_2

#也可以用格式化操作符, it's more common than the former.
Above #会将后面的变量依次替换到前面的%x
#%s is substituted with a string, and if the replacement integer is%d, the decimal%f
Print '%s%s '% (str_1, str_2)

#会输出00 11 22
For I in range (3):
print '%d%d '% (i, i),
print ' #输出一个空的字符串用于换行

#会输出11 22 33
For I in range (1, 4):
print '%d%d '% (i, i),
print '

#会输出00 22 44
For I in range (0, 5, 2):
print '%d%d '% (i, i),
print '

#会输出0 1 0 1 0
i = 0
While I < 5:
i + = 1 #等同于i = i + 1
If I% 2==0: #如果i除2的余数为0
Print 1,
Else
Print 0,
print '

#会输出c
i = 3
If i==1:
print ' A '
Elif i==2:
print ' B '
Elif i==3:
print ' C '
Else
print ' ERROR '

#会输出1 2 3 3 4 4 5 5 6
For I in range (10):
i + = 1
Print I,
If I < 3:
Continue #如果i <3 interrupts the cycle and re-runs from the head of the loop body
Elif i > 5:
Break #如果i >5 interrupts the entire loop
Print I,


At last

Although the process is now mentioned, SEO is more than just a program to deal with the technology. Although I would like to start from the beginning to mention all the aspects that should be learned, but this is a few books are not finished, only a few articles more can not be exhausted.

In the next article, some knowledge points will be skipped, and if the reader does not have the relevant foundation, then it is necessary to learn by yourself. The following will be skipped including but not limited to:

1. Basic Web knowledge, such as the URL of a non-ASCII character set requires encoding and other common sense: http://www.w3school.com.cn/html/html_urlencode.asp

2. The use of browser developer tools, you can choose Chrome Developer Tools, or Firefox firebug plug-ins, etc., personally recommended Chrome. In particular, it is necessary to understand the packet capture function, which is often used when collecting data. The Grab pack feature is in the Chrome developer tool and corresponds to the "Network" tab.

3. Configure the Python pycurl module independently. There are two main options here, one is to install Curl on the Windows system, then install the Setuptools, and finally install the module, the trouble is not recommended, and later the other modules in Windows configuration may also be so troublesome. Another option is to configure a Linux environment, in the CentOS and Fedora Systems, execute: sudo yum install Python-pycurl, in Ubuntu and other systems, execute sudo apt-get install Python-pycurl. This module is then used extensively, so be sure to configure it well. Linux entry commands are visible: Http://ooxx.me/common-ssh-commands.orz

4. Learn about regular expressions. It is used to deal with strings of powerful tools, you can search for information on Baidu to do a preliminary understanding of it, at least first know. * And [\s\s]*? These two meanings, they are most commonly used in the process of acquiring data. This is a very good but difficult regular tutorial, may not be suitable for beginners: http://manual.phpv.net/regular_expression.html

In addition, it is best to buy a python book, although because SEO is not necessary to the program involved in depth, most of the program books on the importance of most of the knowledge is not high. For example, each book will spend a lot of space to introduce the idea and implementation of object-oriented programming, but most of the needs of SEO often only hundreds of lines of code, generally not too will be involved in these. However, at the beginning of some basic knowledge learning process, it is easy to overlook or forget knowledge points, there is a book is much better.

Have not found more suitable for SEO to see the Python books. I have a copy of "Python core programming" on hand, and I should say it's OK. If you are not sure which one to buy, you can go to this forum to find a PDF sample, it above all kinds of computer books should be relatively the most complete: http://club.topsage.com/forum-300-1.html

But don't just look at the PDF, generally learn a language at least a paper-based books, it should be in their own unclear or forgotten what knowledge points, can be used to turn over the reference book at any time.

Article Author: ZERO

This article from Semwatch Reprint please indicate the source link and author.
  • 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.