Python - 基础

Python-开篇


Python是一种通用的解释型,交互式,面向对象的高级编程语言。它是由Guido van Rossum在1985-1990年间创建的。与Perl一样,Python源代码也可以在GNU通用公共许可证(GPL)下获得。Python是根据电视节目“ Monty Python's Flying Circus”命名的,而不是以Python(蛇)命名。

Python 3.0于2008年发布。尽管该版本应该向后不兼容,但后来又将其许多重要功能向后移植到与2.7版本兼容。本教程对Python 3版本编程语言有足够的了解。

为什么要学习Python 3?


Python是一种高级,解释性,交互式和面向对象的脚本语言。Python的设计具有很高的可读性。与其他语言使用标点符号一样,它经常使用英语关键字,并且其语法结构比其他语言更少。

对于学生和在职专业人员,Python是必不可少的工具,尤其是当他们在Web Development Domain中工作时,他们必须成为一名出色的软件工程师。我将列出学习Python的一些关键优势:

  • Python被解释 -Python在运行时由解释器处理。在执行程序之前,无需编译程序。这类似于PERL和PHP。

  • Python是交互式的 -您实际上可以坐在Python提示符下并直接与解释器进行交互以编写程序。

  • Python是面向对象的-Python支持将对象封装在代码中的面向对象的样式或编程技术。

  • Python是一种初学者的语言 -Python对于初学者来说是一种很棒的语言,它支持从简单文本处理到WWW浏览器再到游戏的各种应用程序的开发。

Python的特征


以下是python的重要特征-

  • 它支持功能性和结构化编程方法以及OOP。

  • 它可以用作脚本语言,也可以编译为字节码以构建大型应用程序。

  • 它提供了非常高级的动态数据类型,并支持动态类型检查。

  • 它支持自动垃圾收集。

  • 它可以轻松地与C,C ++,COM,ActiveX,CORBA和Java集成。

使用Python的Hello World。


为了给您带来一些关于Python的兴奋,我将为您提供一个小的常规Python Hello World程序,您可以使用Demo链接进行尝试。

print "Hello, Python!"

Python的应用


如前所述,Python是网络上使用最广泛的语言之一。我将在这里列出其中一些:

  • 易于学习 -Python具有少量关键字,简单的结构和清晰定义的语法。这使学生可以快速掌握语言。

  • 易于阅读 -Python代码更清晰地定义并且对眼睛可见。

  • 易于维护 -Python的源代码非常易于维护。

  • 广泛的标准库 -Python的大部分库在UNIX,Windows和Macintosh上具有很高的可移植性和跨平台兼容性。

  • 交互式模式 -Python支持交互式模式,该模式允许交互式测试和调试代码片段。

  • 可移植 -Python可在多种硬件平台上运行,并且在所有平台上具有相同的接口。

  • 可扩展的 -您可以将低级模块添加到Python解释器。这些模块使程序员能够添加或自定义其工具,从而提高效率。

  • 数据库 -Python提供了到所有主要商业数据库的接口。

  • GUI编程 -Python支持可以创建并移植到许多系统调用,库和Windows系统(例如Windows MFC,Macintosh和Unix的X Window系统)的GUI应用程序。

  • 可扩展 -Python提供比Shell脚本更好的结构和对大型程序的支持。

适合人群


本教程是为希望将其Python技能升级到Python 3的软件程序员设计的。本教程还可以用于从头学习Python编程语言。

先决条件


您应该对计算机编程术语有基本的了解。对任何一种编程语言都有基本的了解是加分的。

Python 3的新增功能


future 模块
Python 3.x引入了一些Python 2不兼容的关键字和功能,可以通过Python 2中的内置future模块导入这些关键字和功能。如果您打算为代码提供Python 3.x支持,建议使用future导入。

例如,如果我们想在Python 2中使用Python 3.x的整数除法,请添加以下import语句。

from __future__ import division

打印功能


Python 3中最显着和最广为人知的更改是如何使用打印功能。现在必须在打印功能中使用括号()。在Python 2中是可选的。

print "Hello World" #is acceptable in Python 2
print ("Hello World") # in Python 3, print must be followed by ()

默认情况下,print()函数在末尾插入新行。在Python 2中,可以通过在最后加上','来抑制它。在Python 3中,“ end =''”会附加空格而不是换行符。

print x,           # Trailing comma suppresses newline in Python 2
print(x, end=" ")  # Appends a space instead of a newline in Python 3

从键盘读取输入


Python 2有两个版本的输入函数,input()和raw_input()。如果输入的数据包含在引号“或”中,则input()函数会将其视为字符串,否则将其视为数字。

在Python 3中,不建议使用raw_input()函数。此外,接收到的数据始终被视为字符串。

In Python 2

>>> x = input('something:') 
something:10 #entered data is treated as number
>>> x
10

>>> x = input('something:')
something:'10' #entered data is treated as string
>>> x
'10'

>>> x = raw_input("something:")
something:10 #entered data is treated as string even without ''
>>> x
'10'

>>> x = raw_input("something:")
something:'10' #entered data treated as string including ''
>>> x
"'10'"

In Python 3

>>> x = input("something:")
something:10
>>> x
'10'

>>> x = input("something:")
something:'10' #entered data treated as string with or without ''
>>> x
"'10'"

>>> x = raw_input("something:") # will result NameError
Traceback (most recent call last):
   File "<pyshell#3>", line 1, in 
  <module>
   x = raw_input("something:")
NameError: name 'raw_input' is not defined

整数部


在Python 2中,将两个整数相除的结果四舍五入为最接近的整数。结果,3/2将显示1。为了获得浮点除法,必须将分子或分母明确用作浮点数。因此,如果3.0 / 2或3 / 2.0或3.0 / 2.0将得出1.5

Python 3默认将3/2评估为1.5,这对于新程序员来说更加直观。

Unicode表示


如果要存储为Unicode,Python 2要求您用au标记字符串。

默认情况下,Python 3将字符串存储为Unicode。我们有Unicode(utf-8)字符串和2个字节的类:字节和字节数组。

xrange()函数已删除


在Python 2中,range()返回一个列表,而xrange()返回一个仅在需要时才生成范围内项目的对象,从而节省了内存。

在Python 3中,删除了range()函数,并将xrange()重命名为range()。此外,range()对象支持Python 3.2及更高版本中的切片。

引发例外


Python 2接受“旧”和“新”两种语法。如果我们不将括号中的异常参数括起来,Python 3会引发SyntaxError。

raise IOError, "file error" #This is accepted in Python 2
raise IOError("file error") #This is also accepted in Python 2
raise IOError, "file error" #syntax error is raised in Python 3
raise IOError("file error") #this is the recommended syntax in Python 3

异常参数
在Python 3中,异常参数应使用'as'关键字声明。

except Myerror, err: # In Python2
except Myerror as err: #In Python 3

next()函数和.next()方法


