The Day2 of the Python automation lesson

Source: Internet
Author: User
Tags control characters

Part II: Introduction to Python and Getting started

First, what is Python?

Python is an object-oriented, interpretive type of computer language, it is characterized by simple syntax, elegant, easy to learn.

Invented by Dutch Guido van Rossum in 1989, the first public release was released in 1991.

Python is purely free software.

Python syntax is simple and clear, and one of the features is to force whitespace (white space) to be indented as a statement.

Python has a rich and powerful library. It is often nicknamed the glue language and is able to easily connect a variety of modules made in other languages, especially in C + +. A common application scenario is to use Python to quickly build a prototype of a program (sometimes even the final interface of the program) and then rewrite it in a more appropriate language, such as a graphics rendering module in a 3D game, with a particularly high performance requirement, and can be rewritten in C + + with a specially requested part. It is then encapsulated as an extension class library that Python can call. It is important to note that you may need to consider platform issues when you use the Extended class library, and some may not provide cross-platform implementations.

Ii. explanatory language and compiled language

Computers can not directly understand the high-level language, only directly understand the machine language, so the high-level language must be translated into machine language, the computer to perform high-level language programming programs. One is compilation, one is explanation. The two ways are only different in the time of translation.

Compiled language is the first to translate the written program into a computer language and then execute, is called a compile everywhere, such as C, C + + is a compiled language, such language features is fast, but need to compile the program in advance can be, program execution efficiency high, relying on the compiler, cross-platform poor.

Interpreted language is the program at the time of operation, through an interpreter, the code sentence by translation into a computer language and then run, that is, you write the code directly can run, such as Python, Shell, Ruby, Java, Perl and so on are interpreted language, Of course, such a language because of the principle is not the same, the execution speed is not compiled language fast, low efficiency, rely on the interpreter, cross-platform good.

Third, choose python2.x or python3.x?

Python now has a 2.x version and a python3.x version, and in choosing the version of this thing, a lot of people are more tangled. Whether to choose 2 or 3, because the 2 and 3 codes are not compatible, Now more commonly used is the 2.7 version, 2.7 version is actually a transition version, in 2008 when the release of 3.0, due to the 3.0 version of the change is relatively large, and the 2.x version is incompatible, many with Python2 's company DD rewrite the code is too laborious, so in the same year released the 2.6 transition version of Python, joined Some 3.0 features, released in 2010 2.7 version, is also a transitional version, in 2014, when the official Python announced 2.7 support to 2020, will not release the 2.8 version, as soon as possible to migrate the program to the 3.x version. Python2 's default character set is ASCII encoding, write Chinese will error, character encoding has been a headache for programmers, python2 in the processing of Chinese, it is really a headache, In the python3.x version, the default character set is Unicode, which saves a lot of things, so, or is recommended to use the python3.x version.

Four, Character set

Characters (Character) are all kinds of words and symbols, including the national text, punctuation, graphic symbols, numbers and so on. The character set (Character set) is a collection of multiple characters, with a variety of character sets, each with a different number of characters, common character set names: The ASCII character set, the GB2312 character set, the BIG5 character set, the GB18030 character set, the Unicode charset, and so on. To accurately handle a variety of character set text, the computer needs character encoding, so that the computer can recognize and store a variety of text. The number of Chinese characters is large, but also divided into Simplified Chinese and traditional Chinese two different writing rules of the text, and the computer was originally designed by English single-byte characters, therefore, the Chinese characters are encoded, is the technical basis for the exchange of information

2 binary: Binary is a system widely used in computing technology. Binary data is a number represented by 0 and 12 digits. Its base is 2, the rounding rule is "every two in one", the borrow rule is "borrowing one as two", which was found by the 18th century German mathematical philosophy master Leibniz. The current computer system is basically binary systems, the data in the computer is mainly in the form of complement storage. The binary in the computer is a very small switch, with "on" to indicate 1, "off" to represent 0.

