Introduction to Python and Getting started

Source: Internet
Author: User
Tags sublime text

I. What is Python

Python is an object-oriented, interpretive type of computer language, it is characterized by simple syntax, elegant, easy to learn. In 1989 births, Guido (Uncle Tortoise) developed. The python here is not meant to be python, but the turtle uncle likes a TV series called "Monty Python Flying Circus", so it is named after Python (the foreigner is so willful).

Two. Interpretive language and compiled language

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, the language is characterized by the speed of operation, but need to pre-compile the program can be.

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.

Three. Choose python2.x or 3.X?

Python2.x announces support to 2020, all recommended options python3.x

Four. Python installation

Python How to install it, this is a no nutrition topic, I do not write, Baidu a heap of heap, to note that if you want 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 into 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, To rename or uninstall the system's own python, 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 within the Yum script.

Five. Character Set

      say the character set before, the first word 2 into the story, the computer compared silly only know 2 binary, what is 2, is 0, 1, the computer only know these two numbers, others do not know, such 0 or 1 is a "bit", the provisions 8 bits for a byte, Byte is the most basic of the real world character of a unit, such as an English letter, a byte is 8 bits, that is, the maximum can save 8 0 or 1, 8-bit binary maximum is 255, how to convert because I am not good at maths ... Do not say here, interested in their own conversion bar. The front cushion so much is for what, is to say the following these, since the computer only know 0 and 1, that how to express these English letters, as well as Chinese characters, punctuation? The computer is old beauty these brothers invented, and then they created the ASCII code this thing, this thing is why, is to use numbers to represent these symbols, encountered these numbers is to know what is represented, and then converted into binary system, so that the computer can save these English symbols, the old United States these brothers, With 127 numbers, it represents all the English uppercase and lowercase letters and symbols, this is the ASCII code table,            http://www.96yx.com/tool/asc2.htm. Then the problem comes, the computer know the old beauty of these buddies of English, then we Chinese compatriots what to do, Chinese characters are broad and profound, there are also what minority characters, how to do, we also want to use the 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, for example in English.The letter or the account of a byte, so that the savings of a lot of space, this is why everyone now use UTF8 reason.

Six. Run Python code

Windows, after installing Python and configuring the environment variables, you can enter Python directly on the command line to enter the Python interactive command line, Linux is also the same, what is called Interactive, interaction is you say a word to me, I respond to you, this is the interaction , look at the following figure, after installing Python Python also comes with an idle, that is, you can write code in it, but that is not very good use, here is not to repeat.

But it is too inconvenient to write code, how to write all the code, and then run together, is to write the code into the file, and then run the file, to. py end of the Python file, there are many Python editor, such as Pycharm, sublime text, notepad++ and so on, can be used, using the editor has code hints, can be very convenient to debug and run, here I recommend the use of Pycharm. Create a new Python file, and then write the code to run it, such as:

This is true under Linux, unlike Windows, where you can run Python files directly, without the need for Python commands, plus execute permissions, but you need to specify the Python interpreter at the front of the Python file, Liunx. With the path of the Python interpreter, there are two ways of writing, the code to see below, the difference is the first one is to go directly to the directory you specify to find the Python interpreter, the second is to find the Python interpreter in the environment variable of your own configuration, and now create a new test.py python file

#!/usr/bin/python #这种写法是去/usr/bin directory to find the Python interpreter, if there is no Python interpreter in this directory or the Python interpreter in the other directory, will be error print (' Hello world! ') #!/usr/bin/env python# This is to go to the environment variable to find your configuration of the Python interpreter directory, in which directory you configure, it will go to the directory to find the Python interpreter print (' Hello world! ')
Below is the Linux run [[email protected] ~]# chmod +x test.py [[email protected] ~]#./test.py Hello world!

Seven, the first procedure, a solemn ceremony

When we were learning the language, the first program was definitely Hello World, and I don't know why, everybody did, and my teacher told me it was a ritual, so I thought it would be the same as worship. But regardless of it, to write the first program, it is very simple, Python syntax is simple, elegant, a print will be done.

Print ("Hello,world")

Eight. Variables

What do variables do? 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. The code is as follows:

name = ' Sriba '

New_name = Name#new_name is also the memory address of Sriba

Rules for defining variables:

Variable name to see the name to know, can not write, blind write to the back of their own can not understand what the variable is dry, do not use pinyin, so very low, not to use Chinese as a variable name, it is 2b programmers do, but Python can be used in Chinese as the variable name!

Variable names can only be any combination of letters, numbers, or underscores
The first character of a variable name cannot be a number
The following keywords cannot be declared as variable names

