First: A beginner's knowledge of Python

Source: Internet
Author: User
Tags python script

Compiled vs. interpreted

Compiled
Advantages: The compiler generally has a pre-compilation process to optimize the code. Because the compilation is done only once, and no compilation is required at runtime, the program execution efficiency of the compiled language is high. Can run independently from the language environment.
Disadvantages: If you need to modify after compilation, you need to recompile the entire module. When compiling, the machine code is generated according to the corresponding operating environment. There will be problems in transplanting between different operating systems. Different executable files need to be compiled according to the operating system environment.

Interpretive
Advantages: good platform compatibility, can run in any environment, provided that an interpreter (virtual machine) is installed. Flexible, you can directly modify the code when you modify it, and it can be deployed quickly without downtime and maintenance.

Disadvantages: It must be explained every time it is run, and its performance is not as good as that of compiled languages.

Note: The java code is said to run once compiled, because the java agent needs to be compiled into bytecode (a kind of intermediate format code), and then the bytecode is run everywhere. Can only be executed after the instruction, so java is mixed

And some people will have doubts. Python code is first compiled into bytecode and then handed over to the Python interpreter for execution. Isn't Python mixed? of course not

1. First of all, you need to know that the pyc bytecode file will be generated only when the py file is imported by import. The bytecode file can be directly executed instead of the source file.

2. But every time the py file is executed, the generated bytecode will not be retained, that is to say, every time the py file is executed, it is necessary to go through it again: py file-> bytecode-> python interpreter -> Machine code, every time is a process of re-interpretation and execution.

3.4 Why choose Python
This fucking need to ask, you have seen TMD so much, also TMD asked this kind of question?

C and Python, Java, C #, etc.

    C language: The machine code is compiled by the code, the machine code is directly executed on the processor, and each instruction controls the CPU

Other languages: The code is compiled to byte code, the virtual machine executes the byte code and converts it into machine code, and then executes it on the processor

CPython interpreter is developed by C language

For use: Python's library is complete and simple to use, if you want to achieve the same function, Python 10 lines of code can be solved, C may need 100 lines or more.
For speed: Python runs faster than C, and it is definitely slower

Python and Java, C #, etc.

For use: Linux original Python, other languages are not available; the above several languages have very rich class library support
For speed: Python may be slightly inferior in speed

1. Speed is never the key

For most applications, it doesn't need to run so fast, because users simply can't feel it. For example, to develop a web application to download MP3, the running time of C program needs 0.001 seconds, and the running time of Python program needs 0.1 seconds, which is 100 times slower, but because the network is slower, you need to wait for 1 second, you think, users can Do you feel the difference between 1.001 seconds and 1.1 seconds? This is the same as F1 racing and ordinary taxis driving on the Third Ring Road in Beijing. Although the theoretical speed of the F1 car is up to 400 kilometers per hour, because the traffic speed of the Third Ring Road is only 20 kilometers per hour, so as a passenger, you feel the speed It is always 20 kilometers.

2. Encryption is not the key

For compiled languages such as C, the compiled code can be sent to the user, and it is almost impossible for the user to reverse the solution, which is equivalent to having its own encryption function. An interpreted language such as python can only publish source code to users, but in fact this is no problem. Now the mainstream thinking is software open source, don't mind how big your software is for commercial value.

3.5 Types of Python interpreters
Python is a language. The code written in this language needs to be interpreted and executed by the Python interpreter. The interpreters are classified as follows:

Cpython (the most commonly used version)
    The official version of Python is implemented in C language, which is the most widely used. The CPython implementation will convert the source file (py file) into a bytecode file (pyc file) and then run it on the Python virtual machine.
Jyhton
    The Java implementation of Python, Jython will dynamically compile Python code into Java bytecode and then run it on the JVM.
IronPython
    Python's C # implementation, IronPython compiles Python code into C # bytecode, and then runs it on the CLR. (Similar to Jython)
PyPy (Special)
    Python, implemented in Python, compiles Python's bytecode bytecode into machine code.
RubyPython, Brython ...
In addition to PyPy, the corresponding relationship and execution process of other Python are as follows:



 PyPy, further processing Python's bytecode on the basis of Python, thereby improving execution speed!

 