BYTE: Byte refers to a small group of contiguous binary figures. is usually 8 bits as a byte. It is a small unit that makes up information and participates in the operation as a whole.

ASCII code: ASCII code uses the specified 7-bit or 8-bit binary number combination to represent 128 or 256 possible characters. The standard ASCII code is also called the base ASCII code, using a 7-bit binary number (the remaining 1 bits of binary 0) to represent all uppercase and lowercase letters, numbers 0 through 9, punctuation, and special control characters used in American English.

ASCII code table, http://www.96yx.com/tool/ASC2.htm.

Chinese characters are broad and profound, what are the characters of minority nationalities, how to do, we also want to use computer Ah! But already said that the largest number of bytes in a byte is 255, the old beauty of these buddies have used 127, the rest is not enough Ah, Chinese characters and minority characters at least tens of thousands of, this can do it, the Chinese is smart, then we will use less points, take 127 of the number of numbers, the specific use of how much, I also remember, as long as the number encountered this interval, I know is Chinese, go to another code table inside, this is stored in Chinese, there are other countries, such as Japanese, Korean, etc., this is called gb2312 code, it contains 6000+ characters, so that, Can solve the problem that the computer does not know Chinese. But Chinese culture, profound, not only have 6000+ a Chinese character, and then have GBK, Unicode, UTF-8 and so on, Unicode encoding is also called the Universal Code, which country of the text is applicable, but it whether you are an English letter, or a Chinese character are accounted for 2 byte size, The original ASCII code an English letter accounted for a byte, this look, the original 100G things, now may have 200G to save the next, this can not, and then appeared the UTF-8 character set, it also belongs to Unicode, and Unicode is not the same, It compresses Unicode, like an English letter or a byte, so it saves a lot of space, which is why everyone now uses UTF8.

V. Installation of Python

To use the Python command to add the Python installation directory to the environment variables, Windows also to the Python installation directory under the scripts directory to add to the environment variables, because some python executable commands, such as PIP, is installed in this directory, Linux because the default with Python, if you want to upgrade the version of the system, you have to rename the Python or uninstall, and then install the Python version you want, Under CentOS because Yum relies on its own python2.6, all cannot be uninstalled, modify the Python environment variable location in the Yum script.

Liu, Pycharm

1.Pycharm How to set the font

File-->settings-->editor-->colors&fonts Select Scheme-->save as--> to modify the font and size.

2. Create New Project

Select path:

3. Upload the code directly to git in Pycharm.

How to download a git project on Pycharm

Upload code to Git

Two ways to run the python command:

1. In Pycharm, right button-"Run **.py."

2. Run in cmd

Right-click on the **.py file,

In the path directly Cmd,python **,py can be.

or the terminal in Pycharm enter the operating system commands.

Seven, variable

Variables are derived from mathematics and are abstract concepts that can store computational results or represent values in a computer language. Variables can be accessed by variable names. The simple point is to store something for the back. The definition of variables in Python is simple, an equal sign does not need to specify the data type, the direct definition is good, it is worth mentioning that the python variable is stored in memory address, that is, where the value exists in memory, if the variable is assigned to another variable, The new variable is stored by the memory address of the variable value that the previous variable knows about, not the previous variable pointed to.

