Python novice Quick Start Basics Tutorial - Syntax

## Python program

Interactive Programming

Interactive programming not need to create a script file that is coming through interactive mode Python interpreter code.

On linux you just type Python commands in the command line to start the interactive programming, prompt as follows:

$ python
Python 2.7.6 (default, Sep  9 2014, 15:04:36) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

When installed on a Window it has been the default Python interactive programming client installation, prompt as follows:

Enter the following text message python prompt, and then press Enter to view operating results:

print “Hello, Python!”;

In Python version 2.7.6, the above examples of output results are as follows:

Hello, Python!

## Scripted Programming

Call script parameters through the interpreter starts executing the script until the script is finished. When the script finishes, the interpreter is no longer valid.

Let's write a simple Python script. All files will be Python .py extension. The following source code copied to test.py file.

print "Hello, Python!";

Here, assuming you've set up a Python interpreter PATH variable. Use the following command to run the program:


$ python test.py

Output:


Hello, Python!

Let's try another way to execute Python scripts. Modify test.py file as follows:


#!/usr/bin/python

print "Hello, Python!";

Here, suppose your Python interpreter / usr / bin directory, execute the script using the following command:


$ chmod +x test.py     # 脚本文件添加可执行权限
$ ./test.py

Output:


Hello, Python!

## Python identifiers

In Python, identified by letters, numbers, underscores.

In Python, all identifiers can include letters, numbers, and the underscore (_), but can not start with a number.

Python identifier is case sensitive.

Identifiers beginning with an underscore have a special significance. Single begin underscore _foorepresentative can not directly access the class attributes, accessed through the interface provided by class, can not be from xxx import *introduced;

In the beginning of the double-underlined __fooprivate members of the representative class; double-underlined start and end of __foo__the representative particular method in Python specific identification, such as a __init__()constructor of the class representatives.

Python same row can display multiple statements, method is to use a semicolon; separated, such as:

>>> print 'hello';print 'runoob';
hello
runoob

#Python reserved characters

The following list shows the reserved words in Python. These words can not be used to retain a constant or variable, or any other identifier names.

All Python keywords contain only lowercase letters.

# Line breaks and indentation

Learning Python and the biggest difference is in other languages, the Python code blocks without using braces {} class controlled, functions, and other logic judgment. python most unique is to use indentation to write modules.

The number of spaces to indent is variable, but all of the code block statement must contain the same number of spaces to indent, this must be strictly enforced. As follows:

if True:
    print "True"
else:
  print "False"
 

以下代码将会执行错误:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py

if True:
    print "Answer"
    print "True"
else:
    print "Answer"
    # 没有严格缩进,在执行时会报错
  print "False"

The implementation of the above code, will appear the following error reminder:

$ python test.py  
  File "test.py", line 10
    print "False"
                ^
IndentationError: unindent does not match any outer indentation level

IndentationError: unindent does not match any outer indentation level error indicates inconsistent indentation you use, some tab key to indent, plenty of spaces to indent, you can change to be consistent.

If IndentationError: unexpected indent error, the python compiler is telling you "Hi, buddy, your file format wrong, may be aligned tab and space no problem", the format of all the python was very strict.

Thus, the number of rows must use the same number of spaces in the first indent Python code block.

We suggest you use a single tab or two spaces or four spaces for each indentation level, remember not to mix

# Multi-line statement

Python statements generally a newline terminator statement.

But we can use the slash (\) line will be divided into multiple lines of statements, as follows:

total = item_one + \
        item_two + \
        item_three

Statement includes [], {}, or () parenthesis not need to use multi-line connector. Following examples:


days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

#Python quotes

Python can use quotation marks ( '), double quote ( "), tris quotation marks (' '' or '' ') for strings, must start and end marks of the same type.

Three of the quotes may consist of multiple lines, multiple lines of text written in shorthand syntax, commonly used in the documentation string, the file in a specific location, is treated as a comment.

word = 'word'
sentence = "这是一个句子。"
paragraph = """这是一个段落。
包含了多个语句"""

#Python comments

python using the single-line comments begin with #.

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py

# 第一个注释
print "Hello, Python!";  # 第二个注释

注释可以在语句或表达式行末:

name = "Madisetti" # 这是一个注释

python 中多行注释使用三个单引号(''')或三个双引号(""")。


#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py


'''
这是多行注释,使用单引号。
这是多行注释,使用单引号。
这是多行注释,使用单引号。
'''

"""
这是多行注释,使用双引号。
这是多行注释,使用双引号。
这是多行注释,使用双引号。
"""

#Python blank line

Separated by a blank line between the function or class method, it indicates start a new code. Also separated by a blank line between the class and the function entry, function entry to highlight start.

Blank lines of code indentation with a different part of the blank line is not a Python syntax. Do not insert a blank line when writing, Python interpreter to run it will not go wrong. However, the role that the partition blank line meaning two different functions or code to facilitate future maintenance or reconstructed code.

Remember: a blank line is part of the program code.

# Wait for user input

The following program will be executed after waiting for user input, press the Enter key will exit:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

raw_input("按下 enter 键退出,其他任意键显示...\n")

The above code, \ n newline achieved. Once the user presses Enter (Enter) key to exit, the other key display.

Display multiple statements on the same line

Python can be used in the same row multiple statements, statements using a semicolon (;) is divided, the following is a simple example:

#!/usr/bin/python

import sys; x = 'runoob'; sys.stdout.write(x + '\n')

Execution code above, enter the result of:

$ python test.py
runoob

#Print output

The default print output is the new line, if you want to achieve in the end do not need to wrap variables comma ,

#!/usr/bin/python
# -*- coding: UTF-8 -*-

x="a"
y="b"
# 换行输出
print x
print y

print '---------'
# 不换行输出
print x,
print y,

# 不换行输出
print x,y

The above examples Implementation of the results:


a
b
---------
a b a b

A plurality of code groups # Syntactically

Indent the same set of statements constituting a code block, we call code group.

Like compound statements such as if, while, def and class, the first line to start with keywords, a colon (:) end, following the line of code constitutes one or more lines of code groups.

We will be the first line and the following code group called a clause (clause).

Following examples:

if expression : 
   suite 
elif expression :  
   suite  
else :  
   suite 

# Command line arguments

Many programs can perform some operations to view some basic information, Python can use the -h parameter to view the help information for each parameter:

$ python -h 
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... 
Options and arguments (and corresponding environment variables): 
-c cmd : program passed in as string (terminates option list) 
-d     : debug output from parser (also PYTHONDEBUG=x) 
-E     : ignore environment variables (such as PYTHONPATH) 
-h     : print this help message and exit 
 
[ etc. ] 

When we execute Python scripts using the form, you can receive parameters on a command line

Recommended reading:

As a someone who has, I have to tell you to ask the older cattle is really important, so that you can take a lot less detours, do not be afraid shame, no face, the face value of some money? Learn a real skill is most important. No skill called really no face. python technology sharing , so that your future is no longer confused.

Recommended reading:

How zero-based learning Python as a programming language?

After learning python12 hours and tell you that you really did not want to learn python so difficult!

Programmed learning, knowledge payment is a regular phenomenon, realized knowledge is more important!

Programmer's skill tree, determines the height of a lifetime career

More Internet industry consulting, programming skills, learning to share public concern number id:! Mtbcxx

Guess you like

Origin blog.csdn.net/weichen090909/article/details/90678779