3.6 Development history of Python interpreter
In 1989, in order to pass the Christmas holiday, Guido began to write a compiler for the Python language. The name Python comes from Guido's beloved TV series Monty Python ’s Flying Circus. He hopes that this new language called Python will meet his ideals: create a language between C and shell that is comprehensive, easy to learn, easy to use, and extensible.
In 1991, the first Python compiler was born. It is implemented in C language and can call C language library files. Since its birth, Python has had: classes, functions, exception handling, core data types including tables and dictionaries, and module-based expansion systems.
Granddaddy of Python web frameworks, Zope 1 was released in 1999
Python 1.0-January 1994 added lambda, map, filter and reduce.
Python 2.0-October 16, 2000, adding a memory recycling mechanism, which forms the basis of the current Python language framework
Python 2.4-November 30, 2004, the most popular WEB framework Django was born in the same year
Python 2.5-September 19, 2006
Python 2.6-October 1, 2008
Python 2.7-July 3, 2010
In November 2014, it was announced that Python 2.7 would be supported until 2020, and reaffirmed that there would be no 2.8 release as users were expected to move to Python 3.4+ as soon as possible
Python 3.0-December 3, 2008
Python 3.1-June 27, 2009
Python 3.2-February 20, 2011
Python 3.3-September 29, 2012
Python 3.4-March 16, 2014
Python 3.5-September 13, 2015
Four Python environment
Note: Setting of environment variables

windows:

1
2
3
4
5
6
7
1. Download the installation package
    https://www.python.org/downloads/
2. Installation
    Default installation path: C: \ python27
3. Configure environment variables
    [Right-click computer]-"[Properties]-" [Advanced System Settings]-"[Advanced]-" [Environment Variables]-"[In the second content box, find the line with the variable name Path Double-click]-> [Python installation directory and the Scripts directory under the installation directory are added to the variable value, use; split]
    Such as: the original value; C: \ python27, remember to have a semicolon in front
linux:

1
2
3
No installation required, original Python environment
  
ps: If you bring 2.6, please update to 2.7
Update Python

windows:

1
Just uninstall and reinstall
linux:

Linux yum relies on its own Python, in order to prevent errors, the update here is actually to install another Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
View default Python version
python -V
  
1. Install gcc to compile Python source code
    yum install gcc
2. Download the source package, https://www.python.org/ftp/python/
3. Unzip and enter the source code file
4. Compile and install
    ./configure
    make all
    make install
5. View version
    /usr/local/bin/python2.7 -V
6. Modify the default Python version
    mv / usr / bin / python /usr/bin/python2.6
    ln -s /usr/local/bin/python2.7 / usr / bin / python
7. Prevent yum from executing abnormally and modify the Python version used by yum
    vi / usr / bin / yum
    Change the head #! / Usr / bin / python to #! / Usr / bin / python2.6
Five Getting started with Python
5.1 The first sentence of python code
1. Interpreter: Debug code on the fly, the code cannot be saved permanently

2. File: permanently save the code


Create a new file hello.py in the D: \ python_test \ directory and write the code as follows

print ('hello world')
Execute hello.py, which is python D: \ python_test \ hello.py

The internal execution process of Python is as follows:



 

When executing python D: \ python_test \ hello.py in the previous step, it is clearly pointed out that the hello.py script is executed by the Python interpreter.

If you want to execute a python script similar to a shell script on the Linux platform, for example: ./hello.py, then you need to specify the interpreter at the head of the hello.py file, as follows:

#! / usr / bin / env python #This line is only valid for linux

print ('hello world')
 

ps: hello.py execution permission must be given before execution, chmod 755 hello.py

5.2 File header
#! / usr / bin / env python
#-*-coding: utf-8-*-
5.3 Notes
Watching on line: # Contents being annotated

Multi-line comment: "" "The commented content" ""

5.4 Passing parameters into the execution script
Python has a large number of modules, which makes developing Python programs very simple. The class library includes three:

Modules provided inside Python
Open source modules in the industry
Modules developed by programmers
Python provides a sys module internally, where sys.argv is used to capture the parameters passed when executing the python script

1
2
3
4
5
6
#! / usr / bin / env python
#-*-coding: utf-8-*-
  
import sys
  
print sys.argv
carried out

C: \ Users \ Administrator> python D: \ python_test \ hello.py arg1 arg2 arg3
['D: \\ python_test \\ hello.py', 'arg1', 'arg2', 'arg3']
 

5.5 Understanding pyc files
When executing Python code, if other .py files are imported, a .pyc file with the same name will be automatically generated during execution. This file is the bytecode generated by the Python interpreter after compilation.

ps: The bytecode can be generated after the code is compiled; the bytecode can also be obtained by decompilation.

Six variables
6.1 Why there are variables
The essence of program execution is a series of state changes. The core of the variable word is one of change and the other is quantity. The “change” corresponds to the change of the program.

For example, the initial level of characters in a game: level = 1, after a period of time to upgrade: level = 10

6.2 Variable declaration and reference
#! / usr / bin / env python

name = 'egon' #Declaration of variables
name #Reference variable value by variable name
print (name) #Reference and print the value corresponding to the variable name name, ie 'egon'
6.3 Identifier command specification:
Variable names can only be letters, numbers or underscores  random combination
The first character of the 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 ',' in ',' is', 'lambda', 'not', 'or', 'pass',' print ' , 'raise', 'return', 'try', 'while', 'with', 'yield']
back to the top
6.4 Assignment of variables
#! / usr / bin / env python