在Python 2中,允许将next()作为生成器对象的方法。在Python 2中,还接受了对生成器对象进行迭代的next()函数。但是,在Python 3中,将next(0作为生成器方法停用,并引发AttributeError。

gen = (letter for letter in 'Hello World') # creates generator object
next(my_generator) #allowed in Python 2 and Python 3
my_generator.next() #allowed in Python 2. raises AttributeError in Python 3

2to3实用程序


通常将2to3.py脚本与Python 3解释器一起安装在tools / scripts文件夹中。它读取Python 2.x源代码,并应用一系列修复程序将其转换为有效的Python 3.x代码。

Here is a sample Python 2 code (area.py):

def area(x,y = 3.14): 
   a = y*x*x
   print a
   return a

a = area(10)
print "area",a

To convert into Python 3 version:

$2to3 -w area.py

Converted code :

def area(x,y = 3.14): # formal parameters
   a = y*x*x
   print (a)
   return a

a = area(10)
print("area",a)

Python 3-概述


Python是一种高级,解释性,交互式和面向对象的脚本语言。Python的设计具有很高的可读性。它经常使用英语关键字,而其他语言则使用标点符号。它的语法结构比其他语言少。

  • Python被解释 -Python在运行时由解释器处理。在执行程序之前,无需编译程序。这类似于PERL和PHP。

  • Python是交互式的 -您实际上可以坐在Python提示符下并直接与解释器进行交互以编写程序。

  • Python是面向对象的-Python支持将对象封装在代码中的面向对象的样式或编程技术。

  • Python是一种初学者的语言 -Python对于初学者来说是一种很棒的语言,它支持从简单文本处理到WWW浏览器再到游戏的各种应用程序的开发。

Python的历史


Python由Guido van Rossum在80年代末和90年代初在荷兰国家数学和计算机科学研究所开发。

Python衍生自许多其他语言,包括ABC,Modula-3,C,C ++,Algol-68,SmallTalk和Unix Shell和其他脚本语言。

Python受版权保护。与Perl一样,Python源代码现在可以在GNU通用公共许可证(GPL)下获得。

尽管Guido van Rossum仍然在指导其进展方面发挥着至关重要的作用,但Python现在由该研究所的核心开发团队维护。

1994年11月发布了Python1.0。2000年,发布了Python 2.0。Python 2.7.11是Python 2的最新版本。

同时,Python 3.0于2008年发布。Python3不向后兼容Python2。Python3的重点在于删除重复的编程构造和模块,以便“应该有一个-最好只有一个-显而易见的方法。” Python 3.5.1是Python 3的最新版本。

Python功能


Python的功能包括-

  • 易于学习 -Python具有少量关键字,简单的结构和清晰定义的语法。这使学生可以快速掌握语言。

  • 易于阅读 -Python代码更清晰地定义并且对眼睛可见。

  • 易于维护 -Python的源代码非常易于维护。

  • 广泛的标准库 -Python的大部分库在UNIX,Windows和Macintosh上具有很高的可移植性和跨平台兼容性。

  • 交互式模式 -Python支持交互式模式,该模式允许交互式测试和调试代码片段。

  • 可移植 -Python可在多种硬件平台上运行,并且在所有平台上具有相同的接口。

  • 可扩展的-您可以将低级模块添加到Python解释器。这些模块使程序员能够添加或自定义其工具,从而提高效率。

  • 数据库-Python提供了到所有主要商业数据库的接口。

  • GUI编程 -Python支持可以创建并移植到许多系统调用,库和Windows系统(例如Windows MFC,Macintosh和Unix的X Window系统)的GUI应用程序。

  • 可扩展 -Python提供比Shell脚本更好的结构和对大型程序的支持。

除了上述功能外,Python还有很多不错的功能。

  • 它支持功能性和结构化编程方法以及OOP。
  • 它可以用作脚本语言,也可以编译为字节码以构建大型应用程序。
  • 它提供了非常高级的动态数据类型,并支持动态类型检查。
  • 它支持自动垃圾收集。
  • 它可以轻松地与C,C ++,COM,ActiveX,CORBA和Java集成。

Python 3-环境设置


Python 3适用于Windows,Mac OS和大多数Linux操作系统。尽管Python 2可用于许多其他操作系统,但尚未提供对Python 3的支持或已将其删除。

本地环境设置


打开一个终端窗口,然后键入“ python”以查明它是否已经安装以及安装了哪个版本。

获取Python


Windows平台


此下载页面上提供了最新版本的Python 3(Python 3.5.1)的二进制文件。

可以使用以下不同的安装选项。

  • Windows x86-64可嵌入的zip文件
  • Windows x86-64可执行安装程序
  • Windows x86-64基于Web的安装程序
  • Windows x86可嵌入的zip文件
  • Windows x86可执行安装程序
  • Windows x86基于Web的安装程序

–为了安装Python 3.5.1,最低操作系统要求是Windows 7 SP1。对于3.0至3.4.x版本,可以使用Windows XP。

Linux平台


不同版本的Linux使用不同的软件包管理器来安装新软件包。

在Ubuntu Linux上,使用以下命令从终端安装Python 3。

$sudo apt-get install python3-minimal

从源安装

从Python的下载URL下载压缩的tarball- https: //www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz

Extract the tarball
tar xvfz Python-3.5.1.tgz  Configure  and  Install: cd Python-3.5.1  ./configure --prefix =  /opt/python3.5.1 make  
sudo make install

苹果系统


从此URL下载Mac OS安装程序-https: //www.python.org/downloads/mac-osx/

  • Mac OS X 64位/ 32位安装程序-python-3.5.1-macosx10.6.pkg
  • Mac OS X 32位i386 / PPC安装程序-python-3.5.1-macosx10.5.pkg

双击该程序包文件,然后按照向导说明进行安装。

最新的源代码,二进制文件,文档,新闻等可在Python的官方网站上找到-

Python官方网站-https : //www.python.org/
您可以从以下站点下载Python文档。该文档有HTML,PDF和PostScript格式。

Python文档网站 - www.python.org/doc/

设置路径


程序和其他可执行文件可以在许多目录中。因此,操作系统提供了列出其搜索可执行文件的目录的搜索路径。

重要特征是-

  • 路径存储在环境变量中,该变量是操作系统维护的命名字符串。此变量包含命令外壳和其他程序可用的信息。

  • path变量在Unix中被命名为PATH,在Windows中被命名为Path(Unix区分大小写; Windows不区分大小写)。

  • 在Mac OS中,安装程序将处理路径详细信息。要从任何特定目录调用Python解释器,必须将Python目录添加到路径中。

在Unix / Linux上设置路径


要将Python目录添加到Unix中特定会话的路径-

  • 在csh shell中 -键入setenv PATH“ $ PATH:/ usr / local / bin / python3”并按Enter。

  • 在bash shell(Linux)中 -键入export PYTHONPATH = / usr / local / bin / python3.4并按Enter。

  • 在sh或ksh shell中 -键入PATH =“ $ PATH:/ usr / local / bin / python3”并按Enter。

注意 -/ usr / local / bin / python3是Python目录的路径。

在Windows上设置路径


要将Python目录添加到Windows中特定会话的路径-

  • 在命令提示符下 -键入path%path%; C:\ Python并按Enter。

注意 -C:\ Python是Python目录的路径

Python环境变量


这是重要的环境变量,Python可以识别它们-

序号 变量与说明
1 PYTHONPATH
它的作用类似于PATH。这个变量告诉Python解释器在哪里可以找到导入程序的模块文件。它应该包括Python源库目录和包含Python源代码的目录。PYTHONPATH有时是由Python安装程序预设的。
2 PYTHONSTARTUP
它包含一个包含Python源代码的初始化文件的路径。每次启动解释器时都会执行该命令。在Unix中,它的名称为.pythonrc.py,其中包含用于加载实用程序或修改PYTHONPATH的命令。
3 PYTHONCASEOK
Windows中使用它来指示Python在import语句中查找第一个不区分大小写的匹配项。将此变量设置为任何值以激活它。
4 PYTHONHOME
它是替代的模块搜索路径。它通常嵌入在PYTHONSTARTUP或PYTHONPATH目录中,以简化切换模块库。

运行Python


有三种不同的启动Python的方式-

互动翻译


您可以从Unix,DOS或任何其他提供命令行解释器或Shell窗口的系统中启动Python。

在命令行输入python

立即在交互式解释器中开始编码。

$python             # Unix/Linux
or
python%             # Unix/Linux
or
C:>python           # Windows/DOS

这是所有可用命令行选项的列表-

序号 选项和说明
1 -d
提供调试输出
2 -O
生成优化的字节码(产生.pyo文件)
3 -S
不要在启动时运行导入站点来查找Python路径
4 -v
详细输出(对导入语句的详细跟踪)
5 -X
禁用基于类的内置异常(仅使用字符串);从版本1.6开始已过时
6 -c cmd
运行以cmd字符串形式发送的Python脚本
7 文件
从给定文件运行Python脚本

命令行脚本


可以在命令行上通过在应用程序上调用解释器来执行Python脚本,如以下示例所示。

$python  script.py          # Unix/Linux
or
python% script.py           # Unix/Linux
or 
C:>python script.py         # Windows/DOS

注意 -确保文件许可模式允许执行。

集成开发环境

如果您的系统上有支持Python的GUI应用程序,则也可以从图形用户界面(GUI)环境中运行Python。

  • Unix -IDLE是第一个用于Python的Unix IDE。

  • Windows - PythonWin是Python的第一个Windows界面,并且是带有GUI的IDE。

  • Macintosh-可以从主网站上获得Macintosh版本的Python和IDLE IDE,可以将其下载为MacBinary或BinHex文件。

如果您无法正确设置环境,则可以寻求系统管理员的帮助。确保正确设置了Python环境,并且工作正常。

–后续章节中给出的所有示例均使用Windows 7和Ubuntu Linux上可用的Python 3.4.1版本执行。

我们已经在线设置了Python编程环境,以便您在学习理论的同时可以在线执行所有可用的示例。随意修改任何示例并在线执行。

Python 3-基本语法


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

第一个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),则将括号用作打印功能是可选的。这产生以下结果-

Hello, Python!

脚本模式编程


使用脚本参数调用解释器将开始执行脚本,并一直持续到脚本完成为止。脚本完成后,解释器不再处于活动状态。

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

现场演示

print  ("Hello, Python!")

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

在Linux上

$ python test.py

这产生以下结果-

Hello, Python!

在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或a到z或下划线(_)开头,后跟零个或多个字母,下划线和数字(0到9)。

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

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

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

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

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

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

保留字


以下列表显示了Python关键字。这些是保留字,您不能将它们用作常量或变量或任何其他标识符名称。所有Python关键字仅包含小写字母。

and exec not
as finally or
assert for pass
break from print
class global raise
continue if return
def import try
del in while
elif is with
else lambda yield
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

file_finish = "end"
file_text = ""
contents=[]

file_name=input("Enter filename: ")
if len(file_name) == 0:
   print("Please enter filename")
   sys.exit()

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 = input("Enter text: ")
   contents.append(file_text)

   if file_text == file_finish:
      # close the file
      file.close()
      break

print(contents)
data = ' '.join([str(elem) for elem in contents])  
print(data)
file.write(data)
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

命令行参数


可以运行许多程序来为您提供有关应如何运行的一些基本信息。蟒蛇使您能够做到这一点- ^ 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.  ]

Python 3-变量类型


变量不过是用于存储值的保留内存位置。这意味着在创建变量时,将在内存中保留一些空间。

解释器根据变量的数据类型分配内存,并确定可以在保留内存中存储的内容。因此,通过为变量分配不同的数据类型,可以在这些变量中存储整数,小数或字符。

给变量赋值

Python变量不需要显式声明即可保留内存空间。为变量分配值时,声明自动发生。等号(=)用于为变量分配值。

=运算符左侧的操作数是变量的名称,=运算符右侧的操作数是存储在变量中的值。例如-

#!/usr/bin/python3

counter = 100          # An integer assignment
miles   = 1000.0       # A floating point
name    = "John"       # A string

print (counter)
print (miles)
print (name)

在这里,100、1000.0和“ John”分别是分配给计数器,里程和名称变量的值。这产生以下结果-

100
1000.0
John

多重分配

Python允许您同时为多个变量分配一个值。
例如-

a = b = c = 1

在这里,将创建一个整数对象,其值为1,并且所有三个变量都分配给相同的存储位置。您还可以将多个对象分配给多个变量。例如-

a, b, c = 1, 2, "john"

在此,分别将两个具有值1和2的整数对象分配给变量a和b,并将一个具有值“ john”的字符串对象分配给变量c。

标准数据类型

存储在存储器中的数据可以有多种类型。例如,一个人的年龄存储为数字值,而他或她的地址存储为字母数字字符。Python具有各种标准数据类型,这些数据类型用于定义可能的操作以及每种操作的存储方法。

Python具有五种标准数据类型-

  • 数值(Numbers)
  • 字符串(String)
  • 列表(List)
  • 元组(Tuple)
  • 字典(Dictionary)

Python数字

数字数据类型存储数值。数字对象是在您为其分配值时创建的。例如-

var1 = 1
var2 = 10

您也可以使用del语句删除对数字对象的引用。del语句的语法是-

del var1[,var2[,var3[....,varN]]]]

您可以使用del语句删除单个对象或多个对象。

例如-

del var
del var_a, var_b

Python支持三种不同的数字类型-

  • int(有符号整数)
  • float(浮点实数值)
  • complex(复数)
    Python3中的所有整数都表示为长整数。因此,没有长的单独的数字类型。

