第一章 简单例子与常用数据类型
1. 程序入门必见的hello 程序
使用的IDE3.4 软件的编程,代码简单如下:
print(“hello aiyq195”)
执行的结果如下:
Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
Python 3.4.4(v3.4.4:737efcadf5a6,2015年12月20日,20:20:57)(MSC v。在win32 1600 64位(AMD64)]输入“版权”、“信用”或“许可证()”的更多信息。
>>> print("hello aiyq195")
hello aiyq195
上面这个就简单的一句话,就可以显示出你要打印出的内容;
它不像c语言,需要定义什么头文件,也不需要定义什么主函数来,就这么简单的一句,print(“回显数据”);而且句子后面也不用分号去分开;
就OK了;
1.1 输出函数 print()
在python 3 版本中,你可以在print 后面不跟()。直接跟上你要输出的内容,但是在python中,你就需要在后面跟上(),但是,在python 2 你输入()也是没错的,所以,最好的就是直接跟上()
例子:
Python 3.4版本:
>>> print("hello aiyq195")
hello aiyq195
>>> print "hello aiyq195"
SyntaxError: Missing parentheses in call to 'print'
Python 2.7版本:
aiyq195@aiyq195-virtual-machine:~$ python
Python 2.7.3 (default, Sep 26 2012, 21:53:58)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello world"
hello world
>>> print ("hello world")
hello world
看上面的内容就明白了,用print函数时,为了防止因为版本问题,直接使用print() 更好点;
1.2 输入函数 input()
input() 函数,是让用户可以输入自己想要输入的数据:
>>> name = input("what is your name?\n")
what is your name?
aiyq195
>>> name
'aiyq195'
>>> cr = input("enter a number!\n")
enter a number!
7
>>> cr
'7'
其中,还有一些内容,就是关于python 2 的版本中,还有一个输入函数raw_input(),其中的差距,看下面的内容:
http://www.cnblogs.com/aiyq195/p/6511139.html
但是,上面的两个函数,使用哪个,就需要自己在考虑在那个版本下执行了!
2. 常见的类型
Python 中类型很多,杂七杂八的类型,其中包括了:
a) 字符
b) 字符串
c) 布尔类型
d) 整数
e) 数字
f) 浮点数
g) 列表
h) 元组
i) 字典
j) 日期
在python中,没有声明这一个说法,他是直接定义,赋值成什么,他就是什么类型了;
下面开始简单整理一下上面的几种类型:
2.1 字符与字符串
如何在python中定义字符串
2.1.1 使用单引号(’)
使用单引号只能代表一些简单的字符串,如果其中含有一些特殊的符号时,会出现错误,如:
>>> str = 'nihao aiyq195'
>>> str
'nihao aiyq195'
>>> str = 'let's go'
SyntaxError: invalid syntax
2.1.2 使用双引号(”)
>>> str = "let's go"
>>> str
"let's go"
2.1.3 使用多引号(”””)
使用多引号,可以表示多行的字符串,也就是说,如果你想同时,显示多行的数据,那你就需要使用多引号来标注,如:
>>> str = """nihao aiyq195,
what is you ages!"
"""
>>> str
'nihao aiyq195,\nwhat is you ages!"\n'
其中的\n就是代表的换行符!
2.1.4 字符串的函数
find 方法
find 方法可以在一个较长的字符串中查找子串,它返回子串所在位置的最左端索引,如果没有找到则返回-1。
>>> cr = "nihao aiyq195"
>>> cr.find("aiyq")
6
>>> lis