Python Learning Path (Basic)--basic grammar Process Control

Source: Internet
Author: User

First, Hello World program

1, create a file under Linux called hello.py, and enter

Print ("Hello world!")

Then execute the command: Python hello.py, output

localhost:~ jieli$ vim hello.pylocalhost:~ jieli$ python hello.pyhello world!

2. Executed by Python interpreter

# !/usr/bin/env python  Print " Hello,world "

Execute:. /hello.py Can.

PS: Need to give hello.py execute permission before execution, chmod 755 hello.py

3. Directly call the Python's own interactive run code

localhost:~jieli$ Pythonpython2.7.10 (default, Oct 23 2015, 18:05:06) [GCC4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on Darwintype" Help","Copyright","credits" or "License"  forMore information.>>>Print("Hello world!") Hello world!

Second, the variable

1.

# _*_coding:utf-8_*_  "Tony"

The variable name is: Name, and the value of the variable name is: "Tony"

2 . 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 ']

Three, character encoding

Python generally uses utf-8

# !/usr/bin/env python # -*-coding:utf-8-*-  Print " Hello, World "

Iv. user Input

# !/usr/bin/env python # _*_coding:utf-8_*_  # name = Raw_input ("What's your Name?") #only on python 2.xname = input ('What'syour name? " )print("" + name)

When entering a password, if you want to be invisible, you need to take advantage of the Getpass method in the Getpass module, namely:

# !/usr/bin/env python # -*-coding:utf-8-*-  Import Getpass   # assign user input to the name variable pwd = Getpass.getpass (" Please enter password:")    #  Print the contents of the input print (PWD)

#input () after the default input character type, if you want to enter a number, you need an integer conversion int ()

V. Initial knowledge of the module

The power of Python is that he has a very rich and powerful library of standards and third-party libraries, and almost any feature you want to implement has the appropriate Python library support

Example 1 sys

# !/usr/bin/env python # -*-coding:utf-8-*- Import  Print(sys.argv)  # output $ python test.py helo world[  'test.py'helo' World' ]  # Gets the arguments passed when executing the script.

Example 2 OS

# !/usr/bin/env python # -*-coding:utf-8-*- Import os Os.system ("df-h"# call system command

Combine

Import Os,sys Os.system ("# ) give the user's input parameters as a command to Os.system to execute

Moreover, the xx.py module that you write can only be imported in the current directory, what if you want to use it anywhere in the system? At this point you have to put this xx.py in the Python Global environment variable directory, basically put in a directory called python/2.7/site-packages , this directory in different OS placed in the same location, with print (Sys.path) to see a list of Python environment variables.

Vi. What is PYC?

1. Explanatory and compiled languages

Computers are not able to recognize high-level languages, so when we run a high-level language program, we need a "translator" to engage in the process of translating high-level languages into machine languages that computers can read. This process is divided into two categories, the first of which is compilation, and the second is interpretation.

A compiled language before a program executes, the program executes a compilation process through the compiler, transforming the program into machine language. The runtime does not need to be translated and executes directly. The most typical example is the C language.

The explanatory language does not have this process of compiling, but rather, when the program is running, it interprets the program line by row, then runs directly, and the most typical example is Ruby.

Through the above example, we can summarize the advantages and disadvantages of the explanatory language and the compiled language, because the compiler language before the program has already made a "translation" of the program, so at run time there is less "translation" process, so the efficiency is higher. But we also can't generalize, some interpretive languages can also be optimized by the interpreter to optimize the whole program when translating the program, thus more efficiently than the compiled language.

In addition, with the rise of virtual machine-based languages such as Java, we cannot simply divide the language into two types-----explanatory and compiled.

In Java, for example, Java is first compiled into a bytecode file by a compiler and then interpreted as a machine file by the interpreter at run time. So we say that Java is a language that is compiled and interpreted first.

2.python Operating Process

The Python interpreter runs two times:

When the Python program runs, the result of the compilation is saved in the Pycodeobject in memory, and when the Python program finishes running, the Python interpreter writes Pycodeobject back to the PYc file.

When the Python program runs for the second time, the program will first look for the PYc file on the hard disk, and if it is found, load it directly or repeat the process.

So we should be able to locate Pycodeobject and pyc files, we say that PYc file is actually a kind of persistent saving way of pycodeobject.

Vii. initial knowledge of data types

1. Digital

2 is an example of an integer.
Long integers are just larger integers.
3.23 and 52.3E-4 are examples of floating-point numbers. The e tag represents a power of 10. Here, 52.3E-4 means 52.3 * 10-4.
( -5+4j) and (2.3-4.6j) are examples of complex numbers, where -5,4 is a real number, j is an imaginary number, and what is the plural in mathematics?

int (integral type)

On a 32-bit machine, the number of integers is 32 bits and the value range is -2**31~2**31-1, which is -2147483648~2147483647
On a 64-bit system, the number of integers is 64 bits and the value range is -2**63~2**63-1, which is -9223372036854775808~9223372036854775807long (Long integer)
Unlike the C language, Python's long integers do not refer to the positioning width, that is, Python does not limit the size of long integer values, but in fact, because of limited machine memory, we use a long integer value can not be infinite.
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.
Float (float type)        First Literacy http://www.cnblogs.com/alex3714/articles/5895848.html
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.
Complex (plural)
The complex number consists of real and imaginary parts, the general form is X+yj, where x is the real part of the complex, and Y is the imaginary part of the complex, where x and y are real numbers. Note: Small number pools exist in Python:-5 ~ 257 2, Boolean true or False 1 or 03, string
"Hello World"
string concatenation of all evils: the string in Python is embodied in the C language as a character array, each time you create a string, you need to open a contiguous space in memory, and once you need to modify the string, you need to open up again, the evil + sign every occurrence will re-open a space within. string concatenation print (' azx%s%d%f '% (s,d,f)) string is%s, integer%d, floating-point number%f string common functions:
    • Remove whitespace
    • Segmentation
    • Length
    • Index
    • Slice
4. List Creation List
Name_list = ['Alex'seven'Eric'  ] or name_list = List (['Alex'seven'  'Eric'])

Basic operation:

    • Index
    • Slice
    • Additional
    • Delete
    • Length
    • Slice
    • Cycle
    • Contains
5, tuples (immutable list)
Ages = (one,22, 33, 44, 55), and 11,

6. Dictionary (unordered)

person = {"name""mr.wu"'age': 18  = dict ({"name""mr.wu"'  Age ': 18})

Common operations:

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

VIII. Data Operations

Arithmetic operations:

Comparison operation:

Assignment operation:

Logical operation:

Member Operations:

Identity operation:

Bit operations:

Operation Priority:

Ix. If---Else

Scenario One: User Login

# 提示输入用户名和密码
# 验证用户名和密码 #     如果错误,则输出用户名或密码错误 #     如果成功,则输出 欢迎,XXX! #!/usr/bin/env python # -*- coding: encoding -*-   import getpass   name  = raw_input ( ‘请输入用户名:‘ ) pwd  = getpass.getpass( ‘请输入密码:‘ )   if name  = = "alex" and pwd  = = "cmd" :      print ( "欢迎,alex!" ) else :      print ( "用户名和密码错误" )

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/bin/env python#-*-coding:utf-8-*-My_age= 28User_input= Int (Input ("input your guess num:")) ifUser_input = =My_age:Print("Congratulations, you got it!")elifUser_input <My_age:Print("Oops,think bigger!")Else:    Print("Think smaller!")
Outer variables, which can be used by the inner layer code, should not be used by the outer code ten, for loop simple loop 10 times
# _*_coding:utf-8_*_ __author__ ' Alex Li '   for  in range:    print("loop:", i)

can also be used in conjunction with the IF

 for  in range    :if i<5:        continue# don't go down, Go directly to the next loop, and you can end the loopingloop    printwith a break ("loop:", i)

Xi. and while Loops

Dead loop

Count = 0 while True:    print(" You are the wind I am the sand, tangled up to the horizon ...  ", Count)    +=1

 

Python Learning Path (Basic)--basic grammar Process Control

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.