例子
这是一些数字的例子-

int float complex
10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3+e18 .876j
-0490 -90. -.6545+0J
-0x260 -32.54e100 3e+26J
0x69 70.2-E12 4.53e-7j

复数由x + yj表示的有序对实数浮点数组成,其中x和y是实数,j是虚数单位。

Python字符串


Python中的字符串被标识为用引号引起来的连续字符集。Python允许使用单引号或双引号。可以使用切片运算符([]和[:])来获取字符串的子集,其中的索引从字符串的开头开始为0,从-1到结尾。

加号(+)是字符串连接运算符,星号(*)是重复运算符。例如-

#!/usr/bin/python3

str = 'Hello World!'

print (str)          # Prints complete string
print (str[0])       # Prints first character of the string
print (str[2:5])     # Prints characters starting from 3rd to 5th
print (str[2:])      # Prints string starting from 3rd character
print (str * 2)      # Prints string two times
print (str + "TEST") # Prints concatenated string

这将产生以下结果-

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python列表


列表是Python复合数据类型中功能最多的。列表包含用逗号分隔并括在方括号([])中的项目。在某种程度上,列表与C中的数组相似。它们之间的区别之一是,属于列表的所有项目都可以具有不同的数据类型。

可以使用切片运算符([]和[:])访问列表中存储的值,其中的索引从列表开头的0开始,一直到-1结束。加号(+)是列表串联运算符,星号(*)是重复运算符。例如-

#!/usr/bin/python3

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print (list)          # Prints complete list
print (list[0])       # Prints first element of the list
print (list[1:3])     # Prints elements starting from 2nd till 3rd 
print (list[2:])      # Prints elements starting from 3rd element
print (tinylist * 2)  # Prints list two times
print (list + tinylist) # Prints concatenated lists

这产生以下结果-

['abcd', 786, 2.23, 'john', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']

Python元组


元组是另一个类似于列表的序列数据类型。元组由多个用逗号分隔的值组成。但是,与列表不同,元组被括在括号内。

列表和元组之间的主要区别是-列表放在方括号([])中,并且它们的元素和大小可以更改,而元组放在括号(())中并且不能更新。元组可以视为只读列表。例如-

#!/usr/bin/python3

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print (tuple)           # Prints complete tuple
print (tuple[0])        # Prints first element of the tuple
print (tuple[1:3])      # Prints elements starting from 2nd till 3rd 
print (tuple[2:])       # Prints elements starting from 3rd element
print (tinytuple * 2)   # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple

这产生以下结果-

('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')

以下代码对元组无效,因为我们试图更新一个元组,这是不允许的。列表可能有类似情况-

#!/usr/bin/python3

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
list = [ 'abcd', 786 , 2.23, 'john', 70.2  ]
tuple[2] = 1000    # Invalid syntax with tuple
list[2] = 1000     # Valid syntax with list

Python字典


Python的字典是一种哈希表类型。它们的工作方式类似于Perl中的关联数组或哈希,并且由键值对组成。字典键几乎可以是任何Python类型,但通常是数字或字符串。另一方面,值可以是任意Python对象。

字典用花括号({})括起来,可以使用方括号([])分配和访问值。例如-

#!/usr/bin/python3

dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one'])       # Prints value for 'one' key
print (dict[2])           # Prints value for 2 key
print (tinydict)          # Prints complete dictionary
print (tinydict.keys())   # Prints all the keys
print (tinydict.values()) # Prints all the values

这产生以下结果-

This is one
This is two
{'name': 'john', 'dept': 'sales', 'code': 6734}
dict_keys(['name', 'dept', 'code'])
dict_values(['john', 'sales', 6734])

字典在元素之间没有顺序的概念。说元素“乱序”是不正确的。他们只是无序的。

数据类型转换


有时,您可能需要在内置类型之间执行转换。要在类型之间进行转换,只需将类型名称用作函数即可。

有几种内置函数可以执行从一种数据类型到另一种数据类型的转换。这些函数返回一个表示转换后值的新对象。

序号 功能说明
1 int(x [,base])
将x转换为整数。如果x是字符串,则基数指定基数。
2 float(x))
将x转换为浮点数。
3 complex(real [,imag])
创建一个复数。
4 str(x)
将对象x转换为字符串表示形式。
5 repr(x)
将对象x转换为表达式字符串。
6 eval(str)
计算字符串并返回一个对象。
7 tuple(s)
将s转换为元组。
8 list(s)
将s转换为列表。
9 set(s)
将s转换为集合。
10 dict(d)
创建字典。d必须是(键,值)元组的序列。
11 frozenset(s)
将s转换为冻结集合。
12 chr(x)
将整数转换为字符。
13 unichr(x)
将整数转换为Unicode字符。
14 ord(x)
将单个字符转换为其整数值。
15 hex(x)
将整数转换为十六进制字符串。
16 oct(x)
将整数转换为八进制字符串。

Python 3-基本运算符

运算符是构造,可以操纵操作数的值。考虑表达式4 + 5 =9。这里,4和5称为操作数,而+称为运算符。

运算符类型

Python语言支持以下类型的运算符-

  • 算术运算符
  • 比较(关系)运算符
  • 赋值运算符
  • 逻辑运算符
  • 按位运算符
  • 成员运算符
  • 标识运算符

让我们一一看一下所有的运算符。

Python算术运算符

假设变量a的值为10,变量b的值为21,则-

操作符 描述
+加法 在运算符的任一侧添加值。 a + b = 31
-减法 从左手操作数中减去右手操作数。 a – b = -11
*乘法 将运算符两侧的值相乘 a * b = 210
/除法 将左操作数除以右操作数 b / a = 2.1
%取余 将左操作数除以右操作数并返回余数 b%a = 1
**指数 对运算符执行指数(幂)计算 a ** b =幂20
//整除 底数除法-操作数的除法,其结果是除去小数点后的数字的商。但是,如果其中一个操作数是负数,则结果是下限的,即从零舍入(朝负无穷大): 9 // 2 = 4和9.0 // 2.0 = 4.0,-11 // 3 = -4,-11.0 // 3 = -4.0
#!/usr/bin/python3

a = 21
b = 10
c = 0

c = a + b
print ("Line 1 - Value of c is ", c)

c = a - b
print ("Line 2 - Value of c is ", c )

c = a * b
print ("Line 3 - Value of c is ", c)

c = a / b
print ("Line 4 - Value of c is ", c )

c = a % b
print ("Line 5 - Value of c is ", c)

a = 2
b = 3
c = a**b 
print ("Line 6 - Value of c is ", c)

a = 10
b = 5
c = a//b 
print ("Line 7 - Value of c is ", c)

Python比较运算符

这些运算符比较它们两侧的值并确定它们之间的关系。它们也称为关系运算符。

假设变量a的值为10,变量b的值为20,则-

操作符 描述
== 如果两个操作数的值相等,则条件变为true。 (a == b)不正确。
!= 如果两个操作数的值不相等,则条件为真。 (a!= b)是真的。
> 如果左操作数的值大于右操作数的值,则条件为true。 (a> b)是不正确的。
< 如果左操作数的值小于右操作数的值,则条件为true。 (a <b)是正确的。
>= 如果左操作数的值大于或等于右操作数的值,则条件为true。 (a> = b)不正确。
<= 如果左操作数的值小于或等于右操作数的值,则条件为true。 (a <= b)是正确的。
#!/usr/bin/python3

a = 21
b = 10

if ( a == b ):
   print ("Line 1 - a is equal to b")
else:
   print ("Line 1 - a is not equal to b")

if ( a != b ):
   print ("Line 2 - a is not equal to b")
else:
   print ("Line 2 - a is equal to b")

if ( a < b ):
   print ("Line 3 - a is less than b" )
else:
   print ("Line 3 - a is not less than b")

if ( a > b ):
   print ("Line 4 - a is greater than b")
else:
   print ("Line 4 - a is not greater than b")

a,b = b,a #values of a and b swapped. a becomes 10, b becomes 21

if ( a <= b ):
   print ("Line 5 - a is either less than or equal to  b")
else:
   print ("Line 5 - a is neither less than nor equal to  b")

if ( b >= a ):
   print ("Line 6 - b is either greater than  or equal to b")
else:
   print ("Line 6 - b is neither greater than  nor equal to b")

Python赋值运算符

假设变量a的值为10,变量b的值为20,则-

操作符 描述
= 将值从右侧操作数分配给左侧操作数 c = a + b将a + b的值赋给c
+= 它将右操作数添加到左操作数,并将结果分配给左操作数 c += a等于c = c + a
-= 它从左侧操作数中减去右侧操作数,并将结果分配给左侧操作数 c-= a等效于c = c-a
*= 它将右操作数与左操作数相乘并将结果分配给左操作数 c *= a等效于c = c * a
/= 它将左操作数除以右操作数,并将结果分配给左操作数 c /= a等于c = c / ac / = a等于c = c / a
%= 它使用两个操作数取模并将结果分配给左操作数 c%= a等于c = c%a
**= 对运算符执行指数(幂)计算并将值赋给左操作数 c **= a等效于c = c ** a
//= 它对运算符进行地板除法并将值赋给左操作数 c //= a等效于c = c // a
#!/usr/bin/python3

a = 21
b = 10
c = 0

c = a + b
print ("Line 1 - Value of c is ", c)

c += a
print ("Line 2 - Value of c is ", c )

c *= a
print ("Line 3 - Value of c is ", c )

c /= a 
print ("Line 4 - Value of c is ", c )

c  = 2
c %= a
print ("Line 5 - Value of c is ", c)

c **= a
print ("Line 6 - Value of c is ", c)

c //= a
print ("Line 7 - Value of c is ", c)

Python按位运算符

按位运算符对位进行运算并执行逐位操作。假设a = 60; 和b = 13; 现在以二进制格式,它们将如下所示-

a = 0011 1100
b = 0000 1101


a&b = 0000 1100
a | b = 0011 1101
a ^ b = 0011 0001
〜a = 1100 0011
Python的内置函数bin()可用于获取整数的二进制表示形式。
Python语言支持以下按位运算符-

操作符 描述

