Python basic syntax, basic data types, and related operations

Source: Internet
Author: User
Tags key string

---restore content starts---

  1. Python file

    1. File at the beginning of the #!/usr/bin/python--in Linux is to tell the system Phthon path is in the/usr/bin/python directory, in the execution of Python files can be used./file name, such as:./h.py can be executed

    2. So the python2.7 file needs to have a #-*-coding:utf-8-*-This sentence to set the encoding format

    3. When there is Chinese output, often output is garbled, this is because the code is UTF-8 format, but the display terminal encoding format is GBK format. If the format of the display terminal is Utf-8, it will display normally, but if it is in GBK format, it is garbled. The UTF-8 encoding and GBK encoding are Unicode (universal code) simplification and optimization, but the encoding method is not the same. To solve the problem of Chinese output display garbled, you need to decode the utf-8 format into Unicode, and then the GBK encoding, and then output, you can display Chinese normally, as follows:

      1.   
        1 #-*-coding:utf-8-*-2 3temp ="Hello"4 5 #first decode the utf-8 to Unicode6 7Temp_unicode = Tem.decode (' Utf-8 ')#the utf-8 here is to specify that the original encoding is UTF-8 encoded8 9TEMP_GBK = Temp_unicode.encode ("GBK")#the GBK here is to specify the encoding in GBK formatTen  One Print(TEMP_GBK) A  - #to the PY3, the auto-convert utf-8 Unicode gbk,utf-8 can be encoded directly into the GBK -  the #The Unicode type of Python was removed from Py3

  1. Enter python in the cmd command window to enter the Pythod environment, enter exit () to exit the editing environment

  2. Comments

    1. Single-line comment, using #

    2. Multi-line comment, using "" "" "" "" "" ""

  3. Import file

    1. . py files that Python provides to users

    2. Import file name (without. py) after importing with import

    3. A. PYc bytecode file with the same name is automatically generated after executing the program, which is equivalent to caching the file

    4. Execution takes precedence of the. pyc file and executes if the. pyc file is not found, then you'll find the. py file and Execute

  4. Get input text

    1. I1 = Raw_input ("Username:") for text entry in plaintext

    2. I2 = Getpass.getpass ("Password:") (Import a file before using this sentence imports Getpass)

  5. Create a xxx.py file

    1. Suggested file name, storage path do not have Chinese

    2. Two lines of the head of the code is more special, must have

  6. Basic data types

    1. Number: A1 = 123

    2. String: S1 = "abc" or s2 = ' abc ' or s3= "" "CDE" "(content in three quotation marks is a multiline text string)

    3. Boolean value: Isable = True

  7. Process Control

    1. If

If condition:

Content One

Content II

Elif Conditions:

Content Five

Content Six

else:

Content Three

Content Four

      1. Python is executed strictly by indentation.

      2. An equal sign is an assignment, two equals is a comparison,! = is not equal to

      3. While

While condition:

Content One

      1. Time.sleep (1) Pause for 1 seconds

      2. Break, you can jump out of the loop

      3. Continue, jump out of this cycle and continue the next cycle.

      4. Pass, do not do anything, can not be empty, write a pass can

      5. For loop

S7 = "Return a copy of the string" for item in S7:    Print Item

        1. Enumerate ()

          1. The Accept parameter can be a list

          2. Automatically generates a column for the list item when used in for loop, default starting from 0, increment 1

Li = ["Computer", "iphone", "Watch", "Car"]for Key,item in Enumerate (LI):    print (key,item) INP = input ("Please enter Product:") inp_ num = Int (INP)  print (Li[inp_num])

------------------------Output-------------------------

(0, ' computer ')

(1, ' iphone ')

(2, ' Watch ')

(3, ' Car ')

Please enter product: 0

Computer

    1. Operator

      1. Arithmetic operations

        1. +-*/% (take balance) * * (power, returns the y power of X)//(Take an integer, return the integer part of the quotient)

PY2:9/2 = 4

9/2=4.5 (need to import modules, such as: from __future__ Import Division)

PY3:9/2 = 4.5

        1.  

    1.  pycharm Set the template for the Py file, adding a fixed two lines to the header: Fileàsettingàedit Oràfile and Code Templateàpython script, enter a fixed two lines Àok

    2.  pycharm Switch the py version, FILEÀSETTINGSÀPROJEC T Interpreterà Select version

    3.   comparison operator: == !=  <>  >  <  >=  < =

    4.   assignment operator: =   += -=  *= /=  %=  **=

    5. &nb Sp;ctrl +/  Comment shortcut

    6.   logical operator:and  or  not

    7. Member operator:  in     Not in

    8.   base data type

      1. Numbers              int

        1. The method of __ in the Int class is a method with special functions

N1 = 123

N2 = 456

Print (n1 + N2) is equivalent to print (n1.__add__ (n2))

        1. Bit_length (), gets the number of binary shortest digits that can be represented

N1 = 4 #00000100

ret = N1.bet_length ()

Print (ret)

      1. String str

        1. Capitalize () method, capitalize first letter

        2. Center (length, blank padding character) method to display the current string in the middle, with the blank part replaced with the specified character

        3. Count () method, number of sub-sequences, number of occurrences of the current string in the specified string

        4. Decode () method, decoding

        5. Encode () method, encoding

        6. EndsWith () method, [Gets the position of the string greater than or equal to 0, the position less than 2], whether to end with XXX

        7. Expandtabs () method to convert the tab (\ T) to a space (default 8 spaces)

        8. The Find () method, which finds the first occurrence of a subsequence, returns 1 if not found

        9. Format () method, string serialization

