Python Basics 01

Source: Internet
Author: User
Tags string format python script

1. Python introduction and comparison with other developing languages:

Compared to C, Java runs slowly, but the code introduction, can reduce the learning cost, speed up the project progress. Cross-platform support for Linux and Windows.

C language is the basis of all high-level languages, to study the principles of Python language, need to look at C. The reason C is faster than Python is that the C language translates the code directly into machine code, which is provided to the machine to run.

High-level languages such as Python and Java and PHP are compiled into bytecode by their respective interpreters, which are then converted from bytecode to machine code to run.

Python can be divided into three categories depending on the interpreter:

CPython: The code is interpreted as a C-language bytecode and then converted to machine code (progressive compilation). This is now the default.

PyPy: Code-"C Language bytecode-" machine code (all conversion completed)--"run. Resolves a problem in which Python is running relatively slowly.

Other languages developed by Python: code-"The corresponding language byte code-" machine code.

Execution process: Open code file--"lexical, grammatical analysis-" interpreted as a bytecode file

If you see a. pyc end file, that is an interpreted bytecode file.

Run Python file in command-line mode: Interpreter location \python.exe python code file address

Eg:c:\users\git.git-think\appdata\local\programs\python\python35\python.exe F:\wangkc\day01\s3.py

2. Character encoding

ASCII code: American Standard, including English letters, numbers and special symbols. One character occupies one byte. A byte of 8 bits.

Universal Code Unicode: Each character occupies at least two bytes. The letter occupies two, the front is 0, the Chinese occupies 3 bytes.

Utf-8: The universal code to compress, save memory. English occupies 1 bytes; Chinese takes 3 bytes.

GBK, GB2312: Chinese two bytes to indicate

Extension: Garbled reason: File encoding and interpreter encoding inconsistent.

File ID: File-->default Settings-I search Coding-->file Encoding,

Interpreter encoding: Can be set by the second line in the code file: #-*-Coding:utf-8-*-

(Py3 defaults to Utf-8,py2, which is ASCII by default.) So in order to make it easier to set the interpreter encoding format in the second line, no matter where the code will run in the future.

3, the IDE recommends the use of pycharm, common settings:

Encoding settings: File-->default settings-->coding-->file Encoding

Text style: Usually the first line sets the installation path where the interpreter is located, and the second line is the encoding format of the interpreter.

File-->default Settings---Search Temp-->file and Code Templates-->python Script, enter in the text box on the right:

#! C:\Users\git.git-THINK\AppData\Local\Programs\Python\Python35\
#-*-Coding:utf-8-*-

Press CTRL + Scroll scrolling text to zoom out:file-->setting--> search mouse-->general--> the mouse option box to the right of the three options all: Change font size (Xoom) with Ctrl +mouse Wheel

  

4. Variables:

Variable name: is the memory address where the value of the variable is recorded.

eg1:name1= ' WANGKC '

Name2 = name1

name1 = ' xingxing '

Print (name2) # printed or ' WANGKC '

eg2:name1 = ' WANGKC '

name2 = ' WANGKC '

This py3 is memory-optimized, and name1 and name2 use the same memory address.

Name of variable name: letter, Number (cannot start), underline

It can't be a keyword inside python.

You can use underline connections to increase the readability of variable names.

5. Input and OUTPUT statements: input, Getpass (import getpass required)

INPUT:NUM1 = Int (input (' Please enter an integer: '))

Inside the parentheses is a hint that prompts the user to enter a value in the console and assigns the value to a variable

Note: input gets the value of the variable as a string format, if you need to do mathematical operations, and so on, you need to cast: Int (NUM1)--"converted to an integer format.

Getpass: Implicit display, the console input is not displayed, you need to execute the file in the CMD command line format to display.

Import getpassnum1 = Int (getpass.getpass (' Please enter an integer: ')) if num1 = = 1:    print (' good! ')

Then execute in cmd: C:\Users\git.git-THINK\AppData\Local\Programs\Python\Python35\python.exe F:\wangkc\day01\s2.py

6. Annotation Method:

#: Single line comment

"" "" "or" ": Multiline Comment

Shortcut: Select and press CTRL +?

7. While conditional expression:

Loop body

EG1: For 1-100 direct all numbers and

i = 1= 0 while I < 101:    = sum + i    + = 1print(sum)

8, continue (jump out of this cycle, directly start the next cycle), break (jump out of the entire cycle):

EG1: Ask 1 to 100 for the and, using break:

i = 1sum = 0while True:    sum = sum + i    if i = =:        break    i + = 1print (sum)

EG2: Seeking the 1/2/3/4/5/6/8/9 and

 

i = 1while I <:    if i = = 7:        i + = 1  #这一行代码要在continue前面, otherwise, the code execution will go into the dead loop, continuously print 6        continue print    ( i)    i + = 1

  

