Python's Path to self-study: Python Basics (i)

Source: Internet
Author: User
Tags loop case

The compiler compiles each statement of the source program into a machine language and saves it as a binary file so that the computer can run the program directly in machine language at a very fast speed.

And the interpreter is only in the execution of the program, only one interpretation of the machine language to the computer to execute, so the speed is not as fast as the compiled program to run.

This is because the computer does not directly recognize and execute the statements we write, it only knows the machine language (in binary form)

What are the pros and cons of a compiled and interpreted type?

Compiled type
Pros: Compilers typically have pre-compiled procedures to optimize code. Because the compilation is done only once, the runtime does not need to compile, so the program execution of the compiled language is highly efficient. Can run independently from the language environment.
Cons: After compilation, the entire module needs to be recompiled if modifications are required. When compiling the machine code according to the corresponding running environment, porting between different operating systems will be problematic, and you need to compile different executables according to the operating system environment you are running.

Explanatory type
Pros: Good platform compatibility, can be run in any environment, provided the interpreter (virtual machine) is installed. Flexible, modify the code when the direct modification can be quickly deployed, without downtime maintenance.

Cons: Every time you run, you have to explain it again, performance is not as good as the compiled language.

Finally, let's take a look at Python Advantages and Disadvantages:

See the pros first

    1. Python's positioning is "elegant", "clear", "simple", so the Python program looks always easy to understand, beginners learn python, not only easy to get started, but also in the future, you can write those very very complex programs.
    2. Development efficiency is very high, Python has a very powerful third-party library, basically you want to achieve any function through the computer, the Python official library has the corresponding modules to support, directly download the call, on the basis of the base library to develop, greatly reduce the development cycle, to avoid repeating the wheel.
    3. High-level language ———— when you write programs in the Python language, you don't have to consider the underlying details such as how to manage the memory used by your program
    4. Portability ———— because of its open source nature, Python has been ported on many platforms (modified to make it work on different platforms). If you are careful to avoid using system-dependent features, all your Python programs can run on almost any system platform on the market without modification
    5. Scalability ———— If you need a piece of your critical code to run faster or you want some algorithms to be private, you can write some of your programs in C or C + + and then use them in your Python program.
    6. Embeddable ———— You can embed python into your C + + program to provide scripting functionality to your program users.

Look at the disadvantages again:

    1. Slow, Python runs faster than the C language, and slower than Java, so this is the main reason why many so-called Daniel disdain to use Python, but in fact, this refers to the speed of slow in most cases the user is not directly aware of, Must rely on the use of testing tools to reflect, such as you use C a program to spend 0.01s, Python is 0.1s, so c directly than Python 10 times times faster, is very exaggerated, but you can not directly perceive through the naked eye, Because a normal person can perceive the smallest unit of time is 0.15-0.4s around, haha. In fact, in most cases python has been fully able to meet your requirements for the speed of the program, unless you want to write to the speed of the most demanding search engine, in this case, of course, it is recommended that you use C to achieve.
    2. Code can not be encrypted, because Python is an explanatory language, its source code is stored in the form of a name, but I do not think this is a disadvantage, if your project requires that the source codes must be encrypted, then you should not use Python in the beginning to implement.
    3. Threads do not take advantage of multi-CPU problems, which is one of the most common drawbacks of Python, the Gil, the Global Interpreter lock (interpreter lock), is a tool that the computer programming language interpreter uses to synchronize threads so that only one thread executes at any moment, The python thread is the native thread of the operating system. On Linux for Pthread, on Windows for win thread, the execution of threads is fully dispatched by the operating system. A Python interpreter process has a main thread and the execution thread for multiple user programs. Multi-threaded parallel execution is prohibited even on multicore CPU platforms due to the existence of the Gil. A compromise solution to this problem is discussed in more detail later in the Threads and Processes section.

In fact, for any language is not perfect, casual, and the advantages and disadvantages of various languages, we should give full play to their strengths, rather than blindly compare, to do the conflict!!!

Python history
  • In 1989, in order to pass the Christmas holiday, Guido began to write the Python language compiler. The name Python, from Guido's beloved TV show Monty Python's Flying Circus. He hoped that the new language, called Python, would fit his ideals: create a language that is all-powerful, easy to learn, easy to use, and extensible, between C and Shell.
  • 1991, the first Python compiler was born. It is implemented in C language and can call the C language library file. From birth, Python already has: classes, functions, exception handling, core data types including tables and dictionaries, and module-based expansion systems.
  • Granddaddy of Python Web frameworks, Zope 1 is released in 1999
  • Python 1.0-january 1994 adds lambda, map, filter and reduce.
  • Python 2.0-october 16, 2000, added a memory recovery mechanism that forms the basis of the Python language framework Now
  • Python 2.4-november 30, 2004, the same year now the most popular web framework Django was born
  • Python 2.5-september 19, 2006
  • Python 2.6-october 1, 2008
  • Python 2.7-july 3, 2010
  • In November, it is announced that Python 2.7 would is supported until 2020, and reaffirmed that there would is 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

Speaking of which, there is not a bit of Python code, don't worry, do some understanding first. For knowledge, the more the more it ~ ~ ~

Well, no more nonsense, let's take a look at the most solemn "ritual"----"Hello world! "Right

For Python2.7 and python3.x exist different, can in the process of learning a little to know, also can go to see the official introduction!

I'm here to get the 3.x version. The editor is pycharm.

Print ("Hello World")

  

In fact, in version 2.7, print does not need to do parentheses, but in the 3 version, will not add to the error ~ ~

declaring Variables
#-*-coding:utf-8-*-"" "in the 3.x version, the default Utf-8" "" "name =" Xiaoming "