name1 = 'lhf'
name2 = 'egon'


#! / usr / bin / env python

name1 = 'lhf'
name2 = name1
 



 

 

Copy code
Copy code
#! / usr / bin / env python

#The level of a game character is increased from 1 to 2
level = 1
level = 2

#The password of a game account is changed from '123' to '456'
passwd = '123'
passwd = '456'

# One's name has 'lhf' changed to 'egon'
name = 'lhf'
name = 'egon'
Copy code
Copy code
back to the top
Seven input and output
The input in python3 is unified, the input of raw_input in python2 is equivalent to the input of python3, and the input in python2

1.res = input ("python3:")

2.res = raw_input ("python2:")

3.res = raw_input ("python2:")

1, 2 no matter what kind of input it receives, it will be stored as a string and assigned to res, and 3 means that whatever type the user enters, it will be assigned to res in whatever type

#! / usr / bin / env python

name = input ('Please enter user name:')
print (name)
carried out

C: \ Users \ Administrator> python D: \ python_test \ hello.py
Please enter username: egon
egon
================================================== =============================

When entering the password, if you want to be invisible, you need to use the getpass method in the getpass module, namely:

#! / usr / bin / env python

import getpass
password = getpass.getpass ('Please enter the password:')
print (password)
Execution (cannot be executed in pycharm, need to execute in the terminal)

C: \ Users \ Administrator> python D: \ python_test \ hello.py
Please enter the password:
123456
back to the top
Eight simple operators
Arithmetic operation; logical operation; comparison operation; relational operation;

back to the top
Nine process control
back to the top
9.1 Conditional statements
1 single branch

2 Multi-branch

Requirement 1. User login verification

Copy code
Copy code
#! / usr / bin / env python

name = input ('Please enter the user name:')
password = input ('Please enter password:')

if name == 'egon' and password == '123':
    print ('egon login success')
else:
    print ('Wrong username or password')
Copy code
Copy code
 

Demand two, according to the user input content output its authority

Copy code
Copy code
#! / usr / bin / env python
#Print its permissions based on user input

'' '
egon-> super administrator
tom-> Ordinary administrator
jack, rain-> business supervisor
Other-> Ordinary users
'' '
name = input ('Please enter the user name:')

if name == 'egon':
    print ('Super Administrator')
elif name == 'tom':
    print ('Ordinary administrator')
elif name == 'jack' or name == 'rain':
    print ('Business Supervisor')
else:
    print ('Ordinary user')
Copy code
Copy code
back to the top
9.2 Loop statement
while loop

1. Basic cycle

while condition:
     
    # Loop body
 
    # If the condition is true, then the loop body is executed
    # If the condition is false, then the loop body is not executed
 

 

 

2, break

break is used to exit this loop

while True:
    print "123"
    break
    print "456"
3.continue

continue is used to exit this loop and continue to the next loop

while True:
    print "123"
    continue
    print "456"
 

4 tag

#! / usr / bin / env python
# _ * _ coding: utf-8 _ * _

# while True:
# username = input ('username:')
# password = input ('password:')
# if username == 'egon' and password == '123':
# while True:
# cmd = input ('>>:')
# if cmd == 'q':
# break
# print ('------>% s'% cmd)
# break
tag = True
while tag:
username = input ('username:')
password = input ('password:')
if username == 'egon' and password == '123':
while tag:
cmd = input ('>>:')
if cmd == 'q':
tag = False
continue
print ('------>% s'% cmd)

for loop

for i in range (1,10):
    for j in range (1, i + 1):
        print ('% s *% s =% s'% (i, j, i * j), end = '')
    print ()

Ten exercises in this section
1. Use a while loop to output 1 2 3 4 5 6 8 9 10

2. Find the sum of all numbers from 1-100

3. Output all odd numbers within 1-100

4. Output all even numbers within 1-100

5. Find the sum of all numbers from 1-2 + 3-4 + 5 ... 99

6. User login (three opportunities to retry)

# question 1
count = 1
while count <= 10:
if count == 7:
count + = 1
continue
print (count)
count + = 1
count = 1
while count <= 10:
if count! = 7:
print (count)
count + = 1
# question 2
res = 0
count = 1
while count <= 100:
res + = count
count + = 1
print (res)

# question 3
count = 1
while count <= 100:
if count% 2! = 0:
print (count)
count + = 1

# question 4
count = 1
while count <= 100:
if count% 2 == 0:
print (count)
count + = 1



#question 5
res = 0
count = 1
while count <= 5:
if count% 2 == 0:
res- = count
else:
res + = count
count + = 1
print (res)
# question 6
count = 0
while count <3:
name = input ('Please enter user name:')
password = input ('Please enter password:')
if name == 'egon' and password == '123':
print ('login success')
break
else:
print ('Wrong username or password')
count + = 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.