Python Syntax Basics

Source: Internet
Author: User
Tags natural string

Main Source: Beginner python Tutorial

Python Introduction

Python is a high-level scripting language that combines explanatory, compiled, interactive, and object-oriented.

Python 's design is highly readable, with English keywords often used in other languages, some punctuation in other languages, and it has a more distinctive grammatical structure than other languages.

  • Python is an interpreted language: This means that there is no compilation in the development process. Similar to the PHP and Perl languages.
  • Python is an interactive language: This means that you can execute your program in a python prompt directly interacting with the execution.
  • Python is an object-oriented language : This means that python supports object-oriented styles or code encapsulation in object programming techniques.
  • Python is the language of beginners: Python is a great language for novice programmers, and it supports a wide range of application development, from simple word processing to WWW browser to gaming.
Python Features
    • 1. Easy to learn: Python has a relatively small number of keywords, simple structure, and a well-defined syntax that is easier to learn.
    • 2. Easy to read: The Python code is defined more clearly.
    • 3. Easy maintenance: The success of Python is that its source code is fairly easy to maintain.
    • 4. A broad library of standards: One of the biggest advantages of Python is the rich library, cross-platform, compatible with Unix,windows and Macintosh very well.
    • 5. Interactive mode: interactive mode of support, you can enter the execution code from the terminal and obtain the results of the language, interactive testing and debugging code snippets.
    • 6. Portable: based on its open source features, Python has been ported (that is, making it work) to many platforms.
    • 7. Extensible: If you need a critical code that runs fast, or if you want to write some algorithms that you don't like to open, you can use C or C + + to complete that part of the program and then call it from your Python program.
    • 8. Database: Python provides the interface for all major business databases.
    • 9.GUI Programming: Python support GUI can be created and ported to many system calls.
    • 10. Embeddable: You can embed python in a C + + program to give your program's users the ability to "script".
Common ways to run Python:
      • Interactive interpreter: Install Python's own editing interpreter
      • Command line: Computer cmd
      • Pycharm
      • Add plug-ins in eclipse
Integrated development Environment: Pycharm

Pycharm is a Python IDE built by JetBrains that supports MacOS, Windows, Linux systems.

Pycharm Features: Debug, Syntax highlighting, project management, code jump, smart tips, AutoComplete, Unit testing, versioning ...

pycharm:https://www.jetbrains.com/pycharm/download/

  

Pycharm Convert Python version file-settings-project:xxx (project name)--project interpreterpython Chinese Code: Print ("Chinese test") If output error: Syntaxe    Rror:non-utf-8 code ... or syntaxerror:non-ascii character ... Represents a python file and does not specify an encoding

The default encoding format in Python is the ASCII format, which fails to print correctly when the encoding format is not modified, so the error occurs when reading Chinese.

The workaround is to add #-*-coding:utf-8-*- or #coding =utf-8 at the beginning of the file.

(if the code contains Chinese, you need to specify the encoding in the header!!!) )

Note: python3.x source files use utf-8 encoding by default, so you can parse Chinese normally without specifying UTF-8 encoding.

Note: If you use the editor and you need to set the PY file storage format to UTF-8, you will receive an error message similar to the following:

SyntaxError:(Unicode error)'UTF-8' codec can'byte0xc4 In 0:byte                

Pycharm Setup Steps:

    • Go to file > Settingsand search for encodingin the input box.
    • Locate Editor > File encodings, and set the IDE Encoding and Project Encoding to Utf-8.

Python identifiers
    • The first character must be a letter in the alphabet or an underscore ' _ '.
    • The other parts of the identifier are composed of letters, numbers, and underscores.
    • Identifiers are case sensitive.

In Python 3, non--ascii identifiers are allowed as well.

Python reserved characters

Reserved words are keywords, and we cannot use them as any identifier names.

Python's standard library provides a keyword module that can output all the keywords for the current version:

Import Keywordprint (keyword.kwlist)

Output:

[' False ', ' None ', ' True ', ' and ', ' as ', ' assert ', ' Break ', ' class ', ' Continue ', ' def ',

' del ', ' elif ', ' Else ', ' except ', ' finally ', ' for ', ' from ', ' global ', ' if ', ' import ',

' In ', ' was ', ' lambda ', ' nonlocal ', ' not ', ' or ', ' Pass ', ' raise ', ' return ', ' Try ',

' While ', ' with ', ' yield ']

