Python是一门脚本语言,我也久闻大名,但正真系统的接触学习是在去年(2013)年底到今年(2014)年初的时候。不得不说的是Python的官方文档相当齐全,如果你是在Windows上学习Python,安装包自带的“Python Manuals”就是一份很好的学习资料(基本上不用去找其他资料了);尤其是其中的Tutorial,非常适合初学者。本文一方面总结了python语言的核心——数据类型和控制结构;另一方面,通过与其他语言的对比表达了我对Python的一些拙见。

数据类型

Python简洁的背后是因为有着强大的类型系统的支持。Python世界的基本数据类型有{int, long, float, complex, str, list, set, tuple, dict},下面通过Python解释器在交互模式下的输入输出实例进行演示(其中有前导符>>>或...的是输入):
tips: Python世界里,可以用type(x)来输出x的类型.

int, long, float, str, complex

  1. >>> type(123)
  2. <type 'int'>
  3. >>> type(-234)
  4. <type 'int'>
  5. >>> type(123456123456)
  6. <type 'long'>
  7. >>> type(-123456123456)
  8. <type 'long'>
  9. >>> type(123.456)
  10. <type 'float'>
  11. >>> type('abc')
  12. <type 'str'>
  13. >>> type("hello, world")
  14. <type 'str'>
从最后两次输入可以看到Python的字符串可以用单引号也可以用双引号。另外,大家可能会疑惑的是到底多大是int和多大是long呢?下面我们来一探究竟:
  1. >>> type(123456)
  2. <type 'int'>
  3. >>> type(123456789)
  4. <type 'int'>
  5. >>> type(1234567890)
  6. <type 'int'>
  7. >>> type(12345678901)
  8. <type 'long'>

可以看到1234567890还是int,12345678901就是long了,说明int是有范围的。记得C/C++的int长度(4B)的同学都知道,C/C++里int的取值范围是:[-2^31, 2^31-1]也就是[-2147483648, 2147483647]。据此,我们可以看看Python的int范围:

  1. >>> type(2147483647)
  2. <type 'int'>
  3. >>> type(2147483648)
  4. <type 'long'>
  5. >>> type(-2147483648)
  6. <type 'int'>
  7. >>> type(-2147483649)
  8. <type 'long'>

这次试验说明,Python的int范围和C/C++一样。(事实上和long一样,这里只是因为运行的是32位的python解释器,如果是64位python解释器,int是8字节)

那么,如果我想指定一个比较小的long怎么办呢?可以通过加L(或小写l)后缀:
  1. >>> type(1L)
  2. <type 'long'>
  3. >>> type(2l)
  4. <type 'long'>
另外,Python的浮点数是没有double的:
  1. >>> type(123.456)
  2. <type 'float'>
  3. >>> type(123456123456.123456123456123456123456)
  4. <type 'float'>

complex(复数)

复数类型在很多语言中是没有的,Python通过整数加J(或小写j)后缀表示复数:
  1. >>> type(3+4j)
  2. <type 'complex'>
  3. >>> type(3+4J)
  4. <type 'complex'>
  5. >>> type(4j)
  6. <type 'complex'>
  7. >>> type(j)
  8. Traceback (most recent call last):
  9. File "<stdin>", line 1, in <module>
  10. NameError: name 'j' is not defined
  11. >>> type(1j)
  12. <type 'complex'>

但是1j不允许直接写成j,j会被当做name查找,如果没找到就会报错。


tuple, list, set, dict

