Python 30分钟入门——数据类型 & 控制结构
Python是一门脚本语言,我也久闻大名,但正真系统的接触学习是在去年(2013)年底到今年(2014)年初的时候。不得不说的是Python的官方文档相当齐全,假设你是在Windows上学习Python,安装包自带的“Python Manuals”就是一份非常好的学习资料(基本上不用去找其它资料了);尤其是当中的Tutorial,非常适合刚開始学习的人。本文一方面总结了python语言的核心——数据类型和控制结构;还有一方面,通过与其它语言的对照表达了我对Python的一些拙见。
数据类型
int, long, float, str, complex
>>> type(123)
<type 'int'>
>>> type(-234)
<type 'int'>
>>> type(123456123456)
<type 'long'>
>>> type(-123456123456)
<type 'long'>
>>> type(123.456)
<type 'float'>
>>> type('abc')
<type 'str'>
>>> type("hello, world")
<type 'str'>
>>> type(123456)
<type 'int'>
>>> type(123456789)
<type 'int'>
>>> type(1234567890)
<type 'int'>
>>> type(12345678901)
<type 'long'>
能够看到1234567890还是int,12345678901就是long了,说明int是有范围的。记得C/C++的int长度(4B)的同学都知道,C/C++里int的取值范围是:[-2^31, 2^31-1]也就是[-2147483648, 2147483647]。据此,我们能够看看Python的int范围:
>>> type(2147483647)
<type 'int'>
>>> type(2147483648)
<type 'long'>
>>> type(-2147483648)
<type 'int'>
>>> type(-2147483649)
<type 'long'>
这次试验说明,Python的int范围和C/C++一样。
>>> type(1L)
<type 'long'>
>>> type(2l)
<type 'long'>
>>> type(123.456)
<type 'float'>
>>> type(123456123456.123456123456123456123456)
<type 'float'>
complex(复数)
>>> type(3+4j)
<type 'complex'>
>>> type(3+4J)
<type 'complex'>
>>> type(4j)
<type 'complex'>
>>> type(j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'j' is not defined
>>> type(1j)
<type 'complex'>
可是1j不同意直接写成j,j会被当做name查找,假设没找到就会报错。
tuple, list, set, dict
>>> type([1, 2, 3])
<type 'list'>
>>> type({2, 3, 4})
<type 'set'>
>>> type((3, 4, 5))
<type 'tuple'>
>>> type({'key1': 'value1', 'key2': 'value2'})
<type 'dict'>
能够看到(), [], {}和它括起来的一系列元素,各自是表示:元组、列表、集合。而dict则是{key1: value1, [key2: value2, ...]}的形式。
>>> (1, 'two', 3.0)
(1, 'two', 3.0)
>>> [(1, 'two', 3.0), '4', 5]
[(1, 'two', 3.0), '4', 5]
>>> {1, 2L, 3.0, 4j}
set([1, 2L, 3.0, 4j])
>>> {1: 'one', 'one': 1}
{1: 'one', 'one': 1}
控制结构
顺序结构
语句
>>> print "hello, world"
hello, world
而且Python程序没有所谓的“入口”,这和多数脚本语言类似。
弱类型
>>> a = 123
>>> b = "asdf"
>>> c = [3, 4, 5]
>>> a
123
>>> b
'asdf'
>>> c
[3, 4, 5]
>>> a = b
>>> b
'asdf'
- 使用变量前不用向提前声明变量的类型
- 一个变量初始化为一个类型后还能给他赋其它类型的值
函数
def sayHello(name):
print 'Hello, ' + name + '!' sayHello('Jack')
这段代码的执行结果为:Hello, Jack!
类
class Man:
def __init__(self, name):
self.name = name def hello(self):
print 'Hello, ' + self.name + '!' m = Man('Jack')
m.hello()
这段代码也会输出:Hello, Jack!
类的很多其它特性和OOP有关,以后有时间再单独发一篇博文展示。
>>> type(sayHello)
<type 'function'>
>>> type(Man)
<type 'classobj'>
>>> type(m)
<type 'instance'>
>>> type(m.hello)
<type 'instancemethod'>
>>> type(Man.hello)
<type 'instancemethod'>
能够想象,Python世界里的东西都是”灰色“的,解释器对它们”一视同仁“,从来不以貌取人,仅仅看他们如今身上的标签是什么~
选择结构
Python的选择结构以if開始。
bool
>>> type(1==1)
<type 'bool'>
>>> type(True)
<type 'bool'>
>>> type(False)
<type 'bool'>
对于Number(int, long, float, complex),0在if条件上也是False:
>>> if 1:
... print "true"
...
true
>>> if 0:
... print "true"
... else:
... print "false"
...
false
>>> if 0.0:
... print "0.0 is true"
...
>>> if 0j:
... print "0j is true"
...
提示:Python是以代码缩进区分代码块的
除此之外,空的string和空的集合(tuple, list, set)也是False:
>>> if '':
... print 'null string is true'
...
>>> if ():
... print 'null tuple is true'
...
>>> if []:
... print 'null list is true'
...
>>> if {}:
... print 'null set is true'
...
if, if-else & if-elif-else
>>> x = int(raw_input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print 'Negative changed to zero'
... elif x == 0:
... print 'Zero'
... elif x == 1:
... print 'Single'
... else:
... print 'More'
...
More
循环结构
for
>>> a = [1, 'two', 3.0]
>>> for i in a:
... print i
...
1
two
3.0
这样的for迭代集合非常方便。
>>> for i in range(1, 6):
... print i
...
1
2
3
4
5
>>> for i in range(10, 65, 10):
... print i
...
10
20
30
40
50
60
这里展示了range的两种调用形式,一种是range(a, b),它将返回一个从a(包括a)到b(不包括)的整数列表(list),还有一种range(a, b, s),将返回一个a~b,以s为步长的list:
>>> range(1, 6)
[1, 2, 3, 4, 5]
>>> range(10, 65, 10)
[10, 20, 30, 40, 50, 60]
while
>>> i = 1
>>>
>>> while i < 5:
... i = i+1
... print i
...
2
3
4
5
顺便一提,Python里 i=i+1 不能写成i++,Python不支持这样的语法;但能够写成 i += 1:
>>> i
5
>>> i += 1
>>> i
6
>>> i++
File "<stdin>", line 1
i++
^
SyntaxError: invalid syntax
>>> ++i
6
>>> i
6
各位可能会疑惑,为什么++i能够?由于pyhon支持前置的+(正负号)运算,++被当做两次正运算了;同理,+++i,++++i都是一样的;我们能够顺便測一下负号运算:
>>> i
6
>>> +++i
6
>>> ++++i
6
>>> -i
-6
>>> --i
6
>>> ---i
-6
和想象的结果一致,Great!
输入输出(IO)
>>> varA = raw_input('please input:')
please input:Life is too short, you need Python!
>>> varA
'Life is too short, you need Python!'
>>> type(raw_input('input something:'))
input something:asdf
<type 'str'>
>>> type(raw_input('input something:'))
input something:123
<type 'str'>
A:你看到了,raw_input不论你输入什么都会返回str类型,这也是为什么叫做raw_input的原因。
>>> type(input('input sth:'))
input sth:123
<type 'int'>
>>> type(input('input sth:'))
input sth:asdf
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'asdf' is not defined
>>> type(input('input sth:'))
input sth:varA
<type 'str'>
>>> input('sth:')
sth:varA
'Life is too short, you need Python!'
>>> input('try some input like your code:')
try some input like your code:[1, 'two', 3.0]
[1, 'two', 3.0]
>>> input('try again:')
try again:'Oh!!!'
'Oh!!!'
后记(我的拙见)
Python 30分钟入门——数据类型 & 控制结构的更多相关文章
- Python 30分钟入门——数据类型 and 控制结构
Python是一门脚本语言,我也久闻大名,但正真系统的接触学习是在去年(2013)年底到今年(2014)年初的时候.不得不说的是Python的官方文档相当齐全,如果你是在Windows上学习Pytho ...
- Python 30分钟入门指南
Python 30分钟入门指南 为什么 OIer 要学 Python? Python 语言特性简洁明了,使用 Python 写测试数据生成器和对拍器,比编写 C++ 事半功倍. Python 学习成本 ...
- Python 30分钟快速入门指南
学习地址 中文版:Python 30分钟入门指南 英文版:Learn X in Y minutes 学习时间 2019/03/10 19:00 - 19:32,多用了2分钟.
- Shell脚本编程30分钟入门
Shell脚本编程30分钟入门 转载地址: Shell脚本编程30分钟入门 什么是Shell脚本 示例 看个例子吧: #!/bin/sh cd ~ mkdir shell_tut cd shell_t ...
- Objective-C 30分钟入门教程
Objective-C 30分钟入门教程 我第一次看OC觉得这个语言的语法有些怪异,为什么充满了@符号,[]符号,函数调用没有()这个,但是面向对象的高级语言也不外乎类,接口,多态,封装,继承等概念. ...
- 30分钟入门Java8之方法引用
30分钟入门Java8之方法引用 前言 之前两篇文章分别介绍了Java8的lambda表达式和默认方法和静态接口方法.今天我们继续学习Java8的新语言特性--方法引用(Method Referenc ...
- 30分钟入门Java8之默认方法和静态接口方法
30分钟入门Java8之默认方法和静态接口方法 前言 上一篇文章30分钟入门Java8之lambda表达式,我们学习了lambda表达式.现在继续Java8新语言特性的学习,今天,我们要学习的是默认方 ...
- 【原创】30分钟入门 github
很久没更新了,这篇文章重点在github的入门使用,读者可以下载github for windows shell,边看边操作,加深印象. 好了,30分钟的愉快之旅开始吧: 一.github使用的注意事 ...
- 正则表达式30分钟入门教程<转载>
来园子之前写的一篇正则表达式教程,部分翻译自codeproject的The 30 Minute Regex Tutorial. 由于评论里有过长的URL,所以本页排版比较混乱,推荐你到原处查看,看完了 ...
随机推荐
- python命令行解析工具argparse模块【4】
上一节我们讲解了add_argument()方法,这一节我们将学习parse_args()方法. parse_args()方法的作用是解析命令行参数,并返回解析之后的 ...
- UNIX网络编程5 POSIX 消息队列
<mqueue.h> mq_open mq_close mq_unlink mq_getattr/mq_setattr mq_send/mq_receive mq_notify sigwa ...
- 腾讯QQ是用什么语言开发的(转)
腾讯QQ的部分COM组件用的VC6,用exescope看其中几个dll的依赖,依赖于MFC42.dll,MSVCRT.dll,MSVCP60.dll都说明是VC6写的. 还有一部分用的VS2005,包 ...
- POJ 2050 Searching the Web
题意简述:做一个极其简单的搜索系统,对以下四种输入进行分析与搜索: 1. 只有一个单词:如 term, 只需找到含有这个单词的document,然后把这个document的含有这个单词term的那些行 ...
- windows phone:使用sqlite-net
继上篇文章后,这里简单介绍下sqlite-net的使用(示例不为作者所写,摘自于:https://github.com/peterhuene/sqlite-net) Please consult th ...
- eclipse the user operation is waiting for building workspace" to complete
"the user operation is waiting for building workspace" to complete", 解决办法: 1.选择菜单栏的“P ...
- 用二进制方法求两个整数的最大公约数(GCD)
二进制GCD算法基本原理是: 先用移位的方式对两个数除2,直到两个数不同时为偶数.然后将剩下的偶数(如果有的话)做同样的操作,这样做的原因是如果u和v中u为偶数,v为奇数,则有gcd(u,v)=gcd ...
- Swift 版本历史记录(关注)
http://numbbbbb.gitbooks.io/-the-swift-programming-language-/content/chapter1/03_revision_history.ht ...
- VirtualBox虚拟机安装RedHat7.3编译Linux0.01内核
引子 由于需要编译linux0.01内核,而目前的linux版本太高需要降低gcc版本等等,需要做不少调整非常不方便. 所以,直接安装RedHat7.3,这样就好编译linux0.01的内核了. 但是 ...
- web前端如何让网页布局稳定性和标准性?
刚开始学css+div布局的同学们,都比较困惑和难写的就是兼容性的问题了,特别是ie6等低版本的浏览器,随意国内逐步慢慢消失取代,但是现阶段还是会有点考虑因素再里面.我们写的网页布局怎么样才是合理的, ...