(ii), Python Foundation

Source: Internet
Author: User
Tags python script

Getting Started with Python

One, the first sentence of Python

Create the hello.py file under the/home/dev/directory, as follows:

print "hello,world"

Execute the hello.py file, i.e.:python /home/dev/hello.py

The python internal execution process is as follows:

The suffix name of the Python file can be arbitrary, but when the module needs to be imported, if it is not the file at the end of the. PY, it will be error-free, so write the file at the end of the. Py.

Second, the Interpreter

When executing python/home/dev/hello.py in the previous step, it is clear that the hello.py script is executed by the Python interpreter.

If you want to execute a python script like executing a shell script, for example, you ./hello.py  would need to specify the interpreter at the head of the hello.py file, as follows:

#!/usr/bin/env python# print "hello,world"

So, execute:. /hello.py Can.

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

Third, the Code

The Python interpreter encodes the content when it loads the code in the. py file.

Note: Python3 default utf-8, python2 default is ASCII

ASCII (American Standard Code for Information interchange, United States Standards Information Interchange Code) is a set of computer coding systems based on the Latin alphabet, mainly used to display modern English and other Western European languages, which can be used up to 8 Bit to represent (one byte), that is: 2**8 = 256, so the ASCII code can only represent a maximum of 256 symbols.

It is clear that the ASCII code cannot represent all the words and symbols in the world, so it is necessary to create a new encoding that can represent all the characters and symbols, namely: Unicode

Unicode (Uniform Code, universal Code, single code) is a character encoding used on a computer. Unicode is created to address the limitations of the traditional character encoding scheme, which sets a uniform and unique binary encoding for each character in each language, which specifies that characters and symbols are represented by at least 16 bits (2 bytes), that is: 2 **16 = 65536,
Note: Here is a minimum of 2 bytes , possibly more

gbk,gb2312, only available in China, support traditional, Chinese requires 2 byte representation

UTF-8, which is compression and optimization of Unicode encoding, does not use a minimum of 2 bytes, but instead classifies all characters and symbols: the contents of the ASCII code are saved with 1 bytes, the characters in Europe are saved in 2 bytes, and the characters in East Asia are saved in 3 bytes ...

Therefore, in writing code, in order not to appear garbled, recommended to use UTF-8, will add #-*-Coding:utf-8-*-

That

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

Python3 no concern
Python2 each file appears in Chinese, the head must be added

Iv. notes

When the line stares: # is annotated content

Multiline Comment: "" "Annotated Content" ""

V. Execute script incoming parameters

Python has a large number of modules, which makes developing Python programs very concise. The class library includes three:

    • Python-supplied modules
    • Industry-Open Source modules
    • Modules developed by programmers themselves

Python internally provides a SYS module where SYS.ARGV is used to capture parameters passed in when executing a python script

# !/usr/bin/env python # -*-coding:utf-8-*-  Import SYS   Print sys.argv

Vi.. pyc file

When you execute Python code, if you import a different. py file, a. pyc file with the same name is automatically generated during execution, which is the bytecode generated after the Python interpreter was compiled.

PS: Code is compiled to generate bytecode, and bytecode can be obtained by decompile.

Seven, variable

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

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

It's best not to repeat what's built into Python and use pycharm programming to avoid it.

The variable name avoids camel-like naming, for example:userId Java and C # Use this camel-like variable name in Python do not use

Eight, input

Perform an action
Reminder user input: User and password
Get user name and password, detect: Username =root password =root
Correct: Login Successful
Error: Login failed

A. use of input, wait forever until the user has entered a value, will assign the value of the input to a thing

N1 = input (' Please enter user name: ')
N2 = input (' Please enter password: ')
Print (N1)
Print (N2)

# !/usr/bin/env python # -*-coding:utf-8-*-  # assign the user input to the name variable name = input (" Please enter user name:"  )#  Print the contents of the input  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

Ix. Process Control and indentation

  Conditional statements

1. If base statementifCondition: Inner code block internal code blockElse:                        ...                                        Print('....')                                        if1 = = 1:                        Print("Welcome to the first Clubhouse 1")                        Print("Welcome to the first Clubhouse 2")                        #TAB Key                    Else:                        Print("Welcome to the one-way")                    2.ifNesting Supportif1 = = 1:                        if2 = = 2:                            Print("Welcome to the first Clubhouse 1")                            Print("Welcome to the first Clubhouse 2")                        Else:                            Print('Welcome to Tokyo Special')                    Else:                        Print("Welcome to the one-way")

3.if elifINP= Input ('Please enter your membership level:') ifINP = ="Senior Member": Print('Beauty') elifINP = ="Platinum Member": Print('Morgan Stanley') elifINP = ="Platinum Members": Print('A little star .') Else: Print('Chengguan') Print('start service put ....') added:Pass generation means empty code, meaningless, just to represent a block of code if1==1: Pass Else: Print('SB')

4. Conditions and OR

if N1 = = "Alex" or N2 = = "Alex!23":
Print (' OK ')
Else
Print (' OK ')

Indent with 4 spaces

Ten, while loop

1. Basic cycle

 while Conditions:          # Loop Body     # if the condition is true, then the loop body executes    # if the condition is false, then the loop body does not perform

2. Break

Break to exit all loops

 while True:     Print " 123 "     Break    Print " 456 "

3, continue

Continue is used to exit the current loop and continue the next loop

 while True:     Print " 123 "    Continue    Print " 456 "

11. Basic Data Type

  string -n1 = "Alex" n2 = ' root ' n3 = "" "Eric" "" N4= "' Tony '

Quoted is the string:

Name = "I am an essay" quotation marks are called strings.
name = ' PP '
Name = "" "PP" ""
name = ' I am an essay '

Addition:
N1 = "Alex"
N2 = "SB"
N4 = "db"

N3 = n1 + n2 + N4

Multiplication:
N1 = "Alex"
N2 = N1 * 10


  number -age=21 weight = fight = 5

Subtraction Secondary Surplus:
A1 = 10
A2 = 20

a3 = A1 + A2

A3 = A1-a2

a3 = A1 * A2

A3 = 100/10

A3 = 4**4

a3 = 39% 8 # Gets the remainder by 39 divided by 8

Add:
A3 = 39//8 Take That quotient equals 4 4*8=32


A = 13
temp = a% 2
If temp = = 0:
Print ("even")
Else
Print (' odd ')

12. Exercises

If condition statement
While loop
Odd even

1. Use while loop input 1 2 3 4 5 6 8 9 10N= 1 whileN < 11:                        ifn = = 7:                            Pass                        Else:                            Print(n) n= n + 1Print('----End----')                                    2, 1-100 of all the numbers and N= 1s=0 whileN < 101: S= S +N N= n + 1Print(s)3, Output 1-100all the odd n inside= 1 whileN < 101: Temp= n% 2iftemp = =0:Pass                        Else:                            Print(n) n= n + 1Print('----End----')                                        4, Output 1-100all even n in the= 1 whileN < 101: Temp= n% 2iftemp = =0:Print(n)Else:                            PassN= n + 1Print('----End----')                5. Seeking 1-2+3-4+5 ... 99 of all the numbers and N= 1s= 0#S is the sum of all the previous numbers                     whileN < 100: Temp= n% 2iftemp = =0:s= S-NElse: S= S +N N= n + 1Print(s)

(ii), Python Foundation

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.