Python Learning Notes (i):p Ython introduction and Getting Started

Source: Internet
Author: User
Tags sublime text

Recently began to learn Python, before also self-taught for a period of time Python, Python is a little understanding, this time to re-understand Python, but also when writing a small tutorial.
First, 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).
Ii. explanatory 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.
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 companies with Python2 rewrite the code is too laborious, so in the same year released the 2.6 transition version of Python, added a 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.
Iv. what kind of character set is a ghost?
Say the character set before, the first said 2 into the story, the computer compared silly only know 2, 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 provision of 8 bits for a byte, byte is a real world character of the most basic unit, For example, an English letter, a byte is 8 bits, which can save up to 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, representing 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, 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
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.
VI. Running 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 the way to go to the environment variable to find your configuration of the Python interpreter directory, you configure in which directory, it will go to which directory to find the Python interpreter    print (  'Hello world! ')
   Below is Linux under the Run    [[email protected]-32534 ~]# chmod +x test.py    [[email protected] -32534 ~]#./test.py    HelloWorld!

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! ')

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

' Sriba '  = name #new_name存的也是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','inch',' is','Lambda',' not','or','Pass','Print','Raise','return','Try',' while',' with','yield']

Nine, single quotes in Python, double quotes, and three quotation marks (that is, three single quotes)
Python, when you define a variable, the strings are enclosed in quotation marks, the single and double quotes are not different, and if there is a single quotation mark inside the string, then you use double quotes outside, Inside there are double quotes, the outside with single quotation marks, if there are both single and double, then use three quotation marks, three quotation marks can also be a multiline comment code, a single 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  "" Span style= "COLOR: #800000" >python   ".      #有双引号和双引号, so use the three quotes outside     

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 ('pleaseenter 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模块         = Getpass.getpass ('pleaseenter 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 tomorrow rain:            so tomorrow with an       umbrella Else:            Tomorrow without an umbrella

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:

Score =int(Input ('Please enter your score:') #接收输入, because input receives a string, you need to force the type to be converted to an integer type with the int functionifscore== -: #如果成绩等于100分的话 Print ('little Genius, you are full marks.') Elif score>= -< score -: #如果成绩大于等于90分小于100分的话 Print ('you don't have a low score, bro .') Elif score> -< score -: #如果成绩大于60分小于90分的话 Print ('brother, this exam is so sloppy.')                Else: #如果分数小于60分的话 Print ('Dude, what are you doing?')

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:

# whileLoop Count=0     whilecount<Ten: #如果count小于10的话, execute the following code, if it is not less than 3 go to else print (count)ifcount==5:                 Break#如果count等于5的话, just end the loop count+=1#这个意思是每次循环完, the value of Count is added one, if not added, the condition has been true, the cycle of death, has been constantly circulatingElse: #这个else是可以不写的, meaning, if the condition is not satisfied, what to do print ('Condition not satisfied')    # forcyclic names= ['Marry','Lily','Lilei']     forNameinchnames:ifName = ='Lily': Contiune #如果名字等于lily的话, do not execute continue 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, import and use, the code is as follows

Import Randomsub_str=random.randint (1,101) #生成1-a random number of 100 while 1: #while的意思就是, let it always be true, that is, the dead loop, the following break to stop the loop num=int(Input ('plase Enter a num, 1-100:'))    ifNum> -and num<1: #判断输入的数字是否在1-100 between print ('num error,plase enter 1-100.')        Continue    Else:        ifnum==sub_str: #如果猜对了, end loop print ('You win. Game over,the num is%d'%sub_str) #不懂这个的请看下面的第十四, string formatted output Breakelif Num<sub_str: #如果猜小了, just jump out of this loop and tip the print ('The num is small,plase enter other Num.')            Continue        Else: #就三种情况, big, small equals, the front two kinds is equal and light rain, then else is greater than, if guessed big, jump out of this cycle, prompted to guess the big print ('The num is too big,plase enter other Num.')            Continue

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}.'. Format (your_name=name))    #使用format格式化输出, the name inside {} can be written in the same way as 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 the age is%d.'%(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

Python Learning Notes (i):p Ython introduction and Getting Started

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.