s = "Hello {0}, age {1}" print (s) s2 = S.format ("Alex") print (s2)

------------------------Output-------------------------

Hello {0}, age {1}
Hello Alex, age 20
        1. Index () method, find the position of the sub-sequence, if not found, error

        2. int (string) to convert the specified string to a number and return

        3. Isalnum () method to determine if there are both letters and numbers

        4. Isalpha () method to determine if all letters are

        5. IsDigit () method to determine whether a number

        6. Islower () method to determine if lowercase

        7. Isspace () method to determine whether it is a space

        8. Istitle () method to determine if the title (the first letter of each word is capitalized)

        9. Join () method, connecting

Li = ["Alex", "eric"]s3 = "_". Join (LI) print (S3)

------------------------Output-------------------------

Alex_eric
        1. Ljust () method, content alignment, right padding, similar to center ()

        2. Lower () method, lowercase

        3. Len () method, return Back to string length

        4. Lstrip () method, remove left blank

        5. Partition () method, split string into left-right three-part

        6. Split () method, split word String

        7. Replace () method, replace strings

        8. RFind () method, looking right-to-left

        9. Rindex () method, similar to Lindex (), Just here is to find the

        10. Rjust () method from right to left, similar to Ljust (), in the opposite direction to Ljust () the

        11. Rpartition () method, similar to partition (), The direction is opposite to partition () the

        12. Rsplit () method, similar to the split () method, in the opposite direction of Split ()

        13. Rstrip () method, similar to the Lstrip () method , the direction is opposite to the Lstrip ()

        14. Strip () method, removing the left and right spaces

        15. StartsWith () method to determine whether a string starts with the specified string

        16. Swapcase () method, lowercase to uppercase, uppercase to lowercase

        17. Title () method to turn text into a caption

        18. Upper () method to convert text to uppercase

        19. Slice

S6 = "Alex" Print (S6[0:2]) #大于等于左边, less than the right 

------------------------output-------------------------

Al

        1.  

      1. Boolean        bool

      2. p> lists             list

        1. Append () method, append element

          li> the
        2. Count () method to count the number of

        3. Extend () methods for an element to append data to the list

        4. Index () method to get the index of an element

          li> the
        5. Insert () method, inserts an element at an index

        6. Pop () method, removes the last element, and can return the removed element

        7. Remove () method to remove a element, only remove the first

        8. Reverse () method found from the left, reverse the list

        9. Sort () method, sort the list

        10. del list [index], Delete List the elements of the specified index

      3. Tuples             tuples

        1. Tuples are almost the same as lists, lists can be modified, tuples cannot be modified

      4. Dictionary       & nbsp;     dict

        1. Each element of the dictionary is a key-value pair, a bit similar to a simple JSON object

user_info = {"Name": "Alex", "Age": "Gender": "M"} 

 

        1. The index of the dictionary element is the corresponding key string

        2. Dictionary does not support slicing

        3. Keys () method, get all keys in dictionary

        4. Values () method to get all value

        5. Items () Methods in the dictionary, getting all the key values in the dictionary

        6. For loop

          1. For Loop when dictionary, the default output key is: For k in User_info is equivalent to a for K in User_info.keys ()

          2. If you want to loop out the value of the dictionary: for-V in User_info.values ()

          3. li>

            If you want to loop out the keys and values of the dictionary at the same time: for K,v in User_info.items ()

        7. Clear () method, empty all elements in the dictionary

        8. G The ET () method, gets the value from key, if key does not exist, you can specify an arbitrary value

        9. Haskey () method, check whether the specified key in the dictionary exists, or use in instead of the

        10. Pop () method, Gets and removes the

        11. SetDefault () method in the dictionary, creates if the key does not exist, returns the existing value if it exists, and does not modify the

        12. Update () method, UPDATE, To update an element in one dictionary to another after the

        13. del dictionary [key], delete the element that specifies key for the dictionary

    1. Range, xrange

      1. Range, which is used in py2.7 to get a number within a specified range, such as range (0,1000000), creates a range of numbers at a stroke, and memory consumption rises rapidly

      2. Xrange, which is used in py2.7 to get a number within a specified range, such as range (0,1000000), does not initially create a number in the range, only one element in its range is created in the For loop, and performance is greatly improved

      3. In Py3, there is no xrange, but range, but the effect is the same as the xrange effect in py2.7

      4. Range (0,10), get all the numbers between 0~9, take the number range is greater than or equal to the left number, less than the right number

Li = ["Computer", "iphone", "Watch", "Car"]n = Len (li) for I in Range (0,n):    print (I,li[i])

------------------------Output-------------------------

(0, ' computer ')

(1, ' iphone ')

(2, ' Watch ')

(3, ' Car ')

    1. View the class of an object, or the functionality that an object has

      1. The type (variable) function can see the data type of the variable, and then, depending on Ctrl + Left, view all internal methods

      2. DIR (variable) for a quick look at all the methods of variable types

      3. Help (Type (variable)) to see a detailed method of variable type

Python basic syntax, basic data types, and related operations

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.