Cases:
Name= ' LJ '  (define string must be ")
Age=20
Print (name)
Print (age)

Rules for defining variables:

Variable name to see the name to understand, not to write blindly, do not use pinyin, not to use Chinese as a variable name, although Python can indeed use Chinese as the variable name!

Variable names can only be any combination of letters, numbers, or underscores, and variable names may begin with a letter or underscore, but cannot begin with a number.
Variable names cannot contain spaces, but you can use underscores to separate words in them.
Do not use Python keywords and function names as variable names, that is, do not reserve words for special purposes using Python, such as Print,and, as, continue, for, are, while, or, in, else, def ....

Variable names should be both brief and descriptive.

Use the lowercase l and the capital Letter o sparingly, as they may be mistaken for numbers 1 and 0.

Eight, single quotes, double quotes, and three quotation marks (three single quotes) in Python

Python in the definition of variables when the strings are enclosed in quotation marks, single and double quotation marks no difference, with anything, if there is a single quotation mark inside the string, then you use double quotation marks inside, there are double quotation marks, the outside with single quotation marks, if there are both single and double, then use three quotation marks, Three quotation marks can also be multiple lines of comment code, single-line comments, using #.

Cases:

Message= ' I told my friend, "Python is my favorite language"
Print (message)
Output: I told my friend, "Python is my favorite language"

Nine, input, output

Python receives user input, uses the input function, and the output uses print.

Cases:

Name=input (' Please enter your name: ') #把接收到的值赋给name变量
Print (name) #输出接收到的输入

Input at the time of receiving inputs, you can see the value you entered, if you enter a password such, do not want to let others see your password, you need to use a standard library, Getpass, what is the standard library, it is not necessary for you to install, complete Python library, is the standard library, Getpass is a standard library, after importing, the direct use of the Getpass.getpass method can be entered in the time, do not echo, the code is as follows:

Import Getpass
Name=input (' Please enter your name: ')
Passwd=getpass.getpass (' Please enter your password: ')
Print (name)
Print (passwd)

Running this code is not supported in Pycharm and must be run in terminal or cmd with Python **.py.

Ten, condition judgment

1. In Python, the conditional judgment uses if else to judge, multi-branch words using if elif ... else, that is, if it's what happens, or how it's going to happen.

Python is indented to represent the code block, so it looks like the code is very organized, such as the above example, if it rains tomorrow, then tomorrow will bring an umbrella, tomorrow with an umbrella is equivalent to the son of if, so you can also think that there is a parent-child relationship, write an example of the actual point, as follows:
name1= ' LJ '
Name2= ' Zhx '
Name=input (' Please enter your name: ')
If name==name1:
Print (' You're welcome ')
Elif name==name2:
Print (' Welcome home! ‘)
Else
Print (' Happy everyday~ ')

If judgment is judged by two types, one is true one is False (Boolean type)

T=true

F=false

Cases:

Car= ' BMW '
Car1=input (' Enter car name: ')
Print (Car1==car)
Output: Enter car NAME:BMW
Ture


Condition Judgment:

= = equals

! = Not equal to

> Greater than

< less than

>= greater than or equal to

<= less than or equal to

Note that there must be a comparison operation with the same type, with different types of errors.

2.if ... and And if ... or

Print (type (variable)) #看变量是什么类型 #

The value received by the input () function is all string type, and if you want to compare it with the int type, you must convert the string int () to type int.

Coercion type conversion: age=int (Input (' Please enter your Age: ')

Cases:

Sex=input (' Please enter your gender: ')
Age=int (Input (' Please enter your Age: '))
Print (' See what type of age ': ', type ')
If sex== ' man ' and age<20:
Print (' Little meat ')
elif sex== ' woman ' and age<20:
Print (' Little Flowers ')
Else
Print (' Old guy ')

If...or ... Meet one of the conditions

#float类型是可以和int类型做比较, add

S= ' Oh hehe ' #字符串

A=18 #int类型, integral type

C=true #布尔型的, False

d=18.8 #小数类型, float

# Print (1/2)
# print (1//2) #地板除, is automatic rounding, will not be rounded, directly erase the decimal part

#在python2里面, this operation print (1/2), the result is not correct, because in python2 int and int type operations will be automatically rounded, there is no problem in Python3

#if判断时候, both true and false, that is, true and false.
#记住一句话, not 0 is true, non-empty is true

Name=input (' Please enter your name: ')
If Name:
Print (name)
Else
Print (' Erro ... ')


Xi. formatted output

What is formatted output, that is, your output is formatted into a look, such as login welcome information, are welcome to Login,marry. Each user login is welcome, but each user's user name is the same, you can not write a line of code for a user, which requires the use of formatted output, there are three ways, the first is to use "+" connection, directly the output of the string and the variable is connected to it, and the second is to use a placeholder, There are three commonly used placeholders,%s,%d, and%f,%s are the following values are a string,%d is the following value must be an integer,%f is followed by a decimal, the third is the {} and Fromat methods, these three, the official recommendation is to use the Format method, is not recommended to use the first type, The first use of the Plus, will be in memory to open up a number of memory space, and the latter two is only a piece of memory space, using the following:


String formatting
 
Name=input (' Please enter your name: ')
Print (' welcome you ' +name) #第一种用 + connection, not recommended, not high efficiency

Print (' welcome you ', name) #第二种用, connect
Print (' Welcome you%s '%name)  #%s represents a placeholder, commonly used.

Cases:
Name=input (' Please enter your name: ')
Sex=input (' Please enter your name gender: ')
Print (' Welcome you '%s ', your gender is '%s ' '% (name,sex)) #使用多个占位符

Placeholder:%d for the following variable is an integer
%f is followed by a decimal, do not specify the number of digits reserved by default 6 bits,%.2f retain a few decimals, will be rounded
Cases:
Age=int (Input (' Please enter an integer: '))
Grade=float (Input (' Please enter your score: '))
Print (' The integer you entered is%d '%age ')
Print (' Your score is%.2f '%grade)


If the parameters are relatively small, it is easier to use placeholders
If there are many arguments, formatting is more intuitive with. Format
Cases:
Age=int (Input (' Please enter an integer: '))
Grade=float (Input (' Please enter your score: '))
Print (' Your age is {your_age} ', ' Your score is {Your_grade} '. Format (your_age=age, Your_grade=grade))

12. Circulation

The cycle is for you to do things repeatedly, for example, you want to build 1000 folders, a build exhausted you, so you can write a code, use the loop to create 1000 for you to save time, Python has two loops, while and for, the difference between the two loops is that the while loop, First of all, if the condition is met, then the loop, for loop must have an iterative object, in order to loop, for example, to have an array, it is worth mentioning that in other languages, for loop needs to define a counter variable, and then starting from 0 to add, Until this counter reaches your preset value, and then stops the loop, and when the data is taken from the array by the subscript 0, it is troublesome that the for loop in Python is very simple, looping through an element in an iterative object, how many elements you have in the object, how many times you are looping, For example, an array list,list = [' A ', ' B ', ' C '], in other languages to get to the list of all the values, you have to use the loop to take off the mark this way to fetch the data, you have to write list[x],list[x],list[x] so, In Python there is no need to directly loop on the list of values, the loop inside there are two more important keywords, continue and break,continue mean, jump out of this cycle, continue the next cycle, break means to stop the loop, Which means that the code under continue and break is not executed.


Loop, iterate, iterate
There are two types of loops in Python:
While
For

1.while Cycle
Count=int (Input (' Please enter an integer: ')) #count是一个计数器
While count<10:
Print (' Good person ')
Count=count+1
#循环体
Else
Print (' done! ')

Break exits the loop, break can only be used inside the loop, and if you encounter a break in the loop, exit the loop immediately
Cases:
Count=0
While count<10:
Print (' Sing a song! ')
Count=count+1
If count==5:
Break

The use of continue, the role of continue is to exit this cycle
Count=0
While count<10:
Count=count+1
If count==5:
Continue
Print (' Sing a song!%d '%count)

2.for Cycle
For,continue usage
Cases:
For I in range (10):
If i==4:
Continue
Print (' Sing a song,%s '% i)

For count in range (1,10): #顾头不顾尾
Print (count)
Else
Print (' over ... ')
#for循环对应的else, only if the For loop ends normally


Day2 of the Python Automation lesson

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.