Python - 基本语法

Python - 基本语法 首页 / Python2入门教程 / Python - 基本语法

Python语言与Perl C Java有许多相似之处。但是,两种语言之间存在一定的区别。

让无涯教程以不同的编程模式执行程序。

交互模式编程

在不将脚本文件作为参数传递的情况下调用解释器将显示以下提示-

$python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

在Python提示符下键入以下文本,然后按回车键-

>>> print "Hello, Python!"

如果您正在运行新版本的Python,则需要使用带括号的print语句,如 print(" Hello,Python!"); 

Hello, Python!

脚本模式编程

使用脚本参数调用解释器将开始执行脚本,并一直持续到脚本完成为止。

用脚本编写一个简单的Python程序。 Python文件的扩展名为 .py 。在test.py文件中键入以下源代码-

print "Hello, Python!"

假设您在PATH变量中设置了Python解释器。现在,尝试按以下方式运行此程序-

链接:https://www.learnfk.comhttps://www.learnfk.com/python/python-basic-syntax.html

来源:LearnFk无涯教程网

$python test.py

这产生以下输出-

Hello, Python!

尝试另一种执行Python脚本的方法。这是修改后的test.py文件-

#!/usr/bin/python

print "Hello, Python!"

假设您在/usr/bin目录中有Python解释器。现在,尝试按以下方式运行此程序-

$chmod +x test.py     # 这是为了使文件可执行
$./test.py

这产生以下输出-

Hello, Python!

Python 标识符

Python标识符是用于标识变量,函数,类,模块或其他对象的名称。标识符以字母A到Z或a到z或下划线(_)开头,后跟零个或多个字母,下划线和数字

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

这是Python标识符的命名约定-

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

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

    无涯教程网

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

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

Python 关键字

以下列表显示了Python关键字,有Python关键字仅包含小写字母。

and execnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
def ifreturn
delimporttry
elif inwhile
elseis with
except lambdayield

Python 行缩进

Python没有提供大括号来指示用于类和函数定义或流控制的代码块。代码块由行缩进表示,行缩进严格执行。

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

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

但是,以下块会产生错误-

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

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

#!/usr/bin/python

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=raw_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中的语句通常以换行符结尾。但是,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/python

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

这产生以下输出-

Hello, Python!

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

name="Madisetti" # 这是注释

您可以注释多行,如下所示:

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

Python解释器也会忽略以下三引号字符串,并且可以将其用作多行注释:

'''
This is a multiline
comment.
'''

Raw_input输入

程序的以下行显示提示,并显示"Press Enter key to exit"的语句,并等待用户采取行动-

#!/usr/bin/python

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

在这里,"\n\n"用于在显示实际行之前创建两个新行。用户按下键后,程序结束。这是一个使控制台窗口保持打开状态的好方法,直到用户完成应用程序操作为止。

Python 单行语句

给定两个分号(;)都不能在一个新的代码块中开始,因此该分号允许在一行上显示多个语句。这是使用分号的示例片段-

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

Python 多行语句

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

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

命令行参数

可以运行许多程序来为您提供有关应如何运行的一些基本信息。 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. ]

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

面试现场 -〔白海飞〕

全栈工程师修炼指南 -〔熊燚(四火)〕

说透敏捷 -〔宋宁〕

检索技术核心20讲 -〔陈东〕

操作系统实战45讲 -〔彭东〕

全链路压测实战30讲 -〔高楼〕

郭东白的架构课 -〔郭东白〕

Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕

AI 应用实战课 -〔黄佳〕

好记忆不如烂笔头。留下您的足迹吧 :)