开发学院

您的位置:首页>教程>正文

教程正文

Python 3 基本语法

Python 3  基本语法

  Python语言与Perl、C和Java有许多相似之处。当然语言之间有一些明显的差异。

第一个Python程序

  让我们以不同的编程模式来执行程序。

交互式模式编程

  在不传递脚本文件作为参数的情况下执行python会出现以下提示:

$ python

Python 3.3.2 (default, Dec 10 2013, 11:35:01)
[GCC 4.6.3] on Linux
Type "help", "copyright", "credits", or "license" for more information.
>>>
On Windows:

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>

  在Python提示符下键入以下文本,然后按Enter:

>>> print ("Hello, Python!")

  如果你运行的是Python的旧版本( Python 2.x ),print函数的括号是可选的。这会产生以下结果。

Hello, Python!

脚本模式编程

  使用脚本作为参数执行python,解释器会执行脚本,并持续到脚本完成。脚本完成后,解释器自动退出。

  让我们编写一个简单的Python程序。Python文件的扩展名为. py。在test.py 文件中键入以下代码。

print ("Hello, Python!")

  我们假设您在PATH变量中已经正确设置了Python解释器。现在,按如下方式运行这个程序。

On Linux

$ python test.py

  上述操作产生如下结果:

Hello, Python!

On Windows

C:\Python34>Python test.py

  上述操作产生如下结果:

Hello, Python!

  让我们尝试另一种在Linux中执行Python脚本的方法。这是修改后的test.py文件?

#!/usr/bin/python3
print ("Hello, Python!")

  我们假设您在/usr/bin目录中有Python解释器。现在,试着按如下方式运行这个程序。

$ chmod +x test.py     # This is to make file executable
$./test.py

  上述操作产生如下结果:

Hello, Python!

Python标识符

  Python标识符是用于标识变量、函数、类、模块或其他对象的名称。标识符支持大小写A到Z以及下划线(_)开头,后面跟0个或多个字母、下划线和数字(0到9)。

  Python不允许在标识符中使用标点符号,如@、$、%等。Python是区分大小写的编程语言。因此,在Python中,Manpower和manpower是两个不同的标识符。

  以下是Python标识符的命名约定。

  •     类名以大写字母开头。所有其他标识符都以小写字母开头。

  •     以单个下划线开头的标识符表示该标识符是私有的。

  •     以两个下划线开头的标识符表示强私有标识符。

  •     如果标识符也以两个尾随下划线结尾,则标识符是语言定义的特殊名称。

python保留字

andexecnotasfinally
orassertforpassbreak
fromprintclassglobalraise
continueifreturndefimport
trydelinwhileelif
iswithelselambdayield
except




行和缩进

  Python不使用大括号( { } )来表示类和函数定义或流控制的代码块。代码块由行缩进表示,行缩进是严格执行的。

  缩进中的空格数是可变的,但是块中的所有语句都必须缩进相同的数量。例如。

if True:
print ("True")

else:
print ("False")

  但是,以下块会生成错误。

if True:
print ("Answer")
print ("True")

else:
print ("Answer")
print ("False")

  因此,在Python中,所有缩进相同空格数的连续行将形成一个块。以下示例有各种语句块。

  注意,此时不要花过多的时间理解逻辑。即使没有大括号,也要确保你理解各种各样的块。

#!/usr/bin/python3

import sys

try:
   # open file stream
   file = open(file_name, "w")

except IOError:
   print ("There was an error writing to", file_name)
   sys.exit()
print ("Enter '", file_finish,)
print "' When finished"
while file_text != file_finish:
   file_text = raw_input("Enter text: ")
   if file_text == file_finish:
      # close the file
  file.close
      break
   file.write(file_text)
   file.write("\n")
file.close()
file_name = input("Enter filename: ")
if len(file_name) == 0:
   print ("Next time please enter something")
   sys.exit()

try:
   file = open(file_name, "r")

except IOError:
   print ("There was an error reading file")
   sys.exit()
file_text = file.read()
file.close()
print (file_text)

多行语句

  Python中的语句通常以新行结束。然而,Python允许使用行延续字符(\)来表示该行应该继续。例如?

total = item_one + \
        item_two + \
        item_three

  包含在[ ],{ },或( )括号中的语句不需要使用行延续字符。例如。

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

Python中的引号

  Python接受单引号( ' )、双引号( " )和三引号( ' ' '或" " )来表示字符串文字,只要相同类型的引号在字符串的开头和结尾。

  三重引号用于跨越多行字符串。例如,以下都是合法的。

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

Python中的注释

  不在字符串文字内的符号(#)是注释的开头。#之后的所有字符,直到物理行的末尾,都是注释的一部分,Python解释器会忽略它们。

#!/usr/bin/python3

# First comment
print ("Hello, Python!") # second comment

  上述代码产生以下结果。

Hello, Python!

  您可以在语句或表达式后的同一行键入注释。

name = "Madisetti" # This is again comment

  Python不支持多行注释,你必须对每一行单独注释。

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

使用空行

  一行只包含空格,可能带有注释,称为空行,Python完全忽略它。

  在交互式解释器会话中,必须输入空的物理换行来终止多行语句。

等待用户输入

  程序的下一行显示提示和语句“按enter键退出”,然后等待用户采取行动?

#!/usr/bin/python3

input("\n\nPress the enter key to exit.")

  这里,“\n\n”用于在显示实际行之前创建两行新行。一旦用户按下键,程序结束。这是一个很好的技巧,在用户完成应用程序之前,保持控制台窗口打开。

单行上的多个语句

  分号(;)允许单行上有多个语句,因为没有语句开始新的代码块。下面是使用分号的示例。

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

多个语句组作为套件

  在Python中,构成单个代码块的单个语句组称为套件。复合语句或复杂语句,如if、while、def和class需要标题行和套件。

  标题行以语句开头(用关键字),以冒号( : )结尾,后面跟着一行或多行组成套件。例如。

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

命令行参数

$ 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. ]