二进制与
如果两个操作数中都存在运算符,则将其复制到结果中 (a & b)(表示0000 1100)
|
二进制或
如果在任何一个操作数中都存在,它将复制一点。 (a | b)= 61(意味着0011 1101)
^
二进制异或
如果在一个操作数中而不是在两个操作数中都将其置位,它将复制该位。 (a ^ b)= 49(意味着0011 0001)

二进制补码
它是一元的,具有“翻转”位的作用。 (〜a)= -61(由于带符号的二进制数,表示2的补码形式的1100 0011。
<<
二进制左移
左操作数的值向左移动右操作数指定的位数。 a << 2 = 240(意味着1111 0000)
>>
二进制右移
左操作数的值向右移动右操作数指定的位数。 a >> 2 = 15(意味着0000 1111)
#!/usr/bin/python3

a = 60            # 60 = 0011 1100
b = 13            # 13 = 0000 1101
print ('a=',a,':',bin(a),'b=',b,':',bin(b))
c = 0

c = a & b;        # 12 = 0000 1100
print ("result of AND is ", c,':',bin(c))

c = a | b;        # 61 = 0011 1101 
print ("result of OR is ", c,':',bin(c))

c = a ^ b;        # 49 = 0011 0001
print ("result of EXOR is ", c,':',bin(c))

c = ~a;           # -61 = 1100 0011
print ("result of COMPLEMENT is ", c,':',bin(c))

c = a << 2;       # 240 = 1111 0000
print ("result of LEFT SHIFT is ", c,':',bin(c))

c = a >> 2;       # 15 = 0000 1111
print ("result of RIGHT SHIFT is ", c,':',bin(c))

Python逻辑运算符

Python语言支持以下逻辑运算符。假设变量a保持True,变量b保持False,则-

操作符 描述
and逻辑与 如果两个操作数都为真,则条件为真。 (a and b)为False。
or逻辑或 如果两个操作数中的任何一个都不为零,则条件为真。 (a or b)为True。
not逻辑非 用于反转其操作数的逻辑状态。 not(a and b)为True。

Python成员运算符

Python的成员运算符测试序列中的成员资格,例如字符串,列表或元组。有两个成员运算符,如下所述-

操作符 描述
in 如果找到指定序列中的变量,则评估为true,否则为false。 x in y,如果x是序列y的成员,则结果为1。
not in 如果找不到指定序列中的变量,则计算为true,否则为false。 x不在y中,如果x不是序列y的成员,则此处的结果不为1。
#!/usr/bin/python3

a = 10
b = 20
list = [1, 2, 3, 4, 5 ]

if ( a in list ):
   print ("Line 1 - a is available in the given list")
else:
   print ("Line 1 - a is not available in the given list")

if ( b not in list ):
   print ("Line 2 - b is not available in the given list")
else:
   print ("Line 2 - b is available in the given list")

c = b/a
if ( c in list ):
   print ("Line 3 - a is available in the given list")
else:
   print ("Line 3 - a is not available in the given list")

Python标识运算符

身份运算符比较两个对象的内存位置。有两个身份运算符,如下所述-

操作符 描述
is 如果运算符两侧的变量指向同一个对象,则返回true;否则返回false。 x is y,如果id(x)等于id(y),结果为1。
is not 如果运算符两侧的变量指向同一个对象,则结果为false,否则为true。 x is not y,如果id(x)不等于id(y),则这里不是 1。
#!/usr/bin/python3

a = 20
b = 20
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))

if ( a is b ):
   print ("Line 2 - a and b have same identity")
else:
   print ("Line 2 - a and b do not have same identity")

if ( id(a) == id(b) ):
   print ("Line 3 - a and b have same identity")
else:
   print ("Line 3 - a and b do not have same identity")

b = 30
print ('Line 4','a=',a,':',id(a), 'b=',b,':',id(b))

if ( a is not b ):
   print ("Line 5 - a and b do not have same identity")
else:
   print ("Line 5 - a and b have same identity")

Python运算符优先级

下表列出了从最高优先级到最低优先级的所有运算符。

序号 运算符和说明
1 **
求幂(提高幂)
2 〜+-
补码,一元加号和减号(最后两个的方法名称为+ @和-@)
3 * /%//
乘,除,模和底除
4 +-
加减
5 >> <<
左右位移
6 &
按位“与”
7 ^ |
按位异或或常规OR
8 <= <>> =
比较运算符
9 <> ==!=
平等经营者
10 =%= / = // =-= + =\ * = * =*
赋值运算符
11 is is not
标识运算符
12 in not in
会员经营者
13 not or and
逻辑运算符
#!/usr/bin/python3

a = 20
b = 10
c = 15
d = 5

print ("a:%d b:%d c:%d d:%d" % (a,b,c,d ))
e = (a + b) * c / d       #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ",  e)

e = ((a + b) * c) / d     # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ",  e)

e = (a + b) * (c / d)    # (30) * (15/5)
print ("Value of (a + b) * (c / d) is ",  e)

e = a + (b * c) / d      #  20 + (150/5)
print ("Value of a + (b * c) / d is ",  e)

Python 3-条件判断

条件判断是对程序执行期间发生的条件以及根据条件采取的指定操作的预期。

条件判断多个表达式,这些表达式产生TRUE或FALSE作为结果。如果结果为TRUE或FALSE,则需要确定要执行的操作以及要执行的语句。

以下是大多数编程语言中常见的典型条件判断的一般形式-

做决定

Python编程语言将任何非零非空值假定为TRUE,并将任何空值假定为FALSE值。

Python编程语言提供以下类型的条件判断语句。

序号 声明与说明
1 if语句
一个if语句包含一个布尔表达式后跟一个或多个语句。
2 if...else语句
一个if语句可以跟着一个可选的else语句,当布尔表达式为FALSE,其执行。
3 嵌套if语句
可以在另一个if or else if语句中使用一个if or else if语句。

if语句

#!/usr/bin/python3

var1 = 100
if var1:
   print ("1 - Got a true expression value")
   print (var1)

var2 = 0
if var2:
   print ("2 - Got a true expression value")
   print (var2)
print ("Good bye!")

if...else语句

#!/usr/bin/python3

amount = int(input("Enter amount: "))

if amount<1000:
   discount = amount*0.05
   print ("Discount",discount)
else:
   discount = amount*0.10
   print ("Discount",discount)
    
print ("Net payable:",amount-discount)

嵌套if语句

# !/usr/bin/python3

num = int(input("enter number"))
if num%2 == 0:
   if num%3 == 0:
      print ("Divisible by 3 and 2")
   else:
      print ("divisible by 2 not divisible by 3")
else:
   if num%3 == 0:
      print ("divisible by 3 not divisible by 2")
   else:
      print  ("not Divisible by 2 not divisible by 3")

注意:如果if子句仅包含一行,则它可能与header语句位于同一行。

#!/usr/bin/python3
var = 100
if ( var  == 100 ) : print ("Value of expression is 100")
print ("Good bye!")

Python 3-循环

通常,语句按顺序执行-函数中的第一个语句首先执行,然后执行第二个,依此类推。在某些情况下,您需要多次执行一个代码块。

编程语言提供了各种控制结构,允许更复杂的执行路径。

循环语句使我们可以多次执行一个语句或一组语句。下图说明了循环语句-

循环架构

Python编程语言提供了以下类型的循环来处理循环需求。

序号 循环类型和说明
1 while循环
在给定条件为TRUE时重复一个语句或一组语句。它在执行循环体之前测试条件。
2 for循环
多次执行一个语句序列,并简化管理循环变量的代码。
3 嵌套循环
您可以同时使用一个或多个循环,也可以使用for循环。

循环样例1

#!/usr/bin/python3

count = 0
while (count < 9):
   print ('The count is:', count)
   count = count + 1

print ("Good bye!")

循环样例2

#!/usr/bin/python3

var = 1
while var == 1 :  # This constructs an infinite loop
   num = int(input("Enter a number  :"))
   print ("You entered: ", num)

print ("Good bye!")

循环样例3

#!/usr/bin/python3

count = 0
while count < 5:
   print (count, " is  less than 5")
   count = count + 1
else:
   print (count, " is not less than 5")

循环样例4

#!/usr/bin/python3

flag = 1
while (flag): print ('Given flag is really true!')
print ("Good bye!")

循环控制语句

循环控制语句从其正常顺序更改执行。当执行离开作用域时,在该作用域中创建的所有自动对象都将被破坏。

Python支持以下控制语句。

序号 控制声明和说明
1 中断声明
终止循环语句,并在循环之后立即将执行转移到该语句。
2 继续声明
使循环跳过其其余部分,并在重新进行迭代之前立即重新测试其状况。
3 通过声明
在语法上需要语句但您不希望执行任何命令或代码时,使用Python中的pass语句。

中断声明样例1

#!/usr/bin/python3

for letter in 'Python':     # First Example
   if letter == 'h':
      break
   print ('Current Letter :', letter)
  
var = 10                    # Second Example
while var > 0:              
   print ('Current variable value :', var)
   var = var -1
   if var == 5:
      break

print ("Good bye!")

中断声明样例2

#!/usr/bin/python3

no = int(input('any number: '))
numbers = [11,33,55,39,55,75,37,21,23,41,13]

for num in numbers:
   if num == no:
      print ('number found in list')
      break
else:
   print ('number not found in list')

继续声明样例1

#!/usr/bin/python3

for letter in 'Python':     # First Example
   if letter == 'h':
      continue
   print ('Current Letter :', letter)

var = 10                    # Second Example
while var > 0:              
   var = var -1
   if var == 5:
      continue
   print ('Current variable value :', var)
print ("Good bye!")

通过声明样例1

#!/usr/bin/python3

for letter in 'Python': 
   if letter == 'h':
      pass
      print ('This is pass block')
   print ('Current Letter :', letter)

print ("Good bye!")

让我们简要介绍一下循环控制语句。

迭代器和生成器

迭代器是一个对象,它使程序员可以遍历集合的所有元素,而无论其具体实现如何。在Python中,迭代器对象实现两个方法,iter()next()

字符串,列表或元组对象可用于创建迭代器。

