First article: Python Foundation _1

Source: Internet
Author: User

The content of this article
    1. Python Introduction
    2. Installation
    3. First Program (Hello,world)
    4. Variable
    5. User inputs (input)
    6. Data type
    7. Data operations
    8. If judgment
    9. The difference between break and continue
    10. While loop

First, Python introduction

The founder of Python is Guido van Rossum. During the Christmas of 1989, in Amsterdam, Guido was determined to develop a new script interpreter as an inheritance of the ABC language in order to get rid of the boredom of Christmas. Python was chosen as the name of the programming language because he was a fan of the comedy community called Monty Python.

June 2017 Tiobe programming language rankings:

By visible, Python language usage is on the rise, while the top three language usage is trending down.

Python the pros and cons

Advantages:

    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.

Disadvantages:

    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.

Second, Python installs Windows
1. Download installation package HTTPS://WWW.PYTHON.ORG/DOWNLOADS/2, install and install in C:\Python363, configure environment variable "right-click Computer"-"attribute"-"Advanced system Settings"-"Advanced"-"environment variable"--" In the second content box, find a row with the variable named path, double-click the Python installation directory to append to the variable value, and split the
Linux:
1. Unzip the tar XF python-3.6.2.tgz2. Compiling the installation CD Python-3.6.2./configure--prefix=/usr/local/python3.6makemake Install3. Configuring environment Variables Vim/etc/profilepath=/usr/local/python3.6/bin: $PATHsource/etc/profile4. Test python3.6

Third, the first procedure (Hello,world)

Open Pycharm, create a new Python project, and create a new Python file.

#!/usr/binl/env python#encoding:utf-8#author:yangleiprint ("Hello,world")

Iv. variables

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. In an instruction language, variables are usually mutable, but in a purely functional language (such as Haskell), variables may be immutable (immutable). In some languages, variables can be explicitly defined as abstractions that can represent mutable states, with storage space, such as in Java and Visual Basic, but others may use other concepts, such as objects in C, to refer to this abstraction without strictly defining the exact extension of the "variable".

declaring variables

#!/usr/binl/env python#encoding:utf-8#author:yangleiname = "Yanglei" Print (name)

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

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 ', ' final ' Ly ', ' for ', ' from ', ' global ', ' if ', ' import ', ' in ', ' was ', ' lambda ', ' not ', ' or ', ' pass ', ' print ', ' raise ', ' return ', ' Try ' , ' while ', ' with ', ' yield ']

Five, user input
#!/usr/binl/env python#encoding:utf-8#author:yangleiinput_name = input ("Please enter your name:") print ("hi,%s"% input _name)

Vi. Types of data

1. Digital

int (integral type)

On a 32-bit machine, the number of integers is 32 bits, the value range is -2**31~2**31-1, that is, -2147483648~2147483647 on a 64-bit system, the number of digits of the integer is 64 bits, the value range is -2**63~2** 63-1, that is, -9223372036854775808~9223372036854775807long (Long Integer) is different from the C language, Python's long integer does not refer to the positioning width, that is: Python does not limit the size of long integer values,     But in fact, because of the limited machine memory, we use a long integer value can not be infinitely large. Note that, since Python2.2, Python automatically converts integer data to long integers if an integer overflows, so it does not cause any serious consequences if you do not add the letter L after long integer data.Note: There is no longer a long type in Python3, all intFloat (float type)     a floating-point number is used to process real numbers, which are numbers with decimals. Similar to the double type in C, accounting for 8 bytes (64 bits), where 52 bits represent the bottom, 11 bits represent the exponent, and the remaining one represents the symbol.  2. Boolean value TRUE or False 1 or 03, string
"Hello World"

string concatenation:

The string in Python is represented in the C language as a character array, and each time a string is created, it needs to open a contiguous space in memory, and once you need to modify the string, you need to make room again, and the Evil + sign will re-open up a space within each occurrence. String Formatted output
#!/usr/binl/env python#encoding:utf-8#author:yangleiname = "Yanglei" Print ("hi,%s"% name) #输出hi, Yanglei

Note: the string is%s; integer%d; floating-point number%f

