码迷,mamicode.com
首页 > 编程语言 > 详细

快速入门:十分钟学会Python

时间:2016-12-30 10:11:34      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:version   元组   tin   title   swap   line   sig   调用   实现   


初试牛刀    

       假设你希望学习Python这门语言,却苦于找不到一个简短而全面的入门教程。那么本教程将花费十分钟的时间带你走入Python的大门。本文的内容介于教程(Toturial)和速查手册(CheatSheet)之间,因此只会包含一些基本概念。很显然,如果你希望真正学好一门语言,你还是需要亲自动手实践的。在此,我会假定你已经有了一定的编程基础,因此我会跳过大部分非Python语言的相关内容。本文将高亮显示重要的关键字,以便你可以很容易看到它们。另外需要注意的是,由于本教程篇幅有限,有很多内容我会直接使用代码来说明加以少许注释。

Python的语言特性

       Python是一门具有强类型(即变量类型是强制要求的)、动态性、隐式类型(不需要做变量声明)、大小写敏感(var和VAR代表了不同的变量)以及面向对象(一切皆为对象)等特点的编程语言。

获取帮助

       你可以很容易的通过Python解释器获取帮助。如果你想知道一个对象(object)是如何工作的,那么你所需要做的就是调用help(<object>)!另外还有一些有用的方法,dir()会显示该对象的所有方法,还有<object>.__doc__会显示其文档:

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. a=help(dir) #获取帮助信息
  4. b=dir(help) #列出方法
  5. print(a)
  6. print(b)
输出结果如下:
  1. Help on built-in function dir in module builtins:
  2. dir(...)
  3. dir([object]) -> list of strings
  4. If called without an argument, return the names in the current scope.
  5. Else, return an alphabetized list of names comprising (some of) the attributes
  6. of the given object, and of attributes reachable from it.
  7. If the object supplies a method named __dir__, it will be used; otherwise
  8. the default dir() logic is used and returns:
  9. for a module object: the module‘s attributes.
  10. for a class object: its attributes, and recursively the attributes
  11. of its bases.
  12. for any other object: its attributes, its class‘s attributes, and
  13. recursively the attributes of its class‘s base classes.
  14. None
  15. [‘__call__‘, ‘__class__‘, ‘__delattr__‘, ‘__dict__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__le__‘, ‘__lt__‘, ‘__module__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘__weakref__‘]
  16. Process finished with exit code 0

语法

      Python中没有强制的语句终止字符,且代码块是通过缩进来指示的。缩进表示一个代码块的开始,逆缩进则表示一个代码块的结束。声明以冒号(:)字符结束,并且开启一个缩进级别。单行注释以井号字符(#)开头,多行注释则以多行字符串的形式出现。赋值(事实上是将对象绑定到名字)通过等号(“=”)实现,双等号(“==”)用于相等判断,”+=”和”-=”用于增加/减少运算(由符号右边的值确定增加/减少的值)。这适用于许多数据类型,包括字符串。你也可以在一行上使用多个变量。例如:

  1. >>> myvar = 3
  2. >>> myvar += 2
  3. >>> myvar
  4. 5
  5. >>> myvar -= 1
  6. >>> myvar
  7. 4
  8. """This is a multiline comment.
  9. The following lines concatenate the two strings."""
  10. >>> mystring = "Hello"
  11. >>> mystring += " world."
  12. >>> print mystring
  13. Hello world.
  14. # This swaps the variables in one line(!).
  15. # It doesn‘t violate strong typing because values aren‘t
  16. # actually being assigned, but new objects are bound to
  17. # the old names.
  18. >>> myvar, mystring = mystring, myvar

数据类型

       Python具有列表(list)、元组(tuple)和字典(dictionaries)三种基本的数据结构,而集合(sets)则包含在集合库中(但从Python2.5版本开始正式成为Python内建类型)。列表的特点跟一维数组类似(当然你也可以创建类似多维数组的“列表的列表”),字典则是具有关联关系的数组(通常也叫做哈希表),而元组则是不可变的一维数组(Python中“数组”可以包含任何类型的元素,这样你就可以使用混合元素,例如整数、字符串或是嵌套包含列表、字典或元组)。数组中第一个元素索引值(下标)为0,使用负数索引值能够从后向前访问数组元素,-1表示最后一个元素。数组元素还能指向函数。来看下面的用法:

  1. >>> sample = [1, ["another", "list"], ("a", "tuple")]
  2. >>> mylist = ["List item 1", 2, 3.14]
  3. >>> mylist[0] = "List item 1 again" # We‘re changing the item.
  4. >>> mylist[-1] = 3.21 # Here, we refer to the last item.
  5. >>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
  6. >>> mydict["pi"] = 3.15 # This is how you change dictionary values.
  7. >>> mytuple = (1, 2, 3)
  8. >>> myfunction = len
  9. >>> print (myfunction(mylist)) #相当于print(len(mylist))
  10. 3

       你可以使用:运算符访问数组中的某一段,如果:左边为空则表示从第一个元素开始,同理:右边为空则表示到最后一个元素结束。负数索引则表示从后向前数的位置(-1是最后一个项目),例如:

  1. >>> mylist = ["List item 1", 2, 3.14]
  2. >>> print mylist[:]
  3. [‘List item 1‘, 2, 3.1400000000000001]
  4. >>> print mylist[0:2]
  5. [‘List item 1‘, 2]
  6. >>> print mylist[-3:-1]
  7. [‘List item 1‘, 2]
  8. >>> print mylist[1:]
  9. [2, 3.14]
  10. # Adding a third parameter, "step" will have Python step in
  11. # N item increments, rather than 1.
  12. # E.g., this will return the first item, then go to the third and
  13. # return that (so, items 0 and 2 in 0-indexing).
  14. >>> print mylist[::2]
  15. [‘List item 1‘, 3.14]

字符串

         Python中的字符串使用单引号(‘)或是双引号(“)来进行标示,并且你还能够在通过某一种标示的字符串中使用另外一种标示符(例如 “He said ‘hello’.”)。而多行字符串可以通过三个连续的单引号(”’)或是双引号(“”")来进行标示。Python可以通过u”This is a unicode string”这样的语法使用Unicode字符串。如果想通过变量来填充字符串,那么可以使用取模运算符(%)和一个元组。使用方式是在目标字符串中从左至右使用%s来指代变量的位置,或者使用字典来代替,示例如下:

  1. print ("This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}) #相当于print("this %s a %s"%("is","test"))
  2. This is a test.    #打印结果

流程控制

       Python中可以使用if、for和while来实现流程控制。Python中并没有select,取而代之使用if来实现。使用for来枚举列表中的元素。如果希望生成一个由数字组成的列表,则可以使用range(<number>)函数。以下是这些声明的语法示例:




            






快速入门:十分钟学会Python

标签:version   元组   tin   title   swap   line   sig   调用   实现   

原文地址:http://www.cnblogs.com/wanghui1991/p/6235746.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!