A summary of some basic syntax of Python

零到壹度
Release: 2018-03-31 14:19:10
Original
1744 people have browsed it

This article is mainly to share with you a summary of some basic syntax of Python. Friends who need it can take a look.

Python Basic Syntax

The Python language has many similarities with languages ​​such as Perl, C and Java. However, there are some differences.

In this chapter we will learn the basic syntax of Python so that you can quickly learn Python programming.


The first Python program

Interactive programming

Interactive programming does not require the creation of script files. Code is written through the interactive mode of the Python interpreter.

On Linux, you only need to enter the Python command on the command line to start interactive programming. The prompt window is 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.
>>>
Copy after login

On Windows, the default interactive program has been installed when installing Python. Programming client, the prompt window is as follows:

Enter the following text information in the python prompt, and then press the Enter key to see the running effect:

>>> print "Hello, Python!";
Copy after login

In Python In version 2.7.6, the output result of the above example is as follows:

Hello, Python!
Copy after login
Copy after login
Copy after login
Copy after login

Scripted programming

Call the interpreter through script parameters to start executing the script until the script is executed. When the script execution is complete, the interpreter is no longer available.

Let us write a simple Python script program. All Python files will have the extension .py. Copy the following source code to the test.py file.

print "Hello, Python!";
Copy after login

Here, it is assumed that you have set the Python interpreter PATH variable. Run the program using the following command:

$ python test.py
Copy after login

Output result:

Hello, Python!
Copy after login
Copy after login
Copy after login
Copy after login

Let’s try another way to execute the Python script. Modify the test.py file as follows:

#!/usr/bin/python
print "Hello, Python!";
Copy after login

Here, assuming that your Python interpreter is in the /usr/bin directory, use the following command to execute the script:

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

Output results:

Hello, Python!
Copy after login
Copy after login
Copy after login
Copy after login

Python identifier

In Python, identifiers consist of letters, numbers, and underscores.

In Python, all identifiers can include English, numbers, and underscores (_), but they cannot start with a number.

Identifiers in Python are case-sensitive.

Identifiers starting with an underscore have special meaning. Starting with a single underscore _foo represents class attributes that cannot be accessed directly. They need to be accessed through the interface provided by the class and cannot be imported using from xxx import *;

以双下划线开头的 __foo 代表类的私有成员;以双下划线开头和结尾的 __foo__ 代表 Python 里特殊方法专用的标识,如 __init__() 代表类的构造函数。

Python 可以同一行显示多条语句,方法是用分号 ; 分开,如:

>>> print 'hello';print 'runoob';
hello
runoob
Copy after login

Python 保留字符

下面的列表显示了在Python中的保留字。这些保留字不能用作常数或变数,或任何其他标识符名称。

所有 Python 的关键字只包含小写字母。

andexecnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
defifreturn
delimporttry
elifinwhile
elseiswith
exceptlambdayield

行和缩进

学习 Python 与其他语言最大的区别就是,Python 的代码块不使用大括号 {} 来控制类,函数以及其他逻辑判断。python 最具特色的就是用缩进来写模块。

缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行。如下所示:

if True:
    print "True"else:
  print "False"
Copy after login

以下代码将会执行错误:

#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:test.pyif True:
    print "Answer"
    print "True"else:
    print "Answer"
    # 没有严格缩进,在执行时会报错
  print "False"
Copy after login

执行以上代码,会出现如下错误提醒:

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

IndentationError: unindent does not match any outer indentation level错误表明,你使用的缩进方式不一致,有的是 tab 键缩进,有的是空格缩进,改为一致即可。

如果是 IndentationError: unexpected indent 错误, 则 python 编译器是在告诉你"Hi,老兄,你的文件里格式不对了,可能是tab和空格没对齐的问题",所有 python 对格式要求非常严格。

因此,在 Python 的代码块中必须使用相同数目的行首缩进空格数。

建议你在每个缩进层次使用 单个制表符两个空格四个空格 , 切记不能混用


多行语句

Python语句中一般以新行作为语句的结束符。

但是我们可以使用斜杠( \)将一行的语句分为多行显示,如下所示:

total = item_one + \
        item_two + \
        item_three
Copy after login

语句中包含 [], {} 或 () 括号就不需要使用多行连接符。如下实例:

days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']
Copy after login

Python 引号

Python 可以使用引号( ' )、双引号( " )、三引号( '''""" ) 来表示字符串,引号的开始与结束必须的相同类型的。

其中三引号可以由多行组成,编写多行文本的快捷语法,常用于文档字符串,在文件的特定地点,被当做注释。

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

Python注释

python中单行注释采用 # 开头。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py
# 第一个注释print "Hello, Python!";  # 第二个注释
Copy after login

输出结果:

Hello, Python!
Copy after login
Copy after login
Copy after login
Copy after login

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

name = "Madisetti" # 这是一个注释
Copy after login

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

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

'''
这是多行注释,使用单引号。
这是多行注释,使用单引号。
这是多行注释,使用单引号。
'''"""
这是多行注释,使用双引号。
这是多行注释,使用双引号。
这是多行注释,使用双引号。
"""
Copy after login

Python空行

函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。

空行与代码缩进不同,空行并不是Python语法的一部分。书写时不插入空行,Python解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码,便于日后代码的维护或重构。

记住:空行也是程序代码的一部分。


等待用户输入

下面的程序执行后就会等待用户输入,按回车键后就会退出:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
raw_input("按下 enter 键退出,其他任意键显示...\n")
Copy after login

以上代码中 ,\n 实现换行。一旦用户按下 enter(回车) 键退出,其它键显示。


同一行显示多条语句

Python可以在同一行中使用多条语句,语句之间使用分号(;)分割,以下是一个简单的实例:

#!/usr/bin/python
import sys; x = 'runoob'; sys.stdout.write(x + '\n')
Copy after login

执行以上代码,输入结果为:

$ python test.py
runoob
Copy after login

Print 输出

print 默认输出是换行的,如果要实现不换行需要在变量末尾加上逗号 ,

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

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

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

# 不换行输出
print x,y
Copy after login

以上实例执行结果为:

a
b
---------
a b a b
Copy after login

多个语句构成代码组

缩进相同的一组语句构成一个代码块,我们称之代码组。

像if、while、def和class这样的复合语句,首行以关键字开始,以冒号( : )结束,该行之后的一行或多行代码构成代码组。

我们将首行及后面的代码组称为一个子句(clause)。

如下实例:

if expression : 
   suite 
elif expression :  
   suite  
else :  
   suite
Copy after login

命令行参数

很多程序可以执行一些操作来查看一些基本信息,Python 可以使用 -h 参数查看各参数帮助信息:

$ 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. ]
Copy after login

我们在使用脚本形式执行 Python 时,可以接收命令行输入的参数,具体使用可以参照 Python 命令行参数。

The above is the detailed content of A summary of some basic syntax of Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!