list = [1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
Iterator object can be traversed using regular for statement
!usr/bin/python3
for x in it:
   print (x, end=" ")
or using next() function
while True:
   try:
      print (next(it))
   except StopIteration:
      sys.exit() #you have to import sys module for this

发生器是产生或产生使用产量的方法值的序列的功能。

调用生成器函数时,它甚至不开始执行该函数就返回生成器对象。首次调用next()方法时,该函数开始执行直到到达yield语句,该语句返回yield值。收益保持跟踪,即记住上一次执行,第二个next()调用从上一个值继续。

以下示例定义了一个生成器,该生成器为所有斐波那契数生成一个迭代器。

#!usr/bin/python3

import sys
def fibonacci(n): #generator function
   a, b, counter = 0, 1, 0
   while True:
      if (counter > n): 
         return
      yield a
      a, b = b, a + b
      counter += 1
f = fibonacci(5) #f is iterator object

while True:
   try:
      print (next(f), end=" ")
   except StopIteration:
      sys.exit()

Python 3-数字

数字数据类型存储数值。它们是不可变的数据类型。这意味着,更改数字数据类型的值将导致新分配的对象。

数字对象是在您为其分配值时创建的。例如-

var1 =  1 
var2 =  10

您也可以使用del语句删除对数字对象的引用。del语句的语法是-

del var1[,var2[,var3[....,varN]]]]

您可以使用del语句删除单个对象或多个对象。例如-

del  var  
del var_a, var_b

Python支持不同的数值类型-

  • int(有符号整数) -它们通常仅称为整数或ints。它们是没有小数点的正或负整数。Python 3中的整数没有大小限制。Python 2有两种整数类型-int和long。Python 3中不再有“ 长整数 ”了。

  • float(浮点实数值) -也称为浮点数,它们表示实数,并用小数点表示,该整数除以整数和小数部分。浮点数也可以用科学计数法表示,E或e表示10的幂(2.5e2 = 2.5 x 10 2 = 250)。

  • 复数(复数) -形式为a + bJ,其中a和b为浮点数,J(或j)表示-1的平方根(这是一个虚数)。该数字的实部是a,虚部是b。复数在Python编程中使用不多。

可以以十六进制或八进制形式表示整数

>>> number =  0xA0F  #Hexa-decimal  
>>> number 
2575  
>>> number =  0o37  #Octal  
>>> number 
31

例子

以下是一些数字示例。

整型 浮点 复数
10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3 + e18 .876j
-0490 -90。 -.6545 + 0J
-0×260 -32.54e100 3e + 26J
0×69 70.2-E12 4.53e-7j

复数由a + bj表示的有序对实数浮点数组成,其中a是复数的实部,b是虚数的虚部。

数字类型转换

Python在内部将包含混合类型的表达式中的数字转换为用于评估的通用类型。有时,您需要将数字从一种类型显式强制转换为另一种类型,以满足运算符或函数参数的要求。

  • int(x)将x转换为纯整数。

  • long(x)将x转换为长整数。

  • float(x)将x转换为浮点数。

  • complex(x)将x转换为具有实部x和虚部为零的复数。

  • complex(x,y)将x和y转换为具有实部x和虚部y的复数。x和y是数字表达式

数学函数

Python包含以下用于执行数学计算的函数。

序号 功能与返回(说明)
1 abs(x)
x的绝对值:x与零之间的(正)距离。
2 ceil(x)
x的上限:不小于x的最小整数。
3 cmp(x, y)
如果x <y则为-1,如果x == y则为0,如果x> y则为1。在Python 3中已弃用。请使用return(x> y)-(x <y)
4 exp(x)
x的指数:e x
5 fabs(x)
x的绝对值。
6 floor(x)
x的下限:不大于x的最大整数。
7 log(x)
x的自然对数,其中x> 0。
8 ** log10(x)**
x> 0时x的以10为底的对数。
9 max(x1, x2,...)
最大的参数:最接近正无穷大的值
10 min(x1, x2,...)
它的最小参数:最接近负无穷大的值。
11 modf(x)
x在两个项目元组中的小数和整数部分。这两部分的符号与x相同。整数部分以浮点数形式返回。
12 pow(x, y)
x ** y的值。
13 round(x [,n])
x从小数点舍入到n位数字。Python会以平局方式从零舍入:round(0.5)为1.0,round(-0.5)为-1.0。
14 sqrt(x)
x> 0时x的平方根。
#!/usr/bin/python3
import math   # This will import math module

print ("abs(-45) : ", abs(-45))
print ("abs(100.12) : ", abs(100.12))

print ("math.ceil(-45.17) : ", math.ceil(-45.17))
print ("math.ceil(100.12) : ", math.ceil(100.12))
print ("math.ceil(100.72) : ", math.ceil(100.72))
print ("math.ceil(math.pi) : ", math.ceil(math.pi))

print ("math.cmp(1,2) : ", math.cmp(1,2) )
print ("math.cmp(2,1) : ", math.cmp(2,1) )
print ("math.cmp(2,2) : ", math.cmp(2,2) )

print ("math.exp(-45.17) : ", math.exp(-45.17))
print ("math.exp(100.12) : ", math.exp(100.12))
print ("math.exp(100.72) : ", math.exp(100.72))
print ("math.exp(math.pi) : ", math.exp(math.pi))

print ("math.fabs(-45.17) : ", math.fabs(-45.17))
print ("math.fabs(100.12) : ", math.fabs(100.12))
print ("math.fabs(100.72) : ", math.fabs(100.72))
print ("math.fabs(math.pi) : ", math.fabs(math.pi))

print ("math.floor(-45.17) : ", math.floor(-45.17))
print ("math.floor(100.12) : ", math.floor(100.12))
print ("math.floor(100.72) : ", math.floor(100.72))
print ("math.floor(math.pi) : ", math.floor(math.pi))

print ("math.log(100.12) : ", math.log(100.12))
print ("math.log(100.72) : ", math.log(100.72))
print ("math.log(math.pi) : ", math.log(math.pi))

print ("math.log10(100.12) : ", math.log10(100.12))
print ("math.log10(100.72) : ", math.log10(100.72))
print ("math.log10(119) : ", math.log10(119))
print ("math.log10(math.pi) : ", math.log10(math.pi))

print ("max(80, 100, 1000) : ", max(80, 100, 1000))
print ("max(-20, 100, 400) : ", max(-20, 100, 400))
print ("max(-80, -20, -10) : ", max(-80, -20, -10))
print ("max(0, 100, -400) : ", max(0, 100, -400))

print ("min(80, 100, 1000) : ", min(80, 100, 1000))
print ("min(-20, 100, 400) : ", min(-20, 100, 400))
print ("min(-80, -20, -10) : ", min(-80, -20, -10))
print ("min(0, 100, -400) : ", min(0, 100, -400))

print ("math.modf(100.12) : ", math.modf(100.12))
print ("math.modf(100.72) : ", math.modf(100.72))
print ("math.modf(119) : ", math.modf(119))
print ("math.modf(math.pi) : ", math.modf(math.pi))

print ("math.pow(100, 2) : ", math.pow(100, 2))
print ("math.pow(100, -2) : ", math.pow(100, -2))
print ("math.pow(2, 4) : ", math.pow(2, 4))
print ("math.pow(3, 0) : ", math.pow(3, 0))

print ("round(70.23456) : ", round(70.23456))
print ("round(56.659,1) : ", round(56.659,1))
print ("round(80.264, 2) : ", round(80.264, 2))
print ("round(100.000056, 3) : ", round(100.000056, 3))
print ("round(-100.000056, 3) : ", round(-100.000056, 3))

print ("math.sqrt(100) : ", math.sqrt(100))
print ("math.sqrt(7) : ", math.sqrt(7))
print ("math.sqrt(math.pi) : ", math.sqrt(math.pi))

随机数函数

随机数用于游戏,模拟,测试,安全性和隐私应用程序。Python包含以下常用功能。

序号 功能说明
1 choice(seq)
列表,元组或字符串中的随机项。
2 randrange ([start,] stop [,step])
从范围(开始,停止,步进)中随机选择的元素。
3 random()
随机浮点数r,使得0小于或等于r且r小于1
4 seed([x])
设置用于生成随机数的整数起始值。在调用任何其他随机模块函数之前,请先调用此函数。返回无。
5 shuffle(lst)
将列表中的项目随机化。返回无。
6 uniform(x, y)
随机浮点数r,使得x小于或等于r且r小于y。
#!/usr/bin/python3
import random

print ("returns a random number from range(100) : ",random.choice(range(100)))
print ("returns random element from list [1, 2, 3, 5, 9]) : ", random.choice([1, 2, 3, 5, 9]))
print ("returns random character from string 'Hello World' : ", random.choice('Hello World'))

# randomly select an odd number between 1-100 
print ("randrange(1,100, 2) : ", random.randrange(1, 100, 2))
# randomly select a number between 0-99 
print ("randrange(100) : ", random.randrange(100))

# First random number
print ("random() : ", random.random())
# Second random number
print ("random() : ", random.random())

random.seed()
print ("random number with default seed", random.random())
random.seed(10)
print ("random number with int seed", random.random())
random.seed("hello",2)
print ("random number with string seed", random.random())

list = [20, 16, 10, 5];
random.shuffle(list)
print ("Reshuffled list : ",  list)

random.shuffle(list)
print ("Reshuffled list : ",  list)

print ("Random Float uniform(5, 10) : ",  random.uniform(5, 10))
print ("Random Float uniform(7, 14) : ",  random.uniform(7, 14))

三角函数

Python包含以下用于执行三角计算的函数。

序号 功能说明
1 acos(x)
返回弧度的x的反余弦值。
2 asin(x)
返回弧度的x的反正弦值。
3 atan(x)
返回弧度的x的反正切值。
4 atan2(y,x)
返回弧度的atan(y / x)。
5 cos(x)
返回x弧度的余弦值。
6 hypot(x, y)
返回欧几里得范数sqrt(x * x + y * y)。
7 sin(x)
返回x弧度的正弦值。
8 tan(x)
返回x弧度的切线。
9 degrees(x)
将角度x从弧度转换为度。
10 radians(x)
将角度x从度转换为弧度。
#!/usr/bin/python3
import math

print ("acos(0.64) : ",  math.acos(0.64))
print ("acos(0) : ",  math.acos(0))
print ("acos(-1) : ",  math.acos(-1))
print ("acos(1) : ",  math.acos(1))