String Common functions:
    • Remove whitespace
    • Segmentation
    • Length
    • Index
    • Slice
4. List Creation list:
#!/usr/binl/env python#encoding:utf-8#author:yangleiname = ["Yanglei", "Jack", "Marry", "Andy"]

Basic operation:

    • Index
    • Slice
    • Additional
    • Delete
    • Length
    • Slice
    • Cycle
    • Contains

5. Dictionary (unordered)

To create a dictionary:
#!/usr/binl/env python#encoding:utf-8#author:yangleiuser_info = {"Name": "Yanglei", "Age": $, "job": "IT"}

Common operations:

    • Index
    • New
    • Delete
    • Key, value, key-value pairs
    • Cycle
    • Length

VII. Data OperationsArithmetic operations:

Comparison operation:

Assignment operation:

Logical operation:

Member Operations:

Identity operation:

Bit operations:

Operator Precedence:

  

Viii. If judgment

Scenario One, user login verification

#!/usr/binl/env Python#encoding:utf-8#author:yangleiinput_user = input ("Please enter your user name:") Input_password = Input ("Please enter your password:") if Input_user = = "Yanglei" and Input_password = "123456":    print ("\033[32;1m%s l Ogin successfully\33[0m "% input_user) Else:    print (" \033[31;1mthe user name or password error,please try Again\033[0m ")

Scenario two, Guess age game

Set your age in the program, and then start the program to let the user guess, after the user input, according to his input prompts the user to enter the correct, if the error, the hint is guessed big or small

#!/usr/binl/env python#encoding:utf-8#author:yangleiguess_age = 50input_age = Int (input ("Please enter your guess Age:") If Input_age > Guess_age:    print ("\033[31;1mcan You guess what big\33[0m") Elif Input_age < guess_age:    Print ("\033[31;1mcan You guess what small\33[0m") Else:    print ("\033[32;1myou guessed it\33[0m")

Outer variables, which can be used by the inner layer code

Inner variables, should not be used by the outer code the difference between the nine, break, and continue Continue:
#!/usr/binl/env Python#encoding:utf-8#author:yangleicount = 1while count <=:    if Count = = 5:        count + = 1
   
    continue    Print (count)    count + = 1
   
Break
#!/usr/binl/env Python#encoding:utf-8#author:yangleicount = 1while count <=:    if Count = = 5:        count + = 1
   break    Print (count)    count + = 1

From this we can see that continue is jumping out of the current loop, and break is jumping out of this layer loop.

Ten, while loop Loop statement, a basic cycle mode of the computer. When the condition is met, it enters the loop and does not meet the jump. The general expression for the while statement is: while (expression) {loop body}

Scenario One, user login verification Upgrade

#!/usr/bin/env Pyhon#encoding:utf-8#auth:yangleicount = 0while Count < 3:    Input_user = input ("Please enter your U Ser name: ")    Input_password = input (" Please enter your password: ")    if Input_user = =" Yanglei "and Input_password = = "123456":        print ("\033[32;1m%s login successfully\33[0m"% input_user) break    elif count = = 2:        print ( "\033[31;1mthe user name or password Mistake,three chances to use Up,the program exits\33[0m")        break    else:        Co UNT + = 1        print ("\033[31;1mthe user name or password error,please try again\033[0m")

Scenario two, Guess age game upgrade

#!/usr/bin/env pyhon#encoding:utf-8#auth:yangleiguess_age = 50count = 0while count <= 3:    if Count = = 3:        input _choose = input ("Does want to continue to play?" ( Y or y| n or N) ")        if input_choose = =" Y "or input_choose = =" Y ":            count = 0            Continue        elif input_choose = =" n "or in Put_choose = = "n": Break        Else:            print ("\033[31;1mare you input errors!\33[0m")            continue    Input_ age = Int (input ("Please enter your guess Age:"))    if Input_age > Guess_age:        print ("\033[31;1mcan You guess wh At big\33[0m ")        count + = 1    elif input_age < guess_age:        print (" \033[31;1mcan You guess what small\33[0m " )        count + = 1    else:        print ("\033[32;1myou guessed it\33[0m")        break

First article: Python Foundation _1

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.