tuple, list, set, dict分别是元组、列表、集合、字典(有的语言叫映射map)。这些类型才是Python类型系统的过人之处,在多数编译型语言(C、C++、Java、C#等)中,这些类型都要通过库来提供(如C++、Java、C#),有的或许库也没有提供(如C)。
  1. >>> type([1, 2, 3])
  2. <type 'list'>
  3. >>> type({2, 3, 4})
  4. <type 'set'>
  5. >>> type((3, 4, 5))
  6. <type 'tuple'>
  7. >>> type({'key1': 'value1', 'key2': 'value2'})
  8. <type 'dict'>

可以看到(), [], {}和它括起来的一系列元素,分别是表示:元组、列表、集合。而dict则是{key1: value1, [key2: value2, ...]}的形式。

上面列出的各种集合的元素类型一致,这在编译型语言里通常是必须的,但在Python里不必:
  1. >>> (1, 'two', 3.0)
  2. (1, 'two', 3.0)
  3. >>> [(1, 'two', 3.0), '4', 5]
  4. [(1, 'two', 3.0), '4', 5]
  5. >>> {1, 2L, 3.0, 4j}
  6. set([1, 2L, 3.0, 4j])
  7. >>> {1: 'one', 'one': 1}
  8. {1: 'one', 'one': 1}

控制结构

结构化程序设计方法提出之时,就有前辈证明了任何算法都可以使用:顺序、选择、循环三种结构表达。下面将展示Python的基本语法,以及选择和循环。

顺序结构

顺序结构本身没什么好说的,这里介绍一下Python的其他特性。

语句

Python的语句以换行符结尾(不像C家族的分号结尾):
  1. >>> print "hello, world"
  2. hello, world

并且Python程序没有所谓的“入口”,这和多数脚本语言类似。


弱类型

Python是弱类型的,也就是变量的类型不是一成不变的。这也和很多脚本语言类似。
  1. >>> a = 123
  2. >>> b = "asdf"
  3. >>> c = [3, 4, 5]
  4. >>> a
  5. 123
  6. >>> b
  7. 'asdf'
  8. >>> c
  9. [3, 4, 5]
  10. >>> a = b
  11. >>> b
  12. 'asdf'
这段交互中有两点与C语言(C++等)不同:
  1. 使用变量前不用向提前声明变量的类型
  2. 一个变量初始化为一个类型后还能给他赋其他类型的值
提示:在Python解释器的交互模式下直接输入变量名也能显示变量的值
“变量”一词在Python里应该叫“名字”(或者符号)更确切,在Python中你可以给一个符号赋予任何类型的值。稍后你将会看到可以给原本赋值为int的对象赋值为一个函数,一个类。

函数

Python的函数定义以def开始,如果有返回值需要用return传递返回值。
比如如下代码定义了一个名为sayHello的函数,并用'Jack'为参数进行了一次调用:
  1. def sayHello(name):
  2. print 'Hello, ' + name + '!'
  3.  
  4. sayHello('Jack')

这段代码的运行结果为:Hello, Jack!

(可将这段代码保存为sayHello.py,然后在对应目录运行python sayHello.py)

Python的类定义以class开始,属性可以在class下方声明也可以在__init__方法里通过self.xxx隐式声明。
先来一段最简单的关于类的代码:
  1. class Man:
  2. def __init__(self, name):
  3. self.name = name
  4.  
  5. def hello(self):
  6. print 'Hello, ' + self.name + '!'
  7.  
  8. m = Man('Jack')
  9. m.hello()

这段代码也会输出:Hello, Jack!

tips: Python方法的第一个参数必须是名为self的参数,用于操作对象的成员。__init__类似其他语言的”构造方法“。

类的更多特性和OOP有关,以后有时间再单独发一篇博文展示。

顺便看看函数、类以及类的实例在Python解释器眼中都是什么:
  1. >>> type(sayHello)
  2. <type 'function'>
  3. >>> type(Man)
  4. <type 'classobj'>
  5. >>> type(m)
  6. <type 'instance'>
  7. >>> type(m.hello)
  8. <type 'instancemethod'>
  9. >>> type(Man.hello)
  10. <type 'instancemethod'>

可以想象,Python世界里的东西都是”灰色“的,解释器对它们”一视同仁“,从来不以貌取人,只看他们现在身上的标签是什么~


选择结构

Python的选择结构以if开始。

bool

if必然要涉及bool值,Python bool的取值为True和False:
  1. >>> type(1==1)
  2. <type 'bool'>
  3. >>> type(True)
  4. <type 'bool'>
  5. >>> type(False)
  6. <type 'bool'>
(上面好像忘了列出bool类型)

对于Number(int, long, float, complex),0在if条件上也是False:

  1. >>> if 1:
  2. ... print "true"
  3. ...
  4. true
  5. >>> if 0:
  6. ... print "true"
  7. ... else:
  8. ... print "false"
  9. ...
  10. false
  11. >>> if 0.0:
  12. ... print "0.0 is true"
  13. ...
  14. >>> if 0j:
  15. ... print "0j is true"
  16. ...

提示:Python是以代码缩进区分代码块的

除此之外,空的string和空的集合(tuple, list, set)也是False:

  1. >>> if '':
  2. ... print 'null string is true'
  3. ...
  4. >>> if ():
  5. ... print 'null tuple is true'
  6. ...
  7. >>> if []:
  8. ... print 'null list is true'
  9. ...
  10. >>> if {}:
  11. ... print 'null set is true'
  12. ...

if, if-else & if-elif-else

上面几个if示例多是只有一个分支的,当然Python也支持多个分支的if:
  1. >>> x = int(raw_input("Please enter an integer: "))
  2. Please enter an integer: 42
  3. >>> if x < 0:
  4. ... x = 0
  5. ... print 'Negative changed to zero'
  6. ... elif x == 0:
  7. ... print 'Zero'
  8. ... elif x == 1:
  9. ... print 'Single'
  10. ... else:
  11. ... print 'More'
  12. ...
  13. More

循环结构

Python的循环有for和while两种,没有do-while,也没有loop-until。

for

Python的for循环和C的不同,它更像C++,Java里的新式for循环:
  1. >>> a = [1, 'two', 3.0]
  2. >>> for i in a:
  3. ... print i
  4. ...
  5. 1
  6. two
  7. 3.0

这种for迭代集合很方便。


但是要想像典型C语言的for循环那样迭代一个整数区间怎么办?别怕,Python提供了内置(built-in)函数range(),它能返回整数区间列表,供你迭代,用起来也很方便:
  1. >>> for i in range(1, 6):
  2. ... print i
  3. ...
  4. 1
  5. 2
  6. 3
  7. 4
  8. 5
  9. >>> for i in range(10, 65, 10):
  10. ... print i
  11. ...
  12. 10
  13. 20
  14. 30
  15. 40
  16. 50
  17. 60

这里展示了range的两种调用形式,一种是range(a, b),它将返回一个从a(包含a)到b(不包含)的整数列表(list),另一种range(a, b, s),将返回一个a~b,以s为步长的list:

  1. >>> range(1, 6)
  2. [1, 2, 3, 4, 5]
  3. >>> range(10, 65, 10)
  4. [10, 20, 30, 40, 50, 60]

while

Python的while循环和C的while差不多:
  1. >>> i = 1
  2. >>>
  3. >>> while i < 5:
  4. ... i = i+1
  5. ... print i
  6. ...
  7. 2
  8. 3
  9. 4
  10. 5

顺便一提,Python里 i=i+1 不能写成i++,Python不支持这种语法;但可以写成 i += 1:

  1. >>> i
  2. 5
  3. >>> i += 1
  4. >>> i
  5. 6
  6. >>> i++
  7. File "<stdin>", line 1
  8. i++
  9. ^
  10. SyntaxError: invalid syntax
  11. >>> ++i
  12. 6
  13. >>> i
  14. 6

各位可能会疑惑,为什么++i可以?因为pyhon支持前置的+(正负号)运算,++被当做两次正运算了;同理,+++i,++++i都是一样的;我们可以顺便测一下负号运算:

  1. >>> i
  2. 6
  3. >>> +++i
  4. 6
  5. >>> ++++i
  6. 6
  7. >>> -i
  8. -6
  9. >>> --i
  10. 6
  11. >>> ---i
  12. -6

和想象的结果一致,Great!

输入输出(IO)

当你想动手写点”更有意思“的小程序的时候,你会发现除了三大基本控制结构和数据类型之外,你最需要的可能就是IO功能。
Q: 输出可以用print,那么输入呢?是input吗?
A:input可以,但更多时候需要用的可能是raw_input和readline这两个built-in function,但readline仅适用于Unix平台.
Q:那么input和raw_input有什么区别呢?
A:来看看我和解释器的下面这段交互,看看你能不能自己发现它们的不同。
  1. >>> varA = raw_input('please input:')
  2. please input:Life is too short, you need Python!
  3. >>> varA
  4. 'Life is too short, you need Python!'
  5. >>> type(raw_input('input something:'))
  6. input something:asdf
  7. <type 'str'>
  8. >>> type(raw_input('input something:'))
  9. input something:123
  10. <type 'str'>

A:你看到了,raw_input不论你输入什么都会返回str类型,这也是为什么叫做raw_input的原因。

A: 继续往下,你会看到input:
  1. >>> type(input('input sth:'))
  2. input sth:123
  3. <type 'int'>
  4. >>> type(input('input sth:'))
  5. input sth:asdf
  6. Traceback (most recent call last):
  7. File "<stdin>", line 1, in <module>
  8. File "<string>", line 1, in <module>
  9. NameError: name 'asdf' is not defined
  10. >>> type(input('input sth:'))
  11. input sth:varA
  12. <type 'str'>
  13. >>> input('sth:')
  14. sth:varA
  15. 'Life is too short, you need Python!'
  16. >>> input('try some input like your code:')
  17. try some input like your code:[1, 'two', 3.0]
  18. [1, 'two', 3.0]
  19. >>> input('try again:')
  20. try again:'Oh!!!'
  21. 'Oh!!!'
Q: Oh, I know! input会按代码的形式解释输入!
A: 嗯,你提到了”解释“,看来你已经悟出了Python的真谛,你可以下山了!
Q: Master, 这样就可以了么?我知道的好像太少了吧?
A: 为师这里有一本《Python秘籍》,你拿去吧,所有问题你都能找到答案,但答案未必在这本书里
(徒儿A就此辞别师父Q,开始了他的Python之旅)

后记(我的拙见)

Python是解释型语言,它的类型系统非常强大!作为一个学了几门C家族语言(C、C++、Java、C#)的我来说,tuple,list,set,dict都是内置类型,简直是太美好了!
在我看来:
1.由于有语言级的tuple, list, set, dict,Python非常适合用来写算法,而且Python写出的算法必然要比其他语言简洁得多!
2.Python的语法简洁易懂,默认提供了文件管理等功能,可以替代多数其他脚本的工作。
3.Python的弱类型(约束少)以及解释器交互模式的趣味性和便捷性,非常适合作为”第一门程序设计语言“,教授少年儿童。

Python 30分钟入门——数据类型 and 控制结构的更多相关文章

  1. Python 30分钟入门——数据类型 &amp; 控制结构

    Python是一门脚本语言,我也久闻大名,但正真系统的接触学习是在去年(2013)年底到今年(2014)年初的时候.不得不说的是Python的官方文档相当齐全,假设你是在Windows上学习Pytho ...

  2. Python 30分钟入门指南

    Python 30分钟入门指南 为什么 OIer 要学 Python? Python 语言特性简洁明了,使用 Python 写测试数据生成器和对拍器,比编写 C++ 事半功倍. Python 学习成本 ...

  3. Python 30分钟快速入门指南

    学习地址 中文版:Python 30分钟入门指南 英文版:Learn X in Y minutes 学习时间 2019/03/10 19:00 - 19:32,多用了2分钟.

  4. Shell脚本编程30分钟入门

    Shell脚本编程30分钟入门 转载地址: Shell脚本编程30分钟入门 什么是Shell脚本 示例 看个例子吧: #!/bin/sh cd ~ mkdir shell_tut cd shell_t ...

  5. Objective-C 30分钟入门教程

    Objective-C 30分钟入门教程 我第一次看OC觉得这个语言的语法有些怪异,为什么充满了@符号,[]符号,函数调用没有()这个,但是面向对象的高级语言也不外乎类,接口,多态,封装,继承等概念. ...

  6. 30分钟入门Java8之方法引用

    30分钟入门Java8之方法引用 前言 之前两篇文章分别介绍了Java8的lambda表达式和默认方法和静态接口方法.今天我们继续学习Java8的新语言特性--方法引用(Method Referenc ...

  7. 30分钟入门Java8之默认方法和静态接口方法

    30分钟入门Java8之默认方法和静态接口方法 前言 上一篇文章30分钟入门Java8之lambda表达式,我们学习了lambda表达式.现在继续Java8新语言特性的学习,今天,我们要学习的是默认方 ...

  8. 【原创】30分钟入门 github

    很久没更新了,这篇文章重点在github的入门使用,读者可以下载github for windows shell,边看边操作,加深印象. 好了,30分钟的愉快之旅开始吧: 一.github使用的注意事 ...

  9. 正则表达式30分钟入门教程<转载>

    来园子之前写的一篇正则表达式教程,部分翻译自codeproject的The 30 Minute Regex Tutorial. 由于评论里有过长的URL,所以本页排版比较混乱,推荐你到原处查看,看完了 ...

随机推荐

  1. jQuery 事件方法

    事件方法触发器或添加一个函数到被选元素的事件处理程序. 下面的表格列出了所有用于处理事件的 jQuery 方法. 方法 描述 bind() 向匹配元素附加一个或更多事件处理器 blur() 触发.或将 ...

  2. Java学习笔记(一)

    纯属个人学习笔记,有什么不足之处大家留言,谢谢 Java程序打包与JAR运行方法 在Eclipse的"包资源管理器"视图中找到要打包成JAR文件的项目.在项目名称上单击鼠标右键,在 ...

  3. django 进阶篇

    models(模型) 创建数据库,设计表结构和字段 使用 MySQLdb 来连接数据库,并编写数据访问层代码 业务逻辑层去调用数据访问层执行数据库操作 import MySQLdb def GetLi ...

  4. github拉取和推送

    登入github 创建一个开源项目 然后打开安装好的git 首先进入一个指定的文件夹 例如: 1)E:\>cd miaov/testGit 回车 进入E盘的testGit文件夹 2)E:\mia ...

  5. JS,删除数据时候,多次确认后才删除。

    function delfun(){ if(window.confirm("请仔细核对无误,删除本数据后不能恢复.")){ if(window.confirm("请再次确 ...

  6. webapi-crud

  7. TTTAttributedLabel 富文本小记

    - (void)setupTipsLabel:(TTTAttributedLabel *)label { UIColor *red = [UIColor mainColor]; UIColor *gr ...

  8. 6. web前端开发分享-css,js移动篇

    随着移动市场的逐步扩大及相关技术的日趋完善,对前端开发提出了新的岗位要求,在继承前人成果的基础上需要在新的历史条件下有新的创新.移动端的开发,虽然没有IE6众多问题的折磨,但是多平台,多设备的兼容,也 ...

  9. SQL Server群集如何在线检测

    SQL Server群集知识介绍 Windows群集安装 基于iSCSI的SQL Server 2012群集测试 前言 群集的检测是调用dll资源,例如对于共享存储,ip,网络名称与DTC 这类Win ...

  10. fedora配置163为yum的源

    一种方法: 1.下载  http://mirrors.163.com/.help/fedora-163.repo 和 http://mirrors.163.com/.help/fedora-updat ...