9. For loop: note Here the For loop can only be formatted with the for variable 1 in variable 2.

List1 = ['li',' king ',' politics ','     list1:    Print( Name

10. If Condition Branch statement:

score = Int (input (' Please enter your score ')) if score >=:    print (' excellent ') Elif score >= and score <:    print (' good ') Els E:    pass    #pass means pass, do not do any action

  

11, Operator:% take surplus,//division, * * several n-th square

A:I = I+1 with i + = 1

B:and (True if both sides are true), or (True if one true)

C:in (Contains a = ' I ' in ' Comein ', which is commonly used to determine whether a string or list contains an element.) )

12, Placeholder:%s string,%d number

str = ' Welcome%s come our Home,her age is%d '% (' WANGKC ', 18)

13. Data type:

1) Integer: A = 18 or a = Int (18)

A = ' 18 '

Conversion: b = Int (a)

2) Boolean boolean:true or False

1 is true,0 to False

' Empty string is False, other is true

Print (int (True)) A = "" If not A:    print (' Yes ')

  

3) String: Defines STR (), forced conversion, string concatenation, string formatting (% of character%s) to determine if string A is in string B, remove index blanks, split, length, slice, index

A string definition: str1 = ' Wang ' or str2 = str ("Wang")

B, Conversion:

i = int () str1 = str (int) print (type (str1))  #class  ' str '    # type (variable name)  returns the types of the variable

C, string concatenation using "+": Print (' name ' + ' age ')

D, remove whitespace: variable name. Strip () remove white space on both sides, Lstrip remove left margin, rstrip remove right margin, note that whitespace includes spaces and line breaks.

val = '   tian  yi youqing    ' new_val = Val.strip ()  #得到一个新的字符串, will not have an effect on the original string. New_val = Val.lstrip () New_val = Val.rstrip () print (val) print (New_val)

E, Length len (variable name)

val = ' Jjdjjdjd ' v = Len (val) print (v)

F, Index

val = ' ddfddd ' i = 0while i < Len (val):        print (val[i])    i + = 1

g, split variable name. Split (' delimiter ', [number])

val = ' abc|def|hij|klm|nob ' val_list = val.split (' | ') Print (val_list)  #[' abc ', ' Def ', ' hij ', ' KLM ', ' Nob ']print (val.split (' | ', 2))  #[' abc ', ' Def ', ' Hij|klm|nob ']    #后面的数字表示把前面的几个分割print (val.split (' | ', -2))  #[' abc ', ' Def ', ' hij ', ' KLM ', ' nob ']

H, Slice

val = ' Abcdefghijk ' Print (Val[1:3])  #打印出索引为1到 (3-1) string  bcprint (Val[:4])  # Abcdprint (val[5:])  # Fghijkprint (Val[:-1])  #abcdefghij

  

4) List: Define, determine whether to include, index, length, slice, append to end, insert, delete remove Del, modify, for loop

#列表创建list1 = [' abc ', ' DDF ', ' iidk ', ' kkk ']list2 = list ([' abc ', ' DDF ', ' iidk ', ' KKK ']) #判断是否包含if ' abc ' in List1:    pass# Index: Print (list1[0]) #长度print (len (list1)) #切片: Print (List1[0::2]) #起始位: Stop bit: Step   [' abc ', ' Iidk '] #追加: list.append (Element), Returns the new list directly without assigning a value. such as List2 = List1.append (' hhhhh ') print (list1,list2)   #[' abc ', ' DDF ', ' iidk ', ' KKK ', ' hhhhh '] None    List2 is Nonelist1.append (11111) print (list1) #插入: Insert (index, Element) List1.insert (0, ' yyyyy ') print (list1) #删除: Remove (Element),  del list[n]list1.remove (11111) print (List1) del list1[0]print (List1) #更新: assignment list1[2] = 22222print (list1) # For loop polling print for i in List1: print    (i)

  

5) Dictionary: Create, key:value form (find corresponding value according to index name), length, increment or modify (because the dictionary is unordered, so when it is incremented, if there is no increment, there is a change), delete, for loop

#创建dict1 = {' name ': ' WANGKC ', ' pwd ': 1234, ' age ': 18}dict2 = dict ({' name ': ' xiaoling ', ' pwd ': 1234, ' age ': ') #依据索引名称或者值pwd = dict1[' pwd ']print (pwd) #长度n = Len (dict1) print (n) #增加或修改, none increase, there is modify dict1[' no '] = 1print (dict1) #删除 del# del dict1[' age ']# Printing (Dict1) #for循环for item in Dict1: Print    (item)    #若是只是字典名, the default is the printed index name for item in Dict1.keys (): Print    (item)   #打印索引名for item in Dict1.values ():    print (item)  #打印索引值for Key,val in Dict1.items ():    print (Key,val)  #key和value All print No 1 PWD 1234 name WANGKC age 18

  

  

  

  

Python Basics 01

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.