Comments

Single-line comments in Python start with #

Line and indent

Python's most distinctive feature is the use of indentation to represent blocks of code, without the need for curly braces ({}).

The number of spaces to indent is variable, but the statement of the same code block must contain the same number of indentation spaces. Examples are as follows:

If True:    print ("True") Else:    print ("False")

The following code does not match the number of spaces in the last line of the statement, resulting in a run error:

If True: Print ("    Answer")    print ("True") Else: Print ("    Answer")  print ("False")    # Indentation inconsistent, resulting in a run error

The above program is not consistent due to indentation, after execution will appear similar to the following error:

File"test.py",6print("False")# indentation inconsistent, resulting in a run error ^Indentationerror :not match no outer indentation            level 
Multi-line statements

Python is usually a line to complete a statement, but if the statement is long, we can use a backslash (\) to implement a multiline statement, for example:

Total = Item_one +         item_two +         Item_three

In [], {}, or () a multiline statement, you do not need to use a backslash (\), for example:

Total = [' Item_one ', ' item_two ', ' item_three ',        ' item_four ', ' item_five ']
Data type

There are four types of Python: integers, long integers, floating-point numbers, and complex numbers.

    • integers, such as 1
    • Long integers are relatively large integers.
    • Floating-point numbers such as 1.23, 3E-2
    • Complex numbers such as 1 + 2j, 1.1 + 2.2j
String
    • The single and double quotation marks in Python are used exactly the same.
    • Use the quotation marks ("' or" ") to specify a multiline string.
    • Escape character ' \ '
    • Natural string, by adding R or R before the string. such as R "This was a line with \ n \" will be displayed, not newline.
    • Python allows processing of Unicode strings, prefixed with u or u, such as u "This is a Unicode string".
    • The string is immutable.
    • The literal cascading string, such as "This" and "is" and "string", is automatically converted to this is string.
Word = ' string ' sentence = ' This is a sentence. "paragraph =" "This is a paragraph that can consist of multiple lines" ""
Blank Line

A blank line separates between functions or methods of a class, representing the beginning of a new piece of code. The class and function entries are also separated by a line of blank lines to highlight the beginning of the function entry.

Blank lines are different from code indentation, and empty lines are not part of the Python syntax. When you write without inserting a blank line, the Python interpreter runs without errors. However, the purpose of a blank line is to separate the code of two different functions or meanings, which facilitates the maintenance or refactoring of future code.

Remember: blank lines are also part of your program code.

Wait for user input

Executing the following program will exit after pressing (enter) the ENTER key:

Input ("\ n \ nthe exit after pressing the ENTER key.") ")

Output:

In the above code, "\ n" will output two new blank lines before the result output. Once the user presses the key, the program exits.

Show multiple statements on the same line

Python can use multiple statements in the same row, with semicolons (;) split between statements.

Multiple statements form a code group

Indenting the same set of statements constitutes a block of code, which we call the code group.

Compound statements such as if, while, Def, and class, the first line begins with a keyword, ends with a colon (:), and one or more lines of code after that line form the code group.

We refer to the first line and the following code group as a clause (clause).

The following example:

If expression:    suiteelif expression:    Suite else:    Suite
Print output

The print default output is newline, and if you want to implement no newline, add end= ""to the end of the variable:

X= "A" y= "B" # newline output print (x) print (y) print ('---------') # No Line break output print (x, end= "") Print (Y, end= "")

The result of the above instance execution is:

AB---------a b 
Import and From...import

Import the appropriate modules in Python using Import or from...import.

Import the entire module (somemodule) in the format: import somemodule

Import a function from a module in the format: from somemodule import somefunction

Import multiple functions from a module in the format: from somemodule import Firstfunc, Secondfunc, Thirdfunc

Import all functions in a module in the format: from somemodule import *

Importing the SYS module

Import sys print (' ================python import mode========================== ');p rint (' command line arguments: ') for I in SYS.ARGV: Print (i) print (' \ n python path ', Sys.path)

Output:

Importing the Argv,path member of the SYS module

From sys import Argv,path # import specific member print (' ======python from import======= ') print (' Path: ', path) # because the path member is already imported, So there's no need to add sys.path when referencing here.

Output:

Python Syntax Basics

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.