The code above declares a variable named: Name, and the value of the variable name is: "Xiaoming"

Rules for variable definitions:

    • 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 ', ' F ' Rom ', ' Global ', ' if ', ' import ', ' in ', ' was ', ' lambda ', ' not ', ' or ', ' pass ', ' print ', ' raise ', ' return ', ' try ', ' while ', ' WI Th ', ' yield ']

Assigning values to variables

#-*-Coding:utf-8-*-name = "Mr, Zhang" name2 = Nameprint ("My name is", name) name = "Maomao" Print (name,name2)

Its printing results can be seen, the assignment of name to Name2,name redefined, and does not affect the value of name2, the value of name2 points to the value pointed to by name, not name!!

To implement user input:

#__Author__: Mr_zhangname = input ("Enter Name:") Age = Input ("Enter Age:") Tob = input ("Please enter Tob:") Salary = input ("Please enter Salary:") info = "" "----------info of%s----------name:%sage:%stob:%ssalary:%s" ""% (name,name,age,tob,salary) Info2 = ""------- ---info of {_name}----------Name:{_name}age:{_age}tob:{_tob}salary:{_salary} "" ". Format (_name=name,            _name = Name,            _age = age,            _tob=tob,            _salary = Salary) Info3 = "" "----------info of {0}----------Name:{0}age:{1}tob: {2} SALARY:{3} "" ". Format (name, name, age,tob,salary) print (info)

  

In fact, here, both know the input, have learned the format of the output of several ways! But the results are the same.

Next, let's write a fun, let's learn a new point of knowledge:

#__Author__: Mr_zhangimport getpass_username = "admin" _password = "admin" name = input ("Please enter the name:") # password = Getpass.getpass ("Please enter the password:")  #getpass模块, is the user at the time of input password, the plaintext encryption, does not display clear text password = input (" Please enter the password: ") if _username = = name and _password==password:    print (" Welcome user{name} login ... ". Format (Name=name)) else:    print ("Invalid username or password") print (Name,password)

  

Actually see here, we not only have an interesting code to write, also learned the IF condition statement syntax, actually very can see, in this program, is a very simple login program!! Of course, in reality there are still more in the situation to judge, then then again ~ ~ ~ Now the main thing is to know, understand

After looking at the IF condition statement, let's get to know another loop: while

#__Author__: Mr_zhanglaozhang = 60i = 0while i<3: Age    = Int (Input ("The Age of: ')")    if Age = = Laozhang:        print ( "Yes,you got it.")        Break    elif Age>laozhang:        print ("no,the")    elif Age <laozhang:        print ("No,the ")    I+=1else:    print (" You have try too many Time....bye!!! ")

In fact, this is a small game, is to guess the age! In the program, if you guess the wrong 3 times, you will quit the program! So let's change the wording, and by the way, recognize another loop: for

#__Author__: Mr_zhanglaozhang = 60for i in range (3): Age    = Int (Input ("The Age of: ')") if age =    = Laozhang:        pri NT ("Yes,you got it.")        Break    Elif Age > Laozhang:        print ("no,the")    Elif Age < laozhang:        print ("No,the Age I S low ")    i + = 1else:    print (" You have try too many Time....bye!!! ")

If you don't understand the for-loop case here, let's write a simple and straightforward one:

#-*-coding:utf-8-*-#__Author__: mr_zhangfor i in range:    print (i) for I in Range (0,10,2):    print (i)

Not hard to see. For loop, range (start value, end value, step)

In fact, this method and the above method, the wording above different, run up is the same, see here, do not know if there are no friends found, I write while and for the time, all use the else, here is not strange, is possible, not only if and else to match Oh ~ ~ ~

Or this game, let us change the rules, that is, after 3 consecutive guesses, do not let him quit directly, but to do a query, if you answer Y, then continue to guess, if n, the complete end, the introduction of the loop:

#__Author__: Mr_zhanglaozhang = 60i = 0while i<3: Age    = Int (Input ("The Age of: ')")    if Age = = Laozhang:        print ( "Yes,you got it.")        Break    elif Age>laozhang:        print ("no,the")    elif Age <laozhang:        print ("No,the ")    i+=1    if i = = 3:        res = input (" Does  want you keep guessing ... (y/n) "," #回车继续        if res! = "N":            i = 0

  

In fact, here I need to add a knowledge point, that is break

The Python break statement, like in the C language, breaks the minimum enclosing for or while loop.

The break statement terminates the Loop statement, that is, the loop condition does not have a false condition, or the sequence is not fully recursive, and the loop statement is stopped.

The break statement is used in the while and for loops.

If you use a nested loop, the break statement stops executing the deepest loop and starts executing the next line of code.

In fact, some people will not understand, do not understand it does not matter, we have to write a case to see what this sentence means ~

#-*-coding:utf-8-*-#__Author__: mr_zhangfor i in range (0,10,2):    print ("*" *10,i) for    J in range:        if j& Gt;5:            break        Else:            print (j)

  

In two nested loops, the internal loop uses a break, the result is only affecting the internal loop, for the outer loop has no effect, so who, break out of the current loop body, then, here, some programming knowledge people will think of Contine, So how does this actually carry out, in fact, in the step execution program when the most clear, continue is to jump out of this cycle, start the next cycle, the impact is just continue behind the operation, you can write a program to run a look!!

This study will first come here, Tiandaochouqin, have to pay, will have to report! A self-study tour of Python. It won't stop! Friends if there is any good resources, hope can be shared, study together, explore, grow together!! Python initiator, caught dead here.

Python's Path to self-study: Python Basics (i)

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.