Basic Python syntax [2]: getting started with python to proficient in [4], and getting started with python to proficient

Source: Internet
Author: User
Tags natural string

Basic Python syntax [2]: getting started with python to proficient in [4], and getting started with python to proficient

The Python basic syntax of the previous blog has been introduced in [2] as a beginner in python. The basic syntax of the previous blog is only a preview version, the purpose is to give you a rough understanding of the basic syntax of python. The basic syntax of python is divided into two parts, because most people in the garden have programming basics, so when learning Python, you can get a preview version first, the preview version is similar and different from other languages (java/C #/php) based on Python syntax, so that you can have a basic understanding of Python. After getting to know about Python, it may be easier to go into the Python syntax.

V Preface

Python: You don't know it. It may be okay. Once you know it, you will fall in love with it.

V: Basic Python syntax

1. Define constants:

The reason why I introduced definition variables in my previous blog didn't introduce definition constants together is that Python constants may be a little complicated compared to other languages. You can define constants not only by using const alone. Defining constants in Python requires the creation of objects.

We need to create a const. py file under the Lib directory. The lib directory mainly contains some modules.

Code body:

class _const(object):    class ConstError(TypeError):pass     def __setattr__(self, name, value):         if self.__dict__.has_key(name):             raise self.ConstError, "Can't rebind const (%s)" %name         self.__dict__[name]=value    def __delattr__(self, name):        if name in self.__dict__:            raise self.ConstError, "Can't unbind const (%s)" %name        raise NameError, nameimport sys sys.modules[__name__] = _const() 

This is a method for defining constant objects. Python defines constants first requires the concept of objects. Therefore, we have briefly understood the definition of objects in the previous blog. As for the above const class, you can just take a look at it. Baidu searches for a large number of Python defined constants. We only need to create a const. py file under the lib folder and copy the above Code to the const. py file. This makes it easy to use constants.

Code Description:

The running result shows that an error is returned after the first output of const. value (result 5. This is because a constant is assigned a value again, so an error is reported. After the constant object method is created, it is very convenient to use constants. The method for using constants is as follows.

import constconst.value=5print(const.value)

2. Number Type:

  • INTEGER (int): 0, 6,-2, 2015,-203
  • Long Integer (long) Example: 201790l,-12694l, 938476l
  • Float examples: 7.5325, 9.434, 6.66
  • Boolean (bool) Example: True, False
  • Complex (complex) Example: 6 + 4j,-5 + 12j, 98 + 9j

The data type is easy to understand. Here, only the plural type may need to be discussed separately.

The complex () function can create a plural number using the real + imag * j parameter. You can also convert the number of a string to the plural value, or convert a number to the plural value. If the first parameter is a string and the second parameter is not required, the string is interpreted and the plural value is returned. However, the second parameter cannot be entered as a string; otherwise, an error occurs. Real and imag parameters can enter numbers. If the imag parameter is not input, it is a zero value by default. This function is equivalent to the int () or float () function. If the real and imag parameters both input zero, this function returns 0j. With this function, you can easily convert a list into a complex number.

Note: When you want to convert a string from the plural form to the plural form, note that no space exists in the string, for example, complex ('1 + 2j '), instead of writing complex (1 + 2j '), otherwise, a ValueError exception is returned.

Code Description:

3. string type:

  • Single quotation mark string: 'hello'
  • Double quotation mark string: "hello"
  • String with three quotation marks: "hello" Or '''hello ''' note: the string contained in the three quotation marks can be composed of multiple lines, which generally represent the narrative string of a large segment. There is basically no difference in use, but double quotation marks and three quotation marks ("""... ") can contain single quotes, three quotes ('''... ''') can contain double quotation marks without escaping.

Code body:

dan='m1n9'print("dan:  {0}".format(dan))dan1='Our "young"!'print("dan1:  {0}".format(dan1))dan2='''Ouryoungcool'''print("dan2:  {0}".format(dan2))dan3="""Ouryoungcool"""print("dan3:  {0}".format(dan3))

Code Description:

4. escape characters and line breaks:

Code body:

comment='I\'m young'print(comment)description="Our \nyoung"print(description)

Code Description:

5. Duplicate natural strings and strings:

The literal meaning of a natural string is to retain its own format without being escaped.

String repetition literally means repeated output of the string.

Code body:

comment=r'Our \nyoung'print(comment)description="Our \nyoung"print(description)three="Our young\n"*3print(three)

Code Description:

6. substring:

Index operator starts from 0

The slicing operator [x: y] indicates the subscript starting from the subscript x to the subscript y-1.

Code body:

description="Our young"d1=description[0]print("d1:   {0}".format(d1))d2=description[8]print("d2:   {0}".format(d2))d3=description[:3]print("d3:   {0}".format(d3))d4=description[3:]print("d4:   {0}".format(d4))d5=description[3:6]print("d5:   {0}".format(d5))

Code Description:

7. Data Type:

  • Basic data type: the basic data type is the number and string we mentioned earlier.
  • List: There is no array concept in python. The list and array concepts are very similar. A list is a container used to store a series of elements, represented.
  • Tuples: The same meta-combination array concept is also very close, represented. In addition, tuples can only be read and cannot be modified.
  • Set:
    • Format: set (element). The python set is an unordered, non-repeating element set.
    • Function:
      • Establish relationships
      • Eliminate repeated Elements
  • Dictionary: The dictionary in Python is also called an associated array, represented. Example: dictionary = {'name': 'toutou', "age": "26", "sex": "male"} ps: Does it look a bit like json?

Code body:

# Coding = UTF-8 # list of people = ["Liu Yi", "Chen Er", "Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "Sun Qi ", "week 8", "Wu JIU"] print people [3] # tuples names = ("Liu Yi", "Chen Er", "Zhang San", "Li Si ", "Wang Wu", "Zhao Liu", "Sun Qi", "Zhou Ba", "Wu JIU") print people [1] # set xitems = set ("1222234566666789 ") xitems. add ("x") xitems. remove ("8") xitems. discard ("8") print xitemsyitems = set ("1357") # print ("intersection: {0 }". format (xitems & yitems) # xitems & yitems = xitems. intersection (yitems) # Union print ("union: {0 }". format (xitems | yitems) # xitems | yitems = xitems. union (yitems) # difference set print ("difference set: {0 }". format (xitems-yitems) # xitems-yitems = xitems. difference (yitems) xitems. pop () xitems. clear () print ("xitems set cleared: {0 }". format (xitems) # dictionary = {'name': 'toutou', "age": "26", "sex ": "male"} print dictionary ["name"] # Add project dictionary ['hobby'] = 'cnblogs' print dictionary ["sex"] print dictionary ["holobby"]

Code Description:

8. identifier:

In daily life, a identifier is used to specify a person or a person, and his or her name is required. When solving equations in mathematics, we often use one or more variable or function names. In programming languages, identifiers are the names used by users for programming, variables, constants, functions, and statement blocks are also named identifiers.

Identifier naming rules:

  • It must start with a letter or underscore, and cannot start with a number or another character.
  • Except the first character, other parts can be letters, underscores, or numbers.
  • The identifier is case sensitive. For example, the name and Name are different identifiers.

Special identifier: the keyword in python is the identifier that comes with a specific meaning in the system. Common python keywords include: and, elif, global, or, else, pass, break, continue, import, class, return, for, while... many common python keywords are similar to those in other languages. We should try to avoid repeated keywords during naming. You do not have to worry about poor differentiation. In fact, it is also very well differentiated. General keywords in IDE will show specific colors.

9. Object:

Python object type: built-in Pyhon objects: Numbers, strings, lists, tuples, dictionaries, and collections. in Python, everything can be seen as an object.

Pickle module: in Python, some objects need persistent storage without losing the type and data of the object. These objects need to be serialized and used after serialization, then restore the original data. This serialization process is called pickle ).

Code body:

# Coding = UTF-8 # pickle modular (pickled) import pickle # dumps (object) serialization listx = ["one", "two", "three"] listb = pickle. dumps (listx) print ("dumps (object) serialization: {0 }". format (listb) # loads (string) deserialization listz = pickle. loads (listb) print ("loads (string) deserialization: {0 }". format (listz) # demp (object, file), serialized and stored the object to the file writeFile = file ('test. pke ', 'wb') pickle. dump (listx, writeFile, True) writeFile. close () # load (object, file) deserializes the data stored by dump in the file. readFile = file ('test. pke ', 'rb') listTemp = pickle. load (readFile) print ("# load (object, file) Stores dump data in the file in reverse order \ n columns: {0 }". format (listTemp) readFile. close ()

Code Description:

10. Lines and indentation:

Physical and logical rows:

  • Physical row: the row actually seen. A physical row in python can generally contain multiple logical rows. When multiple logical rows are written in a physical row, they are separated by semicolons. A logical row must be followed by a semicolon. Note that in a program, if a logical row occupies the end of a physical row, the semicolon can also be omitted. (Omitted rule: Each physical row contains a semicolon by default, so. The last logical row of each physical row can be omitted by semicolon. Therefore: when a logical row occupies a physical row, the semicolon can be omitted .)
  • Logical line: number of lines in the sense of a piece of code

Line connection: For more information about the line connection, see the code diagram.

Indent: In my previous blog, some people mentioned that the python language is "language that controls code by indentation ". Indeed, in python, the blank space at the starting position of the logical line is defined by syntax. If the blank space is incorrect, the program will execute an error. (This is a big difference from other languages .) In general (except for logical rows after if/while...), the start position of a separate logical row should not be blank. There are two ways to indent: Press space or tab. (Generally, the IDE will be automatically indented .) As for indentation, it may be a little uncomfortable or uncomfortable to get started. Just try more.

Code body:

# Coding = UTF-8 # physical and logical lines # The following are two physical lines: print "physical line 1" print "physical line 2" # The following is one physical line, two logical lines print "logical line 1"; print "logical line 2" # The following is a logical flight, two physical rows print ''' do you mean I am a physical row or a logical row? ''' # Line connection print "I Am a line connection" \ "connected"

Code Description:

V blog Summary

I have introduced so much about the basic syntax of python 1 and 2. If you have any questions or want to add them, you can speak enthusiastically. The basics are very important. In terms of the basic Python syntax, there are many differences from other languages. You need to work hard and get used to it.

 


Author:Please call my first brother
Exit: http://www.cnblogs.com/toutou/
About the author: focused on Microsoft platform project development. If you have any questions or suggestions, please kindly advise me!
Copyright Disclaimer: The copyright of this article is shared by the author and the blog site. You are welcome to reprint this article. However, you must keep this statement without the author's consent and provide the original article link clearly on the article page.
We hereby declare that all comments and private messages will be replied immediately. You are also welcome to correct the mistakes and make progress together. Or directly send a private message to me.
Support blogger: If you think the article is helpful to you, click the bottom right corner of the article[Recommended]. Your encouragement is the greatest motivation for the author to stick to originality and continuous writing!

Related Article

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.