Getting Started with Python: basic syntax

Source: Internet
Author: User

For most of the transition from other programming languages to Python, it's more or less customary. If you use the syntax of other programming languages to write Python code, a wall-up is unavoidable.

This article is based on the official documentation I've read for two hours (Python 2.7: https://docs.python.org/2/tutorial/index.html, As for the reason I studied python2.x: work needed),

Extract the important details from it to avoid stepping on the pits again.

First a Python file (foo.py):

#!python#-*-coding:utf-8-*-" "python Comments: Multiline comments: 3 single or 3 double quotation marks in pairs (for example, the current position) single-line comment: Using #" "#defines a Foo function to print the specified msg count times"""params:count:int, print msg:string, message content usefor: When printing multiple times, whether a for loop is used. Raise:valueerror: When Count<0 is thrown"""defFoo (count=1, msg='Hello'+' '+"Foo", usefor=1):    ifCount <0:RaiseValueError ('Count < 0')    ifUsefor:#0,1 can be used as a bool decision        Print("print use for, Count ="+ bytes (count) +" :")         forIinchRange (count):#range (n), generates a list from 0 to N, which can be used as an index            Print(msg+' '+bytes (i))Else:        Print("print Use while, Count ="+ bytes (count) +" :") I=0 whileI <Count:Print(msg+" "+bytes (i)) I+=1#Python does not support the i++ notation, supporting the i+=if __name__=='__main__' :     Print('Main in foo.py') foo (2,usefor=1) foo (usefor=0, count=3); Foo (-1)    

    • File header
      • Specify the file Interpreter
      • Specify file Encoding
    • Comments
    • code block, indent
    • Basic data types
      • String
      • Number
      • Boolean
    • Control statements
      • If, elif, else
      • Loop:for, while
    • Program Entry: Main function

1. File header

As a scripting language, the file header specifies some execution environment, and so on, is a very common thing. It is common in the shell.

The same is true for Python scripts:

1.1 Specifying the Interpreter

scripting language, very common configuration:

#!/bin/sh           Shell Script #!/usr/bin/perl     perl script #!/usr/bin/python   python script #!/usr/bin/python3  python3 Script # !/usr/bin/python2  Python2 script and sometimes not quite clear about the full pathname of the script interpreter, or the development environment is different from the installation path of the running environment. To ensure compatibility, you can also write: #!/usr/bin/env Python3
This will automatically search the absolute path of the script interpreter when it runs.
1.2 Specifying the file encoding

The default encoding of the Py file is ASCII, and many of the above scripts are not supported by ASCII, so you need to specify the file encoding. The format is:

# -*-coding:encoding-*-

2. Comments

notes for Python:

    Multiline comment: A pair of 3 single quotes or 3 double quotation marks (for example, the current position)    line Comment: Use #

3, code block, indentation

code block : from the foo.py file above, it is easy to see that the code block begins with a colon: Whether it's a function definition, if,else, or loop (for, while)

is used: As the beginning of the code block. Does not include a block of code with {}.

Indentation: In a Python program, it does not use {} to include blocks of code, and to maintain blocks of code with indentation. Instead of writing tab, use 4 spaces for indentation.

4. Basic data Type 4.1 String4.2 Number4.3 Boolean

A boolean similar to Javascript,python is also changeable.

The following cases are false:
1.None
2.False
3. Any type of number 0, including 0,0.0,0l,0j
4. Empty sequence (sequence) or map (mapping) Type Object
5. For objects of user-defined type, if their class defines a __nonzero__ () or __len__ () special method and returns false or 0

For the last rule, there are a few things to note:
1. If the class does not have any of these two methods defined, then this type of object truth test is always true
2. If the class defines both __nonzero__ () and __len__ (), only the return value of the __nonzero__ () is referenced

The following cases are FALSE:1.NONE2.FALSE3. Any type of number 0, including 0,0.0,0l,0j4. Empty sequence (sequence) or map (mapping) Type Object 5. For objects of user-defined type, if their class defines __ nonzero__ () or __len__ () special method and returns false or 0
For the last rule, there are a few things to note: 1. If the class does not have any of the two methods defined, then this type of object truth test is always True2. If the class defines both __nonzero__ () and __len__ (), only the __nonzero__ () is referenced. The return value

Getting Started with Python: basic syntax

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.