print ("asin(0.64) : ",  math.asin(0.64))
print ("asin(0) : ",  math.asin(0))
print ("asin(-1) : ",  math.asin(-1))
print ("asin(1) : ",  math.asin(1))

print ("atan(0.64) : ",  math.atan(0.64))
print ("atan(0) : ",  math.atan(0))
print ("atan(10) : ",  math.atan(10))
print ("atan(-1) : ",  math.atan(-1))
print ("atan(1) : ",  math.atan(1))

print ("atan2(-0.50,-0.50) : ",  math.atan2(-0.50,-0.50))
print ("atan2(0.50,0.50) : ",  math.atan2(0.50,0.50))
print ("atan2(5,5) : ",  math.atan2(5,5))
print ("atan2(-10,10) : ",  math.atan2(-10,10))
print ("atan2(10,20) : ",  math.atan2(10,20))

print ("cos(3) : ",  math.cos(3))
print ("cos(-3) : ",  math.cos(-3))
print ("cos(0) : ",  math.cos(0))
print ("cos(math.pi) : ",  math.cos(math.pi))
print ("cos(2*math.pi) : ",  math.cos(2*math.pi))

print ("hypot(3, 2) : ",  math.hypot(3, 2))
print ("hypot(-3, 3) : ",  math.hypot(-3, 3))
print ("hypot(0, 2) : ",  math.hypot(0, 2))

print ("sin(3) : ",  math.sin(3))
print ("sin(-3) : ",  math.sin(-3))
print ("sin(0) : ",  math.sin(0))
print ("sin(math.pi) : ",  math.sin(math.pi))
print ("sin(math.pi/2) : ",  math.sin(math.pi/2))

print ("(tan(3) : ",  math.tan(3))
print ("tan(-3) : ",  math.tan(-3))
print ("tan(0) : ",  math.tan(0))
print ("tan(math.pi) : ",  math.tan(math.pi))
print ("tan(math.pi/2) : ",  math.tan(math.pi/2))
print ("tan(math.pi/4) : ",  math.tan(math.pi/4))

print ("degrees(3) : ",  math.degrees(3))
print ("degrees(-3) : ",  math.degrees(-3))
print ("degrees(0) : ",  math.degrees(0))
print ("degrees(math.pi) : ",  math.degrees(math.pi))
print ("degrees(math.pi/2) : ",  math.degrees(math.pi/2))
print ("degrees(math.pi/4) : ",  math.degrees(math.pi/4))

print ("radians(3) : ",  math.radians(3))
print ("radians(-3) : ",  math.radians(-3))
print ("radians(0) : ",  math.radians(0))
print ("radians(math.pi) : ",  math.radians(math.pi))
print ("radians(math.pi/2) : ",  math.radians(math.pi/2))
print ("radians(math.pi/4) : ",  math.radians(math.pi/4))

数学常数

该模块还定义了两个数学常数-

序号 常数与说明
1 pi
数学常数pi。
2 e
数学常数e。

Python 3-字符串

字符串是Python中最流行的类型之一。我们只需将字符括在引号中即可创建它们。Python将单引号与双引号相同。创建字符串就像将值分配给变量一样简单。例如-

var1 = 'Hello World!'
var2 = "Python Programming"

访问字符串中的值

Python不支持字符类型。这些被视为长度为一的字符串,因此也被视为子字符串。

要访问子字符串,请使用方括号和一个或多个索引进行切片以获得您的子字符串。例如-

#!/usr/bin/python3

var1 = 'Hello World!'
var2 = "Python Programming"

print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])

更新字符串

您可以通过(重新)将变量分配给另一个字符串来“更新”现有字符串。新值可以与其先前值相关,也可以与完全不同的字符串相关。例如-

#!/usr/bin/python3

var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python')

转义字符

下表是可以用反斜杠表示的转义字符或不可打印字符的列表。

转义字符被解释;用单引号和双引号引起来。

反斜杠符号 十六进制字符 描述
\a 0x07 铃声或警报
\b 0x08 退格键
\cx Control-x
\Cx Control-x
\e 0x1b 逃逸
\F 0x0c 换页
\M-\Cx 元控制x
\n 0x0a 新行
\nnn 八进制表示法,其中n在0.7范围内
\r 0x0d 回车
\s 0x20 空间
\t 0x09 标签
\v 0x0b 垂直标签
\X 字符x
\xnn 十六进制表示法,其中n在0.9,af或AF范围内

字符串特殊运算符

假设字符串变量a持有“ Hello”,变量b持有“ Python”,则-
参考列表:

操作符 描述
+ 串联-在运算符的任一侧添加值 a + b将给HelloPython
* 重复-创建新字符串,将同一字符串的多个副本连接在一起 a * 2将给出-HelloHello
[] 切片-根据给定的索引给出字符 a [1]将给e
[ : ] 范围切片-提供给定范围内的字符 a [1:4]会给ell
in 成员资格-如果给定字符串中存在字符,则返回true H会给1
not in 成员资格-如果给定字符串中不存在字符,则返回true M不在会给1
r/R 原始字符串-禁止转义字符的实际含义。原始字符串的语法与普通字符串的语法完全相同,不同之处在于原始字符串运算符,在引号之前的字母“ r”。“ r”可以是小写(r)或大写(R),并且必须放在第一个引号之前。 打印r'\ n'打印\ n和打印R'\ n'打印\ n
格式-执行字符串格式化 见下一节

字符串格式化运算符

Python最酷的功能之一是字符串格式运算符%。该运算符是字符串所独有的,并弥补了C的printf()系列具有的功能。以下是一个简单的例子-

#!/usr/bin/python3

print ("My name is %s and weight is %d kg!" % ('Zara', 21)) 

这是可以与%一起使用的完整符号集的列表-

序号 格式符号和转换
1 %C**
字符
2 %s
在格式化之前通过str()进行字符串转换
3 %i
有符号十进制整数
4 %d
有符号十进制整数
5 %u
无符号十进制整数
6 %o
八进制整数
7 %x
十六进制整数(小写字母)
8 %X
十六进制整数(大写字母)
9 %e
指数符号(小写的“ e”)
10 %E
指数表示法(使用大写字母“ E”)
11 %f
浮点实数
12 %g
%f和%e中的较短者
13 %G
%f和%E中的较短者

下表列出了其他受支持的符号和功能-

序号 符号与功能
1 *
参数指定宽度或精度
2 -
左对齐
3 +
显示标志
4 <sp>
在正数之前保留空格
5 #
根据使用的是x还是X,添加八进制前导零('0')或十六进制前导'0x'或'0X'。
6 0
从左到左填充零(而不是空格)
7
'%%'只剩下一个文字'%'
8 (var)
映射变量(字典参数)
9 m.n.
m是最小总宽度,n是小数点后要显示的位数(如果有)。

三引号

通过允许字符串跨越多行,包括逐字换行符,TAB和任何其他特殊字符,Python的三重引号得以解决。

三重引号的语法包含三个连续的单引号双引号

#!/usr/bin/python3

para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print (para_str)

原始字符串根本不会将反斜杠视为特殊字符。您输入到原始字符串中的每个字符都保持您编写它的方式-

#!/usr/bin/python3

print ('C:\\nowhere')

现在,让我们使用原始字符串。我们将表达式放在r'expression'中,如下所示:

#!/usr/bin/python3  
print  (r'C:\\nowhere')

Unicode字串

在Python 3中,所有字符串均以Unicode表示。在Python 2中,内部存储为8位ASCII,因此需要附加'u'使其成为Unicode。现在不再需要。

内置字符串方法
Python包含以下内置方法来处理字符串-

序号 方法与说明
1 capitalize()
首字母大写
2 center(width, fillchar)
返回以fillchar填充的字符串,原始字符串的中心为width列的总和。
3 count(str, beg = 0,end = len(string))
计算给定起始索引beg和终止索引end时,str在字符串或字符串子字符串中出现的次数。
4 decode(encoding = 'UTF-8',errors = 'strict')
使用注册用于编码的编解码器解码字符串。编码默认为默认字符串编码。
5 encode(encoding = 'UTF-8',errors = 'strict')
返回字符串的编码字符串版本;如果发生错误,默认情况下会引发ValueError,除非使用'ignore'或'replace'给出错误。
6 endswith(suffix, beg = 0, end = len(string))
确定字符串或字符串的子字符串(如果给出了开始索引beg和结束索引end)是否以后缀结尾;如果是,则返回true,否则返回false。
7 expandtabs(tabsize = 8)
将字符串中的制表符扩展到多个空格;如果未提供tabsize,则默认为每个标签8个空格。
8 find(str, beg = 0 end = len(string))
如果给定了开始索引beg和结束索引end,则确定str是在字符串中还是在字符串的子字符串中出现,如果找到则返回索引,否则返回-1。
9 index(str, beg = 0, end = len(string))
与find()相同,但是如果未找到str则引发异常。
10 isalnum()
如果string至少包含1个字符,并且所有字符均为字母数字,则返回true;否则返回false。
11 isalpha()
如果string至少包含1个字符,并且所有字符均为字母,则返回true;否则返回false。
12 isdigit()
如果字符串仅包含数字,则返回true,否则返回false。
13 islower()
如果string至少包含1个大小写字符,并且所有大小写字符均为小写,则返回true;否则返回false。
14 isnumeric()
如果Unicode字符串仅包含数字字符,则返回true,否则返回false。
15 isspace()
如果字符串仅包含空格字符,则返回true,否则返回false。
16 istitle()
如果将字符串正确地“加标题”,则返回true,否则返回false。
17 isupper()
如果string至少包含一个大小写字符,并且所有大小写字符均为大写,则返回true;否则返回false。
18 join(seq)
使用分隔符字符串将序列seq中元素的字符串表示形式合并(连接)为字符串。
19 len(string)
返回字符串的长度
20 ljust(width[, fillchar])
返回一个带空格的字符串,原始字符串左对齐到宽度列的总数。
21 lower()
将字符串中的所有大写字母转换为小写。
22 lstrip()
删除字符串中所有前导空格。
23 maketrans()
返回要在翻译功能中使用的翻译表。
24 max(str)
返回字符串str中的最大字母字符。
25 min(str)
返回字符串str中的最小字母字符。
26 replace(old, new [, max])
如果给定了最大值,则用新的或最多最大的次数替换字符串中所有旧的事件。
27 rfind(str, beg = 0,end = len(string))
与find()相同,但向后搜索字符串。
28 rindex( str, beg = 0, end = len(string))
与index()相同,但向后搜索字符串。
29 rjust(width,[, fillchar])
返回一个带空格的字符串,原始字符串右对齐为width列的总和。
30 rstrip()
删除字符串的所有结尾空格。
31 split(str="", num=string.count(str))
根据定界符str分割字符串(如果未提供,则空格)并返回子字符串列表;如果给定,最多可拆分为num个子字符串。
32 splitlines( num=string.count('\n'))
分割所有(或num个)NEWLINE字符串,并返回删除了NEWLINE的每一行的列表。
33 startswith(str, beg=0,end=len(string))
确定字符串或字符串的子字符串(如果已给出起始索引beg和结束索引end)以子字符串str开头;如果是,则返回true,否则返回false。
34 strip([chars])
对字符串执行lstrip()和rstrip()
35 swapcase()
转换字符串中所有字母的大小写。
36 title()
返回字符串的“ titlecased”版本,即所有单词均以大写字母开头,其余均为小写字母。
37 translate(table, deletechars="")
根据转换表str(256个字符)翻译字符串,删除del字符串中的字符串。
38 upper()
将字符串中的小写字母转换为大写。
39 zfill (width)
返回原始字符串,将其用零填充到总的宽度字符;用于数字,zfill()保留给定的任何符号(小于1的零)。
40 isdecimal()
如果Unicode字符串仅包含十进制字符,则返回true,否则返回false。
#!/usr/bin/python3