[' and ', ' as ', ' assert ', ' Break ', ' class ', ' Continue ', ' Def ', ' del ', ' elif ', ' Else ', ' except ', ' exec ', ' finally ', ' for ', ' From ', ' global ', ' if ', ' Import ', ' on ', ' is ', ' lambda ', ' no ', ' or ', ' pass ', ' print ', ' raise ', ' return ', ' try ', ' while ', ' With ', ' yield ']

Nine, 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, a single line comment, using #, the code is as follows:

msg = "I ' m sriba." #有单引号, so outside with double quotes info = ' Python comments ues ' # '. ' # #有双引号, so outside with single quotes new_msg = ' i ' m sriba, I love ' Python "." #有双引号和双引号, so the outside of the three quotation marks "'" Above the code is a description of single quotation marks, double quotes and three quotation marks of this paragraph is a comment, indicating that the three quotation marks also have a multi-line comment function ""

X. Input/Output

How does python receive user input, use the input function, use Raw_input in Python2, receive a string, output, the first program has been written using print, code into the following:

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 like this, do not want to let others see your password, how to do it, you need to use a standard library, Getpass, what is the standard library, is not need you to install, loaded Python on the library, is the standard library, Getpass is a standard library, import in, directly using the Getpass.getpass method can be entered at the time, do not echo, the code is as follows:
Import getpass #导入getpass模块 password = getpass.getpass (' Please enter your password: ') #接收输入的密码 Print (password)

Xi. Conditions of Judgment

The conditional judgment in Python uses if else to judge, multi-branch words using if elif ... else, that is, if how to do what, otherwise, how to do so, the format is as follows:

If it rains tomorrow:

Then bring the umbrella tomorrow.

Else

Not with an umbrella tomorrow.

Python is indented to represent the code block, so it seems that 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, all can also be considered to have the indentation is a parent-child relationship, write an example:

score = Int (input ("Enter your Score:")) #接收输入, because input receives a string, it needs to be cast to an integer type with an int function
If score = =: #如果成绩等于100分的话
Print ("You got a full score on the test")
Elif score >= and score<100: #如果成绩在90与100之间
Print (' Your score is not low, it's good ')
Elif score > Score <90: #如果成绩在60与90之间
Print ("Brother, this exam is so careless.")
else: #如果低于60分
Print ("Brother, you should be repeating!" ")

12. Circulation

What is the cycle is to do, the white is for you to repeat the thing, for example, you want to build 1000 folders, a build exhausted you, so you can write a section of 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, While loop before, first judge once, if the condition is met, then loop, for loop must have an iterative object, in order to loop, for example, there is 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, That is, the code below continue and break is not executed, in the following format:

While loop

While Count <10: #如果count小于10的话, execute the following code

    Print (count)
if count = = 5:#
break# if count=5, it ends the loop.
Count = count+1# Each cycle, count is added one, if not added, the condition has been true, the dead loop, has been continuously circulating
else: #这个else是可以不写的, meaning that if the condition is not satisfied, go to execute the following code
Print ("Condition not satisfied")
For loop
names = [' Marry ', ' haha ', ' hehe '] for name in Names:if name = = ' haha ': contiune #如果名字等于lily的话, do not execute cont Inue the following code, and then cycle the next print (name) Else: #for也有个else, but this is generally no one writes it, meaning if the normal cycle is done what print (' over ')

13, little practice, write a small game it

Since we have learned the conditions of judgment and circulation, then use it to practice exercises, write a small game, guess the number of games, the request is so, produce a random number, 1-100, receive user input, if guessed right, the game is over, guess big, hint guess big, small hint guess small. Generate random number module using Random.randint (1,101), is a standard package, the import can use, the code is as follows:

Import Random
num = Random.randint (1,101)
While True:
guess_num = Int (input ("Please enter an integer between 1-100:"))
If Guess_num >100 and Guess_num <1:
Print ("Please enter an integer between 1-100:")
Continue
Else
if guess_num = = num:
Print ("Congratulations, guess right!! 1 ")
Break
Elif Guess_num < num:
Print ("Guess small, guess small!!") ")
Continue
Else
Print ("Big guess, big guess!!") ")

14. 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:

Name = input (' Please enter your name: ') print (' Your name is ' +name ') #使用加号连接 print (' Your name is%s '%name) #使用占位符 print (' Your name is {your_name} '. forma    T (your_name=name)) #使用format格式化输出, the name inside {} can be written casually but be consistent with the name in the following format, and then write the variable you defined earlier to the equal sign. Age = Print (' My name is%s ' and I'm%d years old. ') % (name,age)) #这种是里面有多个格式化内容的, the front one is a string, the following is an integer, multiple variables followed by the value of the time must be added parentheses

Introduction to Python and Getting started

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.