str = "this is string example....wow!!!"
print ("str.capitalize() : ", str.capitalize())

str = "this is string example....wow!!!"
print ("str.center(40, 'a') : ", str.center(40, 'a'))

str = "this is string example....wow!!!"
sub = 'i'
print ("str.count('i') : ", str.count(sub))
sub = 'exam'
print ("str.count('exam', 10, 40) : ", str.count(sub,10,40))

Str = "this is string example....wow!!!";
Str = Str.encode('base64','strict');

print "Encoded String: " + Str
print "Decoded String: " + Str.decode('base64','strict')

import base64

Str = "this is string example....wow!!!"
Str = base64.b64encode(Str.encode('utf-8',errors = 'strict'))

print ("Encoded String: " , Str)

Str = 'this is string example....wow!!!'
suffix = '!!'
print (Str.endswith(suffix))
print (Str.endswith(suffix,20))

suffix = 'exam'
print (Str.endswith(suffix))
print (Str.endswith(suffix, 0, 19))

str = "this is\tstring example....wow!!!"
print ("Original string: " + str)
print ("Defualt exapanded tab: " +  str.expandtabs())
print ("Double exapanded tab: " +  str.expandtabs(16))

str1 = "this is string example....wow!!!"
str2 = "exam";

print (str1.find(str2))
print (str1.find(str2, 10))
print (str1.find(str2, 40))

str1 = "this is string example....wow!!!"
str2 = "exam";

print (str1.index(str2))
print (str1.index(str2, 10))
print (str1.index(str2, 40))

str = "this2016"  # No space in this string
print (str.isalnum())

str = "this is string example....wow!!!"
print (str.isalnum())

str = "this";  # No space & digit in this string
print (str.isalpha())

str = "this is string example....wow!!!"
print (str.isalpha())

str = "123456";  # Only digit in this string
print (str.isdigit())

str = "this is string example....wow!!!"
print (str.isdigit())

str = "THIS is string example....wow!!!"
print (str.islower())

str = "this is string example....wow!!!"
print (str.islower())

str = "this2016"  
print (str.isnumeric())

str = "23443434"
print (str.isnumeric())

str = "       " 
print (str.isspace())

str = "This is string example....wow!!!"
print (str.isspace())

str = "This Is String Example...Wow!!!"
print (str.istitle())

str = "This is string example....wow!!!"
print (str.istitle())

str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.isupper())

str = "THIS is string example....wow!!!"
print (str.isupper())

s = "-"
seq = ("a", "b", "c") # This is sequence of strings.
print (s.join( seq ))

str = "this is string example....wow!!!"
print ("Length of the string: ", len(str))

str = "this is string example....wow!!!"
print str.ljust(50, '*')

str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.lower())

str = "     this is string example....wow!!!"
print (str.lstrip())

str = "*****this is string example....wow!!!*****"
print (str.lstrip('*'))

intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)

str = "this is string example....wow!!!"
print (str.translate(trantab))

str = "this is a string example....really!!!"
print ("Max character: " + max(str))

str = "this is a string example....wow!!!"
print ("Max character: " + max(str))

str = "www.tutorialspoint.com"
print ("Min character: " + min(str))

str = "TUTORIALSPOINT"
print ("Min character: " + min(str))

str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))

str1 = "this is really a string example....wow!!!"
str2 = "is"

print (str1.rfind(str2))
print (str1.rfind(str2, 0, 10))
print (str1.rfind(str2, 10, 0))

print (str1.find(str2))
print (str1.find(str2, 0, 10))
print (str1.find(str2, 10, 0))

str1 = "this is really a string example....wow!!!"
str2 = "is"

print (str1.rindex(str2))
print (str1.rindex(str2,10))

str = "this is string example....wow!!!"
print (str.rjust(50, '*'))

str = "     this is string example....wow!!!     "
print (str.rstrip())

str = "*****this is string example....wow!!!*****"
print (str.rstrip('*'))

str = "this is string example....wow!!!"
print (str.split( ))
print (str.split('i',1))
print (str.split('w'))

str = "this is \nstring example....\nwow!!!"
print (str.splitlines( ))

str = "this is string example....wow!!!"
print (str.startswith( 'this' ))
print (str.startswith( 'string', 8 ))
print (str.startswith( 'this', 2, 4 ))

str = "*****this is string example....wow!!!*****"
print (str.strip( '*' ))

str = "this is string example....wow!!!"
print (str.swapcase())

str = "This Is String Example....WOW!!!"
print (str.swapcase())

str = "this is string example....wow!!!"
print (str.title())

from string import maketrans # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";
print (str.translate(trantab))

str = "this is string example....wow!!!"
print ("str.upper : ",str.upper())

str = "this is string example....wow!!!"
print ("str.zfill : ",str.zfill(40))
print ("str.zfill : ",str.zfill(50))

str = "this2016"
print (str.isdecimal())

str = "23443434"
print (str.isdecimal())

Python 3-列表

Python中最基本的数据结构是序列。序列的每个元素都分配有一个数字-其位置或索引。第一个索引为零,第二个索引为1,依此类推。

Python有六种内置的序列类型,但是最常见的是列表和元组,我们将在本教程中看到它们。

您可以对所有序列类型执行某些操作。这些操作包括索引,切片,加,乘和检查成员资格。此外,Python具有内置函数,用于查找序列的长度以及查找其最大和最小元素。

Python列表

该列表是Python中最通用的数据类型,可以将其写成方括号之间的逗号分隔值(项目)列表。关于列表的重要事项是列表中的项目不必是同一类型。

创建列表就像在方括号之间放置不同的逗号分隔值一样简单。例如-

list1 =  ['physics',  'chemistry',  1997,  2000]; 
list2 =  [1,  2,  3,  4,  5  ]; 
list3 =  ["a",  "b",  "c",  "d"];

与字符串索引相似,列表索引从0开始,并且列表可以被切片,连接等。

访问列表中的值

要访问列表中的值,请使用方括号对一个或多个索引进行切片,以获取该索引处可用的值。例如-

#!/usr/bin/python3 
list1 =  ['physics',  'chemistry',  1997,  2000] 
list2 =  [1,  2,  3,  4,  5,  6,  7  ]  
print  ("list1[0]: ", list1[0])  
print  ("list2[1:5]: ", list2[1:5])

更新清单

您可以通过在赋值运算符的左侧提供切片来更新列表的单个或多个元素,并可以使用append()方法将其添加到列表中的元素。例如-

#!/usr/bin/python3 
list =  ['physics',  'chemistry',  1997,  2000]  
print  ("Value available at index 2 : ", list[2]) 
list[2]  =  2001  
print  ("New value available at index 2 : ", list[2])

–下一节将讨论append()方法。

删除列表元素

要删除列表元素,如果您确切知道要删除的元素,则可以使用del语句。如果您不确定确切要删除哪些项目,则可以使用remove()方法。例如-

#!/usr/bin/python3 
list =  ['physics',  'chemistry',  1997,  2000]  
print  (list)  
del list[2]  
print  ("After deleting value at index 2 : ", list)

注意 -remove()方法将在后续章节中讨论。

基本清单操作

列表对+和*运算符的响应非常类似于字符串;它们在这里也意味着串联和重复,只是结果是一个新列表,而不是字符串。

实际上,列表响应了我们在上一章中对字符串使用的所有常规序列操作。

Python表达式 结果 描述
len([1, 2, 3]) 3 长度
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] 级联
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 重复
3 in [1, 2, 3] True 成员资格
for x in [1,2,3] : print (x,end = ' ') 1 2 3 迭代

索引,切片和矩阵

由于列表是序列,因此索引和切片对列表的作用与对字符串的作用相同。

假设以下输入-

L = ['C++'', 'Java', 'Python']
Python表达式 结果 描述
L[2] 'Python' 偏移量从零开始
L[-2] 'Java' 负数:从右数
L[1:] ['Java','Python'] 切片获取部分

内置列表功能和方法

Python包含以下列表函数-

序号 功能说明
1 len(list)
给出列表的总长度。
2 max(list)
从列表中返回具有最大值的项目。
3 min(list)
从列表中返回带有最小值的项目。
4 list(seq)
将元组转换为列表。
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 'maths']
print (len(list1))

list2 = list(range(5)) #creates list of numbers between 0-4
print (len(list2))

list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))

list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("min value element : ", min(list1))
print ("min value element : ", min(list2))

list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("min value element : ", min(list1))
print ("min value element : ", min(list2))

aTuple = (123, 'C++', 'Java', 'Python')
list1 = list(aTuple)
print ("List elements : ", list1)

str = "Hello World"

list2 = list(str)
print ("List elements : ", list2)

Python包括以下列表方法-

序号 方法与说明
1 list.append(obj)
将对象obj附加到列表
2 list.count(obj)
返回列表中obj出现次数的计数
3 list.extend(seq)
将seq的内容追加到列表
4 list.index(obj)
返回列表中obj出现的最低索引
5 list.insert(index,obj)
将对象obj插入偏移量索引处的列表中
6 list.pop(obj = list [-1])
从列表中删除并返回最后一个对象或obj
7 list.remove(obj)
从列表中删除对象obj
8 list.reverse()
反转列表中的对象
9 list.sort([func])
对列表的对象进行排序,如果给定,则使用compare func
#!/usr/bin/python3

list1 = ['C++', 'Java', 'Python']
list1.append('C#')
print ("updated list : ", list1)

aList = [123, 'xyz', 'zara', 'abc', 123];

print ("Count for 123 : ", aList.count(123))
print ("Count for zara : ", aList.count('zara'))

list1 = ['physics', 'chemistry', 'maths']
list2 = list(range(5))     #creates list of numbers between 0-4
list1.extend(list2)
print ('Extended List :', list1)

list1 = ['physics', 'chemistry', 'maths']
print ('Index of chemistry', list1.index('chemistry'))
print ('Index of C#', list1.index('C#'))

list1 = ['physics', 'chemistry', 'maths']
list1.insert(1, 'Biology')
print ('Final list : ', list1)

list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.pop()
print ("list now : ", list1)

list1.pop(1)
print ("list now : ", list1)

list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.remove('Biology')
print ("list now : ", list1)
list1.remove('maths')
print ("list now : ", list1)

list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.reverse()
print ("list now : ", list1)

list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.sort()
print ("list now : ", list1)

Python 3-元组

元组是有序且不可变的对象的集合。元组是序列,就像列表一样。元组和列表之间的主要区别在于,与列表不同,不能更改元组。元组使用括号,而列表使用方括号。

创建元组就像放置不同的逗号分隔值一样简单。您也可以选择将这些逗号分隔的值放在括号之间。例如-

tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"

空元组写为两个不包含任何内容的括号-

tup1 = ();

要编写包含单个值的元组,即使只有一个值,您也必须添加逗号-

tup1 = (50,)

像字符串索引一样,元组索引从0开始,并且可以对其进行切片,连接等。

访问元组中的值

要访问元组中的值,请使用方括号与一个或多个索引一起切​​片,以获取该索引处的可用值。例如-

#!/usr/bin/python3

tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )

print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])

更新元组

元组是不可变的,这意味着您无法更新或更改元组元素的值。您可以使用部分现有的元组来创建新的元组,如以下示例所示:

#!/usr/bin/python3

tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')

# Following action is not valid for tuples
# tup1[0] = 100;

# So let's create a new tuple as follows
tup3 = tup1 + tup2
print (tup3)

删除元组元素

无法删除单个元组元素。当然,将另一个元组与不想要的元素丢弃在一起并没有错。

要显式删除整个元组,只需使用del语句。例如-

#!/usr/bin/python3

tup = ('physics', 'chemistry', 1997, 2000);

print (tup)
del tup;
print ("After deleting tup : ")
print (tup)

这将产生以下结果。

注意 -引发异常。这是因为在del tup 之后,元组不再存在。

('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
   File "test.py", line 9, in <module>
      print tup;
NameError: name 'tup' is not defined

元组基本操作

元组对+和*运算符的响应非常类似于字符串;它们在这里也意味着串联和重复,只是结果是一个新的元组,而不是字符串。

实际上,元组可以响应上一章中我们在字符串上使用的所有常规序列操作。

Python表达式 结果 描述
len((1, 2, 3)) 3 长度
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) 级联
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') 重复
3 in (1, 2, 3) True 会员资格
for x in (1,2,3) : print (x, end = ' ') 1 2 3 迭代

索引,切片和矩阵

由于元组是序列,因此假设以下输入,对元组进行索引和切片的方式与对字符串进行处理的方式相同:

T=('C++', 'Java', 'Python')
Python表达式 结果 描述
T [2] 'Python' 偏移量从零开始
T [-2] 'Java' 负数:从右数
T [1:] ('Java', 'Python') 切片获取部分

没有封闭的分隔符

如以下简短示例所示,没有任何封闭的定界符是用逗号分隔的多个对象的任何集合,这些对象用逗号分隔,没有标识符号,即列表的括号,元组的括号等,默认情况下为元组。

内置元组功能

Python包含以下元组函数-

序号 功能说明
1 cmp(tuple1, tuple2)
比较两个元组的元素。
2 len(tuple)
给出元组的总长度。
3 max(tuple)
从元组返回具有最大值的项目。
4 min(tuple)
从元组返回具有最小值的项目。
5 tuple(seq)
将列表转换为元组。
#!/usr/bin/python3

tuple1, tuple2 = (123, 'xyz'), (456, 'abc')

print cmp(tuple1, tuple2)
print cmp(tuple2, tuple1)
tuple3 = tuple2 + (786,);
print cmp(tuple2, tuple3)

tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
print ("First tuple length : ", len(tuple1))
print ("Second tuple length : ", len(tuple2))

tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("Max value element : ", max(tuple1))
print ("Max value element : ", max(tuple2))

tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("min value element : ", min(tuple1))
print ("min value element : ", min(tuple2))

list1 = ['maths', 'che', 'phy', 'bio']
tuple1 = tuple(list1)
print ("tuple elements : ", tuple1)

Python 3-字典

每个键都由一个冒号(:)与其值分隔,各项目之间以逗号分隔,并且整个内容都用花括号括起来。一个没有任何项目的空字典仅用两个大括号书写,例如:{}。

键在字典中是唯一的,而值可能不是。字典的值可以是任何类型,但是键必须是不可变的数据类型,例如字符串,数字或元组。

在字典中访问值

要访问字典元素,您可以使用熟悉的方括号和键来获取其值。以下是一个简单的例子-

#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])

如果我们尝试使用不是字典一部分的键来访问数据项,则会出现如下错误:

#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print ("dict['Alice']: ", dict['Alice'])

更新字典

您可以通过添加新条目或键值对,修改现有条目或删除现有条目来更新字典,如下面的简单示例所示。

#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School" # Add new entry

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

删除字典元素

您可以删除单个词典元素,也可以清除词典的全部内容。您也可以通过单个操作删除整个词典。

要显式删除整个字典,只需使用del语句。以下是一个简单的例子-

#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

del dict['Name'] # remove entry with key 'Name'
dict.clear()     # remove all entries in dict
del dict         # delete entire dictionary

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

这将产生以下结果。

出现异常是因为在del dict之后,字典不再存在。

dict['Age']:
Traceback (most recent call last):
   File "test.py", line 8, in <module>
      print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable

注意 -del()方法将在后续部分中讨论。

字典键的属性

字典值没有限制。它们可以是任意的Python对象,可以是标准对象或用户定义的对象。但是,对于密钥来说并非如此。

关于字典键,有两点要记住-

(a)每个密钥不允许输入多个。这意味着不允许重复的密钥。如果在分配过程中遇到重复的键,则以最后一个分配为准。例如-

#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print ("dict['Name']: ", dict['Name'])

(b)键必须是不变的。这意味着您可以使用字符串,数字或元组作为字典键,但是不允许使用['key']之类的东西。以下是一个简单的例子-

#!/usr/bin/python3

dict = {['Name']: 'Zara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])

内置词典功能和方法

Python包含以下字典函数-

序号 功能说明
1 cmp(dict1,dict2)
在Python 3中不再可用。
2 len(dict)
给出字典的总长度。这将等于字典中的项目数。
3 str(dict)
产生字典的可打印字符串表示形式
4 type(variable)
返回传递的变量的类型。如果传递的变量是字典,则它将返回字典类型。

Python包括以下字典方法-

序号 方法与说明
1 dict.clear()
删除字典字典的所有元素
2 dict.copy()
返回字典字典的浅表副本
3 dict.fromkeys()
使用seq中的键并将value 设置value创建一个新的字典。
4 dict.get(key,default = None)
对于,返回值或默认值(如果键不在字典中)
5 dict.has_key(key)
删除后,改用in操作。
6 dict.items()
返回dict(键,值)元组对的列表
7 dict.keys()
返回字典字典键的列表
8 dict.setdefault(key, default = None)
与get()类似,但是如果key不在dict中,它将设置dict [key] =默认
9 dict.update(dict2)
将字典dict2的键值对添加到dict
10 dict.values()
返回字典字典值列表
#!/usr/bin/python3

dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = {'Name': 'Mahnaz', 'Age': 27};
dict3 = {'Name': 'Abid', 'Age': 27};
dict4 = {'Name': 'Zara', 'Age': 7};
print "Return Value : %d" %  cmp (dict1, dict2)
print "Return Value : %d" %  cmp (dict2, dict3)
print "Return Value : %d" %  cmp (dict1, dict4)

dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
print ("Length : %d" % len (dict))

dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
print ("Equivalent String : %s" % str (dict))

dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
print ("Variable Type : %s" %  type (dict))

dict = {'Name': 'Zara', 'Age': 7}
print ("Start Len : %d" %  len(dict))

dict.clear()
print ("End Len : %d" %  len(dict))

dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
dict2 = dict1.copy()
print ("New Dictionary : ",dict2)

seq = ('name', 'age', 'sex')

dict = dict.fromkeys(seq)
print ("New Dictionary : %s" %  str(dict))

dict = dict.fromkeys(seq, 10)
print ("New Dictionary : %s" %  str(dict))

dict = {'Name': 'Zara', 'Age': 27}

print ("Value : %s" %  dict.get('Age'))
print ("Value : %s" %  dict.get('Sex', "NA"))

dict = {'Name': 'Zara', 'Age': 7}

print ("Value : %s" %  dict.has_key('Age'))
print ("Value : %s" %  dict.has_key('Sex'))

dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" %  dict.items())

dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" %  dict.items())

dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" %  dict.keys())

dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" %  dict.setdefault('Age', None))
print ("Value : %s" %  dict.setdefault('Sex', None))
print (dict)

dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }

dict.update(dict2)
print ("updated dict : ", dict)

dict = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}
print ("Values : ",  list(dict.values()))

Python 3 - Date & Time

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266